_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 |
|---|---|---|---|---|---|---|---|---|
d2c14ab84a1023a2f22dc4d1df5638fb3868087d26931f660519d727c0b5b9ef | alephcloud/hs-aws-lambda | UploadFunction.hs | Copyright ( c ) 2013 - 2014 PivotCloud , Inc.
--
Aws . Lambda . Commands . UploadFunction
--
-- Please feel free to contact us at with any
-- contributions, additions, or other feedback; we would love to hear from
-- you.
--
Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may
-- not use this file except in compliance with the License. You may obtain a
-- copy of the License at -2.0
--
-- Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS , WITHOUT
-- WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-- License for the specific language governing permissions and limitations
-- under the License.
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE UnicodeSyntax #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeFamilies #
module Aws.Lambda.Commands.UploadFunction
( -- * Request
UploadFunction(..)
-- ** Lenses
, ufDescription
, ufFunctionName
, ufHandler
, ufMemorySize
, ufMode
, ufRole
, ufRuntime
, ufTimeout
, ufRawCode
, ufLastModified
) where
import Aws.Lambda.Core
import Aws.Lambda.Types
import qualified Codec.Archive.Zip as Z
import Control.Lens hiding ((<.>))
import Data.Aeson
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as LB
import qualified Data.Text as T
import Data.Time
import Data.Time.Clock.POSIX
import Network.HTTP.Types
import Prelude.Unicode
import System.FilePath
-- | Creates a new Lambda function or updates an existing function. The
-- function metadata is created from the request parameters, and the code for
-- the function is provided by a @.zip@ file in the request body. If the
-- function name already exists, the existing Lambda function is updated with
-- the new code and metadata.
--
This operation requires permission for the @lambda : UploadFunction@ action .
--
-- Note that these bindings take care of packaging up the function source code
-- as a @.zip@ file automatically.
--
data UploadFunction
= UploadFunction
{ _ufDescription ∷ !T.Text
-- ^ A short, user-defined function description. Lambda does not use this
-- value. Assign a meaningful description as you see fit.
, _ufFunctionName ∷ !T.Text
-- ^ The name you want to assign to the function you are uploading.
, _ufHandler ∷ !T.Text
^ The function that Lambda calls to begin execution . For Node.js , it is
the @module - name.export@ value in your function
, _ufMemorySize ∷ !Int
^ The amount of memory , in MB , your Lambda function is given . Lambda uses
-- this memory size to infer the amount of CPU allocated to your function.
-- Your function use-case determines your CPU and memory requirements. For
-- example, database operation might need less memory compared to image
processing function . The default value is 128 MB . The value must be a
multiple of 64 MB .
, _ufMode ∷ !FunctionMode
-- ^ How the Lambda function will be invoked.
, _ufRole ∷ !Arn
^ The Amazon Resource Name ( ARN ) of the IAM role that Lambda assumes when
it executes your function to access any other Amazon Web Services ( AWS )
-- resources.
, _ufRuntime ∷ !FunctionRuntime
-- ^ The runtime environment for the Lambda function you are uploading.
, _ufTimeout ∷ !Int
-- ^ The function execution time at which Lambda should terminate the
-- function. Because the execution time has cost implications, we recommend
you set this value based on your expected execution time . The default is 3
-- seconds.
, _ufRawCode ∷ !B.ByteString
-- ^ The raw code of the function (which will be packaged into a ZIP archive
-- automatically).
, _ufLastModified ∷ !UTCTime
-- ^ The last-modified date to be assigned to the file in the ZIP archive.
} deriving (Eq, Show)
makeLenses ''UploadFunction
newtype UploadFunctionResponse
= UploadFunctionResponse
{ _ufrConfiguration ∷ FunctionConfiguration
} deriving (Eq, Show, FromJSON)
instance LambdaTransaction UploadFunction B.ByteString UploadFunctionResponse where
buildQuery uf =
lambdaQuery' PUT ["functions", uf ^. ufFunctionName] archivedSource
& lqParams
%~ (at "Description" ?~ uf ^. ufDescription)
∘ (at "Handler" ?~ uf ^. ufHandler)
∘ (at "MemorySize" ?~ uf ^. ufMemorySize ∘ to (T.pack ∘ show))
∘ (at "Mode" ?~ uf ^. ufMode ∘ re _TextFunctionMode)
∘ (at "Role" ?~ uf ^. ufRole ∘ to arnToText)
∘ (at "Runtime" ?~ uf ^. ufRuntime ∘ re _TextFunctionRuntime)
∘ (at "Timeout" ?~ uf ^. ufTimeout ∘ to (T.pack ∘ show))
where
extension =
case uf ^. ufRuntime of
FunctionRuntimeNodeJs → "js"
archivedSource =
LB.toStrict ∘ Z.fromArchive ∘ flip Z.addEntryToArchive Z.emptyArchive $
Z.toEntry
(uf ^. ufFunctionName ∘ to T.unpack <.> extension)
(uf ^. ufLastModified ∘ to (round ∘ utcTimeToPOSIXSeconds))
(uf ^. ufRawCode ∘ to LB.fromStrict)
| null | https://raw.githubusercontent.com/alephcloud/hs-aws-lambda/df10334bf419384db254d71da06c801849571c1e/src/Aws/Lambda/Commands/UploadFunction.hs | haskell |
Please feel free to contact us at with any
contributions, additions, or other feedback; we would love to hear from
you.
not use this file except in compliance with the License. You may obtain a
copy of the License at -2.0
Unless required by applicable law or agreed to in writing, software
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations
under the License.
# LANGUAGE OverloadedStrings #
* Request
** Lenses
| Creates a new Lambda function or updates an existing function. The
function metadata is created from the request parameters, and the code for
the function is provided by a @.zip@ file in the request body. If the
function name already exists, the existing Lambda function is updated with
the new code and metadata.
Note that these bindings take care of packaging up the function source code
as a @.zip@ file automatically.
^ A short, user-defined function description. Lambda does not use this
value. Assign a meaningful description as you see fit.
^ The name you want to assign to the function you are uploading.
this memory size to infer the amount of CPU allocated to your function.
Your function use-case determines your CPU and memory requirements. For
example, database operation might need less memory compared to image
^ How the Lambda function will be invoked.
resources.
^ The runtime environment for the Lambda function you are uploading.
^ The function execution time at which Lambda should terminate the
function. Because the execution time has cost implications, we recommend
seconds.
^ The raw code of the function (which will be packaged into a ZIP archive
automatically).
^ The last-modified date to be assigned to the file in the ZIP archive. | Copyright ( c ) 2013 - 2014 PivotCloud , Inc.
Aws . Lambda . Commands . UploadFunction
Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may
distributed under the License is distributed on an " AS IS " BASIS , WITHOUT
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE UnicodeSyntax #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeFamilies #
module Aws.Lambda.Commands.UploadFunction
UploadFunction(..)
, ufDescription
, ufFunctionName
, ufHandler
, ufMemorySize
, ufMode
, ufRole
, ufRuntime
, ufTimeout
, ufRawCode
, ufLastModified
) where
import Aws.Lambda.Core
import Aws.Lambda.Types
import qualified Codec.Archive.Zip as Z
import Control.Lens hiding ((<.>))
import Data.Aeson
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as LB
import qualified Data.Text as T
import Data.Time
import Data.Time.Clock.POSIX
import Network.HTTP.Types
import Prelude.Unicode
import System.FilePath
This operation requires permission for the @lambda : UploadFunction@ action .
data UploadFunction
= UploadFunction
{ _ufDescription ∷ !T.Text
, _ufFunctionName ∷ !T.Text
, _ufHandler ∷ !T.Text
^ The function that Lambda calls to begin execution . For Node.js , it is
the @module - name.export@ value in your function
, _ufMemorySize ∷ !Int
^ The amount of memory , in MB , your Lambda function is given . Lambda uses
processing function . The default value is 128 MB . The value must be a
multiple of 64 MB .
, _ufMode ∷ !FunctionMode
, _ufRole ∷ !Arn
^ The Amazon Resource Name ( ARN ) of the IAM role that Lambda assumes when
it executes your function to access any other Amazon Web Services ( AWS )
, _ufRuntime ∷ !FunctionRuntime
, _ufTimeout ∷ !Int
you set this value based on your expected execution time . The default is 3
, _ufRawCode ∷ !B.ByteString
, _ufLastModified ∷ !UTCTime
} deriving (Eq, Show)
makeLenses ''UploadFunction
newtype UploadFunctionResponse
= UploadFunctionResponse
{ _ufrConfiguration ∷ FunctionConfiguration
} deriving (Eq, Show, FromJSON)
instance LambdaTransaction UploadFunction B.ByteString UploadFunctionResponse where
buildQuery uf =
lambdaQuery' PUT ["functions", uf ^. ufFunctionName] archivedSource
& lqParams
%~ (at "Description" ?~ uf ^. ufDescription)
∘ (at "Handler" ?~ uf ^. ufHandler)
∘ (at "MemorySize" ?~ uf ^. ufMemorySize ∘ to (T.pack ∘ show))
∘ (at "Mode" ?~ uf ^. ufMode ∘ re _TextFunctionMode)
∘ (at "Role" ?~ uf ^. ufRole ∘ to arnToText)
∘ (at "Runtime" ?~ uf ^. ufRuntime ∘ re _TextFunctionRuntime)
∘ (at "Timeout" ?~ uf ^. ufTimeout ∘ to (T.pack ∘ show))
where
extension =
case uf ^. ufRuntime of
FunctionRuntimeNodeJs → "js"
archivedSource =
LB.toStrict ∘ Z.fromArchive ∘ flip Z.addEntryToArchive Z.emptyArchive $
Z.toEntry
(uf ^. ufFunctionName ∘ to T.unpack <.> extension)
(uf ^. ufLastModified ∘ to (round ∘ utcTimeToPOSIXSeconds))
(uf ^. ufRawCode ∘ to LB.fromStrict)
|
f2b010d3f7b496e8056906515506ef6d22ca01498f167389f22cf7265800fee3 | wargrey/graphics | misc.rkt | #lang typed/racket/base
(provide (all-defined-out))
(require racket/fixnum)
(require racket/math)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-type HSB->RGB (-> Flonum Flonum Flonum (Values Flonum Flonum Flonum)))
(define-type RGB->HSB (-> Flonum Flonum Flonum (Values Flonum Flonum Flonum)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define gamut->byte : (-> Flonum Byte) (λ [r] (min (max (exact-round (* r 255.0)) 0) #xFF)))
(define byte->gamut : (-> Byte Nonnegative-Flonum) (λ [r] (real->double-flonum (/ r 255))))
(define real->gamut : (-> Real Nonnegative-Flonum) (λ [r] (max (min (real->double-flonum r) 1.0) 0.0)))
(define real->alpha : (-> Real Nonnegative-Flonum) (λ [r] (max (min (real->double-flonum r) 1.0) 0.0)))
(define gamut->uint16 : (-> Flonum Index) (λ [r] (assert (min (max (exact-round (* r 65535.0)) 0) 65535) index?)))
(define real->hue : (-> Real Nonnegative-Flonum)
(lambda [hue]
(cond [(nan? hue) +nan.0]
[(and (<= 0 hue) (< hue 360)) (real->double-flonum hue)]
[else (let ([integer-part (modulo (exact-truncate hue) 360)])
(cond [(integer? hue) (real->double-flonum integer-part)]
[(positive? hue) (max (real->double-flonum (+ integer-part (- hue (truncate hue)))) 0.0)]
[(zero? integer-part) (max (+ 360.0 (real->double-flonum (- hue (truncate hue)))) 0.0)]
[else (max (real->double-flonum (- integer-part (- (truncate hue) hue))) 0.0)]))])))
(define rgb-bytes->hex : (-> Byte Byte Byte Index)
(lambda [r g b]
(fxand #xFFFFFF
(fxior (fxlshift r 16)
(fxior (fxlshift g 8)
b)))))
(define hex->rgb-bytes : (-> Integer (Values Byte Byte Byte))
(lambda [rgb]
(values (fxand (fxrshift rgb 16) #xFF)
(fxand (fxrshift rgb 8) #xFF)
(fxand rgb #xFF))))
(define rgb-gamuts->hex : (-> Flonum Flonum Flonum Index)
(lambda [r g b]
(rgb-bytes->hex (gamut->byte r) (gamut->byte g) (gamut->byte b))))
(define hex->rgb-gamuts : (-> Integer (Values Nonnegative-Flonum Nonnegative-Flonum Nonnegative-Flonum))
(lambda [rgb]
(define-values (r g b) (hex->rgb-bytes rgb))
(values (byte->gamut r) (byte->gamut g) (byte->gamut b))))
(define rgb-bytes->hsb : (-> RGB->HSB Byte Byte Byte (Values Flonum Flonum Flonum))
(lambda [rgb->hsb red green blue]
(rgb->hsb (byte->gamut red)
(byte->gamut green)
(byte->gamut blue))))
(define hsb->rgb-bytes : (-> HSB->RGB Real Real Real (Values Byte Byte Byte))
(lambda [hsb->rgb hue s% b%]
(define-values (red green blue) (hsb->rgb (real->hue hue) (real->gamut s%) (real->gamut b%)))
(values (gamut->byte red)
(gamut->byte green)
(gamut->byte blue))))
(define rgb-hex->hsb : (-> RGB->HSB Integer (Values Flonum Flonum Flonum))
(lambda [rgb->hsb hex]
(define-values (red green blue) (hex->rgb-bytes hex))
(rgb-bytes->hsb rgb->hsb red green blue)))
(define hsb->rgb-hex : (-> HSB->RGB Real Real Real Index)
(lambda [hsb->rgb hue s% b%]
(define-values (red green blue) (hsb->rgb-bytes hsb->rgb hue s% b%))
(rgb-bytes->hex red green blue)))
| null | https://raw.githubusercontent.com/wargrey/graphics/33ef0325b50cbed3358e56c5c432522c11a348de/colorspace/misc.rkt | racket | #lang typed/racket/base
(provide (all-defined-out))
(require racket/fixnum)
(require racket/math)
(define-type HSB->RGB (-> Flonum Flonum Flonum (Values Flonum Flonum Flonum)))
(define-type RGB->HSB (-> Flonum Flonum Flonum (Values Flonum Flonum Flonum)))
(define gamut->byte : (-> Flonum Byte) (λ [r] (min (max (exact-round (* r 255.0)) 0) #xFF)))
(define byte->gamut : (-> Byte Nonnegative-Flonum) (λ [r] (real->double-flonum (/ r 255))))
(define real->gamut : (-> Real Nonnegative-Flonum) (λ [r] (max (min (real->double-flonum r) 1.0) 0.0)))
(define real->alpha : (-> Real Nonnegative-Flonum) (λ [r] (max (min (real->double-flonum r) 1.0) 0.0)))
(define gamut->uint16 : (-> Flonum Index) (λ [r] (assert (min (max (exact-round (* r 65535.0)) 0) 65535) index?)))
(define real->hue : (-> Real Nonnegative-Flonum)
(lambda [hue]
(cond [(nan? hue) +nan.0]
[(and (<= 0 hue) (< hue 360)) (real->double-flonum hue)]
[else (let ([integer-part (modulo (exact-truncate hue) 360)])
(cond [(integer? hue) (real->double-flonum integer-part)]
[(positive? hue) (max (real->double-flonum (+ integer-part (- hue (truncate hue)))) 0.0)]
[(zero? integer-part) (max (+ 360.0 (real->double-flonum (- hue (truncate hue)))) 0.0)]
[else (max (real->double-flonum (- integer-part (- (truncate hue) hue))) 0.0)]))])))
(define rgb-bytes->hex : (-> Byte Byte Byte Index)
(lambda [r g b]
(fxand #xFFFFFF
(fxior (fxlshift r 16)
(fxior (fxlshift g 8)
b)))))
(define hex->rgb-bytes : (-> Integer (Values Byte Byte Byte))
(lambda [rgb]
(values (fxand (fxrshift rgb 16) #xFF)
(fxand (fxrshift rgb 8) #xFF)
(fxand rgb #xFF))))
(define rgb-gamuts->hex : (-> Flonum Flonum Flonum Index)
(lambda [r g b]
(rgb-bytes->hex (gamut->byte r) (gamut->byte g) (gamut->byte b))))
(define hex->rgb-gamuts : (-> Integer (Values Nonnegative-Flonum Nonnegative-Flonum Nonnegative-Flonum))
(lambda [rgb]
(define-values (r g b) (hex->rgb-bytes rgb))
(values (byte->gamut r) (byte->gamut g) (byte->gamut b))))
(define rgb-bytes->hsb : (-> RGB->HSB Byte Byte Byte (Values Flonum Flonum Flonum))
(lambda [rgb->hsb red green blue]
(rgb->hsb (byte->gamut red)
(byte->gamut green)
(byte->gamut blue))))
(define hsb->rgb-bytes : (-> HSB->RGB Real Real Real (Values Byte Byte Byte))
(lambda [hsb->rgb hue s% b%]
(define-values (red green blue) (hsb->rgb (real->hue hue) (real->gamut s%) (real->gamut b%)))
(values (gamut->byte red)
(gamut->byte green)
(gamut->byte blue))))
(define rgb-hex->hsb : (-> RGB->HSB Integer (Values Flonum Flonum Flonum))
(lambda [rgb->hsb hex]
(define-values (red green blue) (hex->rgb-bytes hex))
(rgb-bytes->hsb rgb->hsb red green blue)))
(define hsb->rgb-hex : (-> HSB->RGB Real Real Real Index)
(lambda [hsb->rgb hue s% b%]
(define-values (red green blue) (hsb->rgb-bytes hsb->rgb hue s% b%))
(rgb-bytes->hex red green blue)))
| |
62f30bdddea768a5eabd9999f311a9f4654cefcc07a950e98f65e45ad2243c5d | kupl/FixML | sub2.ml | type heap = EMPTY | NODE of rank * value * heap * heap
and rank = int
and value = int
exception EmptyHeap
let rank h = match h with
| EMPTY -> -1
| NODE(r,_,_,_) -> r
let shake (x,lh,rh) =
if (rank lh) >= (rank rh)
then NODE(rank rh+1, x, lh, rh)
else NODE(rank lh+1, x, rh, lh)
let rec merge (h1, h2) =
match h1 with
EMPTY -> h2
| NODE(_,x1,lh1,rh1) ->
(match h2 with
EMPTY -> h1
| NODE(_,x2,lh2,rh2) ->
(if x1 < x2 then merge(rh1, shake(x1, lh1, h2))
else merge(rh2, shake(x2, lh2, h1)))
)
let findMin h = match h with
| EMPTY -> raise EmptyHeap
| NODE(_,x,_,_) -> x
let insert(x,h) = merge(h, NODE(0,x,EMPTY,EMPTY))
let deleteMin h = match h with
| EMPTY -> raise EmptyHeap
| NODE(_,x,lh,rh) -> merge (lh,rh)
| null | https://raw.githubusercontent.com/kupl/FixML/0a032a733d68cd8ccc8b1034d2908cd43b241fce/benchmarks/priority_queue/priority_queue/submissions/sub2.ml | ocaml | type heap = EMPTY | NODE of rank * value * heap * heap
and rank = int
and value = int
exception EmptyHeap
let rank h = match h with
| EMPTY -> -1
| NODE(r,_,_,_) -> r
let shake (x,lh,rh) =
if (rank lh) >= (rank rh)
then NODE(rank rh+1, x, lh, rh)
else NODE(rank lh+1, x, rh, lh)
let rec merge (h1, h2) =
match h1 with
EMPTY -> h2
| NODE(_,x1,lh1,rh1) ->
(match h2 with
EMPTY -> h1
| NODE(_,x2,lh2,rh2) ->
(if x1 < x2 then merge(rh1, shake(x1, lh1, h2))
else merge(rh2, shake(x2, lh2, h1)))
)
let findMin h = match h with
| EMPTY -> raise EmptyHeap
| NODE(_,x,_,_) -> x
let insert(x,h) = merge(h, NODE(0,x,EMPTY,EMPTY))
let deleteMin h = match h with
| EMPTY -> raise EmptyHeap
| NODE(_,x,lh,rh) -> merge (lh,rh)
| |
f5edd3cfd7ee5a8c9adfa149a62ea67be58716d54233352ae720c8c15e16fe73 | fendor/hsimport | ModuleTest20.hs | {-# Language PatternGuards #-}
module Blub
( blub
, foo
, bar
) where
import Ugah.Foo
import Control.Applicative
import Ugah.Blub
ddd
f :: Int -> Int
f = (+ 3)
| null | https://raw.githubusercontent.com/fendor/hsimport/9be9918b06545cfd7282e4db08c2b88f1d8162cd/tests/inputFiles/ModuleTest20.hs | haskell | # Language PatternGuards # | module Blub
( blub
, foo
, bar
) where
import Ugah.Foo
import Control.Applicative
import Ugah.Blub
ddd
f :: Int -> Int
f = (+ 3)
|
e263eb60af7bda93eec151175dbf923ba03bc5c3475551f1f8525afb53286e73 | ucsd-progsys/liquidhaskell | Sumk.hs | {-@ LIQUID "--expect-any-error" @-}
module Sumk () where
import Language.Haskell.Liquid.Prelude
m = choose 0
bot = choose 0
dsum ranjit jhala k =
if (ranjit `leq` 0)
then k jhala
else dsum (ranjit `minus` 1) (ranjit `plus` jhala) k
prop0 = dsum m bot (\x -> liquidAssertB ((m `plus` bot) `leq` x))
prop1 = liquidAssertB (1 `leq` 0)
| null | https://raw.githubusercontent.com/ucsd-progsys/liquidhaskell/f46dbafd6ce1f61af5b56f31924c21639c982a8a/tests/neg/Sumk.hs | haskell | @ LIQUID "--expect-any-error" @ | module Sumk () where
import Language.Haskell.Liquid.Prelude
m = choose 0
bot = choose 0
dsum ranjit jhala k =
if (ranjit `leq` 0)
then k jhala
else dsum (ranjit `minus` 1) (ranjit `plus` jhala) k
prop0 = dsum m bot (\x -> liquidAssertB ((m `plus` bot) `leq` x))
prop1 = liquidAssertB (1 `leq` 0)
|
7d22c5eb863686a8f323c2d69112a4fc073c2131efe87aa884f66abf3a0f7943 | exercism/haskell | Person.hs | module Person
( Address (..)
, Born (..)
, Name (..)
, Person (..)
, bornStreet
, renameStreets
, setBirthMonth
, setCurrentStreet
) where
import Data.Time.Calendar (Day)
data Person = Person { _name :: Name
, _born :: Born
, _address :: Address
}
data Name = Name { _foreNames :: String
, _surName :: String
}
data Born = Born { _bornAt :: Address
, _bornOn :: Day
}
data Address = Address { _street :: String
, _houseNumber :: Int
, _place :: String
, _country :: String
}
bornStreet :: Born -> String
bornStreet born = error "You need to implement this function."
setCurrentStreet :: String -> Person -> Person
setCurrentStreet street person = error "You need to implement this function."
setBirthMonth :: Int -> Person -> Person
setBirthMonth month person = error "You need to implement this function."
renameStreets :: (String -> String) -> Person -> Person
renameStreets f person = error "You need to implement this function."
| null | https://raw.githubusercontent.com/exercism/haskell/2b98084efc7d5ab098975c462f7977ee19c2fd29/exercises/practice/lens-person/src/Person.hs | haskell | module Person
( Address (..)
, Born (..)
, Name (..)
, Person (..)
, bornStreet
, renameStreets
, setBirthMonth
, setCurrentStreet
) where
import Data.Time.Calendar (Day)
data Person = Person { _name :: Name
, _born :: Born
, _address :: Address
}
data Name = Name { _foreNames :: String
, _surName :: String
}
data Born = Born { _bornAt :: Address
, _bornOn :: Day
}
data Address = Address { _street :: String
, _houseNumber :: Int
, _place :: String
, _country :: String
}
bornStreet :: Born -> String
bornStreet born = error "You need to implement this function."
setCurrentStreet :: String -> Person -> Person
setCurrentStreet street person = error "You need to implement this function."
setBirthMonth :: Int -> Person -> Person
setBirthMonth month person = error "You need to implement this function."
renameStreets :: (String -> String) -> Person -> Person
renameStreets f person = error "You need to implement this function."
| |
05bda06c596fb2cb097965afa85191a096e9a3216dc1a8dc0367c76f9c2fd594 | vikram/lisplibraries | english.lisp | -*- Mode : LISP ; Syntax : ANSI - Common - Lisp ; Base : 10 -*-
;; See the file LICENCE for licence information.
(in-package #:cl-l10n)
(defparameter *english-plural-overrides*
(read-key->value-text-file-into-hashtable
(merge-pathnames (make-pathname :directory '(:relative "languages")
:name "english-plural-overrides"
:type "text")
(asdf:component-pathname (asdf:find-system :cl-l10n)))))
(defun english-plural-of (word &optional (uppercase nil uppercase-provided-p))
"Returns the english plural of the given word."
;;
;; /~damian/papers/HTML/Plurals.html
(declare (type (simple-array character) word)
(optimize (speed 3) (debug 0)))
(let ((length (length word)))
(when (< length 2)
(error "There's no English word with less then two letters"))
(aif (gethash (string-downcase word) *english-plural-overrides*)
(return-from english-plural-of it)
(let* ((original-last-letter (elt word (1- length)))
(last-letter (char-downcase original-last-letter))
(last-letter2 (char-downcase (elt word (- length 2)))))
(unless uppercase-provided-p
(setf uppercase (upper-case-p original-last-letter)))
(macrolet ((all-but-last (&optional (count 1))
`(subseq word 0 (- length ,count)))
(emit (body postfix)
`(return-from english-plural-of
(concatenate 'string ,body
(if uppercase
(string-upcase ,postfix)
,postfix)))))
(when (>= length 2)
(cond ((or (and (eq last-letter2 #\s) (eq last-letter #\s))
(and (eq last-letter2 #\e) (eq last-letter #\x)))
(emit word "es"))
((and (eq last-letter2 #\i) (eq last-letter #\s)) (emit (all-but-last 2) "es"))
((and (eq last-letter2 #\i) (eq last-letter #\x)) (emit (all-but-last 2) "ices"))
((eq last-letter #\s) (emit word "ses"))
((and (eq last-letter #\y)
(not (vowelp last-letter2))) (emit (all-but-last) "ies"))))
(emit word "s"))))))
(defun english-indefinit-article-for (word)
"Returns a/an for the given word."
(declare (type (simple-array character) word)
(optimize (speed 3) (debug 0)))
(if (> (length word) 1)
(if (vowelp (elt word 0))
"an"
"a")
word))
| null | https://raw.githubusercontent.com/vikram/lisplibraries/105e3ef2d165275eb78f36f5090c9e2cdd0754dd/site/ucw-boxset/dependencies/cl-l10n/languages/english.lisp | lisp | Syntax : ANSI - Common - Lisp ; Base : 10 -*-
See the file LICENCE for licence information.
/~damian/papers/HTML/Plurals.html |
(in-package #:cl-l10n)
(defparameter *english-plural-overrides*
(read-key->value-text-file-into-hashtable
(merge-pathnames (make-pathname :directory '(:relative "languages")
:name "english-plural-overrides"
:type "text")
(asdf:component-pathname (asdf:find-system :cl-l10n)))))
(defun english-plural-of (word &optional (uppercase nil uppercase-provided-p))
"Returns the english plural of the given word."
(declare (type (simple-array character) word)
(optimize (speed 3) (debug 0)))
(let ((length (length word)))
(when (< length 2)
(error "There's no English word with less then two letters"))
(aif (gethash (string-downcase word) *english-plural-overrides*)
(return-from english-plural-of it)
(let* ((original-last-letter (elt word (1- length)))
(last-letter (char-downcase original-last-letter))
(last-letter2 (char-downcase (elt word (- length 2)))))
(unless uppercase-provided-p
(setf uppercase (upper-case-p original-last-letter)))
(macrolet ((all-but-last (&optional (count 1))
`(subseq word 0 (- length ,count)))
(emit (body postfix)
`(return-from english-plural-of
(concatenate 'string ,body
(if uppercase
(string-upcase ,postfix)
,postfix)))))
(when (>= length 2)
(cond ((or (and (eq last-letter2 #\s) (eq last-letter #\s))
(and (eq last-letter2 #\e) (eq last-letter #\x)))
(emit word "es"))
((and (eq last-letter2 #\i) (eq last-letter #\s)) (emit (all-but-last 2) "es"))
((and (eq last-letter2 #\i) (eq last-letter #\x)) (emit (all-but-last 2) "ices"))
((eq last-letter #\s) (emit word "ses"))
((and (eq last-letter #\y)
(not (vowelp last-letter2))) (emit (all-but-last) "ies"))))
(emit word "s"))))))
(defun english-indefinit-article-for (word)
"Returns a/an for the given word."
(declare (type (simple-array character) word)
(optimize (speed 3) (debug 0)))
(if (> (length word) 1)
(if (vowelp (elt word 0))
"an"
"a")
word))
|
80be8257416fdab307adb883191f89cc86baae04412b1c2342f03c3bf778b988 | garrigue/lablgtk | gdk.ml | (**************************************************************************)
(* Lablgtk *)
(* *)
(* This program is free software; you can redistribute it *)
and/or modify it under the terms of the GNU Library General
Public License as published by the Free Software Foundation
version 2 , with the exception described in file COPYING which
(* comes with the library. *)
(* *)
(* 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 Library General Public License for more details .
(* *)
You should have received a copy of the GNU Library General
Public License along with this program ; if not , write to the
Free Software Foundation , Inc. , 59 Temple Place , Suite 330 ,
Boston , MA 02111 - 1307 USA
(* *)
(* *)
(**************************************************************************)
$ Id$
open StdLabels
open Gaux
open Gobject
type color
type rgba
Removed in gtk3
type colormap
type colormap
*)
type visual
type screen = [`gdkscreen] obj
type region
type gc
type window = [`gdkwindow] obj
type cairo = Cairo.context
type atom
type keysym = int
type +'a event
type drag_context = [`dragcontext] obj
type cursor
type xid = int32
type native_window
type device
type display
exception Error of string
let _ = Callback.register_exception "gdkerror" (Error"")
external _gdk_init : unit -> unit = "ml_gdk_init"
let () = _gdk_init ()
module Tags = struct
include (GdkEnums : module type of GdkEnums
with module Conv := GdkEnums.Conv and type xdata := GdkEnums.xdata)
type xdata =
[ `BYTES of string
| `SHORTS of int array
| `INT32S of int32 array ]
type xdata_ret = [ xdata | `NONE ]
end
open Tags
module Convert = struct
external test_modifier : modifier -> int -> bool
= "ml_test_GdkModifier_val"
let modifier i =
List.filter [`SHIFT;`LOCK;`CONTROL;`MOD1;`MOD2;`MOD3;`MOD4;`MOD5;
`BUTTON1;`BUTTON2;`BUTTON3;`BUTTON4;`BUTTON5;`SUPER;
`HYPER;`META;`RELEASE]
~f:(fun m -> test_modifier m i)
external test_window_state : window_state -> int -> bool
= "ml_test_GdkWindowState_val"
let window_state i =
List.filter [ `WITHDRAWN; `ICONIFIED; `MAXIMIZED; `STICKY ]
~f:(fun m -> test_window_state m i)
end
module Atom = struct
external intern : string -> bool -> atom = "ml_gdk_atom_intern"
let intern ?(dont_create=false) name = intern name dont_create
external name : atom -> string = "ml_gdk_atom_name"
let none = intern "NONE"
let primary = intern "PRIMARY"
let secondary = intern "SECONDARY"
let clipboard = intern "CLIPBOARD"
let string = intern "STRING"
end
module Property = struct
external change :
window ->
property:atom -> typ:atom -> mode:property_mode -> xdata -> unit
= "ml_gdk_property_change"
let change ~window ~typ ?(mode=`REPLACE) property data =
change window ~property ~typ ~mode data
external get :
window -> property:atom ->
max_length:int -> delete:bool -> (atom * xdata) option
= "ml_gdk_property_get"
let get ~window ?(max_length=65000) ?(delete=false) property =
get window ~property ~max_length ~delete
external delete : window:window -> atom -> unit
= "ml_gdk_property_delete"
end
module Screen = struct
external get_width : screen -> int = "ml_gdk_screen_get_width"
external width : unit -> int = "ml_gdk_screen_width"
let width ?screen () =
match screen with None -> width () | Some s -> get_width s
external get_height : screen -> int = "ml_gdk_screen_get_height"
external height : unit -> int = "ml_gdk_screen_height"
let height ?screen () =
match screen with None -> height () | Some s -> get_height s
external get_pango_context_for : screen -> Pango.context =
"ml_gdk_pango_context_get_for_screen"
external get_pango_context : unit -> Pango.context =
"ml_gdk_pango_context_get"
let get_pango_context ?screen () =
match screen with None -> get_pango_context ()
| Some s -> get_pango_context_for s
(* Only with Gtk-2.2 *)
external default : unit -> screen = "ml_gdk_screen_get_default"
end
module Visual = struct
type visual_type =
[ `STATIC_GRAY|`GRAYSCALE|`STATIC_COLOR
|`PSEUDO_COLOR|`TRUE_COLOR|`DIRECT_COLOR ]
external get_best : ?depth:int -> ?kind:visual_type -> unit -> visual
= "ml_gdk_visual_get_best"
external get_screen : visual -> screen = "ml_gdk_visual_get_screen"
external get_type : visual -> visual_type = "ml_gdk_visual_get_visual_type"
external depth : visual -> int = "ml_gdk_visual_get_depth"
end
module Color = struct
Removed in GdkColor 3.0
external color_white : colormap - > color = " ml_gdk_color_white "
external color_black : colormap - > color = " ml_gdk_color_black "
external color_white : colormap -> color = "ml_gdk_color_white"
external color_black : colormap -> color = "ml_gdk_color_black"
*)
external color_parse : string -> color = "ml_gdk_color_parse"
external color_to_string : color -> string = "ml_gdk_color_to_string"
Removed in GdkColor 3.0
external color_alloc : colormap - > color - > bool = " ml_gdk_color_alloc "
external color_alloc : colormap -> color -> bool = "ml_gdk_color_alloc"
*)
external color_create : red:int -> green:int -> blue:int -> color
= "ml_GdkColor"
Removed in GdkColor 3.0
external get_system_colormap : unit - > colormap
= " ml_gdk_colormap_get_system "
external colormap_new : visual - > privat : bool - > colormap
= " ml_gdk_colormap_new "
let ? ( privat = false ) vis = colormap_new vis ~privat
external get_visual : colormap - > visual
= " ml_gdk_colormap_get_visual "
type spec = [ ` BLACK | ` NAME of string | ` RGB of int * int * int | ` WHITE ]
let color_alloc ~colormap color =
if not ( color_alloc colormap color ) then raise ( Error"Color.alloc " ) ;
color
let alloc ~colormap color =
match color with
` WHITE - > color_white colormap
| ` BLACK - > color_black colormap
| ` NAME s - > color_alloc ~colormap ( color_parse s )
| ` RGB ( red , green , blue ) - >
color_alloc ~colormap ( color_create ~red ~green ~blue )
external get_system_colormap : unit -> colormap
= "ml_gdk_colormap_get_system"
external colormap_new : visual -> privat:bool -> colormap
= "ml_gdk_colormap_new"
let get_colormap ?(privat=false) vis = colormap_new vis ~privat
external get_visual : colormap -> visual
= "ml_gdk_colormap_get_visual"
type spec = [ `BLACK | `NAME of string | `RGB of int * int * int | `WHITE]
let color_alloc ~colormap color =
if not (color_alloc colormap color) then raise (Error"Color.alloc");
color
let alloc ~colormap color =
match color with
`WHITE -> color_white colormap
| `BLACK -> color_black colormap
| `NAME s -> color_alloc ~colormap (color_parse s)
| `RGB (red,green,blue) ->
color_alloc ~colormap (color_create ~red ~green ~blue)
*)
deprecated in 3.14 in favor of RGBA
external red : color -> int = "ml_GdkColor_red"
external blue : color -> int = "ml_GdkColor_blue"
external green : color -> int = "ml_GdkColor_green"
external pixel : color -> int = "ml_GdkColor_pixel"
end
module Rectangle = struct
type t
external create : x:int -> y:int -> width:int -> height:int -> t
= "ml_GdkRectangle"
external x : t -> int = "ml_GdkRectangle_x"
external y : t -> int = "ml_GdkRectangle_y"
external width : t -> int = "ml_GdkRectangle_width"
external height : t -> int = "ml_GdkRectangle_height"
end
module Windowing = struct
external get : unit -> [`QUARTZ | `WIN32 | `X11] = "ml_gdk_get_platform"
let platform = get ()
end
module Window = struct
let cast w : window = Gobject.try_cast w "GdkWindow"
external create_foreign : display -> xid -> window =
"ml_gdk_x11_window_foreign_new_for_display"
external get_parent : window -> window = "ml_gdk_window_get_parent"
external get_position : window -> int * int = "ml_gdk_window_get_position"
external get_origin : window -> int * int = "ml_gdk_window_get_origin"
external get_pointer_location : window -> int * int =
"ml_gdk_window_get_pointer_location"
(* external root_parent : unit -> window = "ml_GDK_ROOT_PARENT" *)
(* external set_back_pixmap : window -> pixmap -> int -> unit =
"ml_gdk_window_set_back_pixmap" *)
external set_cursor : window -> cursor -> unit =
"ml_gdk_window_set_cursor"
external clear : window - > unit = " ml_gdk_window_clear "
external :
window - > x : int - > y : int - > width : int - > height : int - > unit
= " ml_gdk_window_clear "
external clear_area :
window -> x:int -> y:int -> width:int -> height:int -> unit
= "ml_gdk_window_clear" *)
external get_xid : window -> xid = "ml_GDK_WINDOW_XID"
let get_xwindow = get_xid
external get_visual : window -> visual = "ml_gdk_window_get_visual"
(* let set_back_pixmap w pix =
let null_pixmap = (Obj.magic Gpointer.boxed_null : pixmap) in
match pix with
`NONE -> set_back_pixmap w null_pixmap 0
| `PARENT_RELATIVE -> set_back_pixmap w null_pixmap 1
| `PIXMAP(pixmap) -> set_back_pixmap w pixmap 0
(* anything OK, Maybe... *) *)
let xid_of_native (w : native_window) : xid =
if Windowing.platform = `X11 then Obj.magic w else
failwith "Gdk.Window.xid_of_native only allowed for X11"
let native_of_xid (id : xid) : native_window =
if Windowing.platform = `X11 then Obj.magic id else
failwith "Gdk.Window.native_of_xid only allowed for X11"
external set_transient_for : window -> window -> unit = "ml_gdk_window_set_transient_for"
end
module DnD = struct
external drag_status : drag_context -> drag_action option -> time:int32 -> unit
= "ml_gdk_drag_status"
external drag_context_suggested_action : drag_context -> drag_action
= "ml_gdk_drag_context_get_suggested_action"
external drag_context_targets : drag_context -> atom list
= "ml_gdk_drag_context_list_targets"
end
module Truecolor = struct
( * Truecolor quick color query
module Truecolor = struct
(* Truecolor quick color query *)
type visual_shift_prec = {
red_shift : int;
red_prec : int;
green_shift : int;
green_prec : int;
blue_shift : int;
blue_prec : int
}
let shift_prec visual = {
red_shift = Visual.red_shift visual;
red_prec = Visual.red_prec visual;
green_shift = Visual.green_shift visual;
green_prec = Visual.green_prec visual;
blue_shift = Visual.blue_shift visual;
blue_prec = Visual.blue_prec visual;
}
let color_creator visual =
match Visual.get_type visual with
`TRUE_COLOR | `DIRECT_COLOR ->
let shift_prec = shift_prec visual in
(* Format.eprintf "red : %d %d, "
shift_prec.red_shift shift_prec.red_prec;
Format.eprintf "green : %d %d, "
shift_prec.green_shift shift_prec.green_prec;
Format.eprintf "blue : %d %d"
shift_prec.blue_shift shift_prec.blue_prec;
Format.pp_print_newline Format.err_formatter (); *)
let red_lsr = 16 - shift_prec.red_prec
and green_lsr = 16 - shift_prec.green_prec
and blue_lsr = 16 - shift_prec.blue_prec in
fun ~red: red ~green: green ~blue: blue ->
(((red lsr red_lsr) lsl shift_prec.red_shift) lor
((green lsr green_lsr) lsl shift_prec.green_shift) lor
((blue lsr blue_lsr) lsl shift_prec.blue_shift))
| _ -> raise (Invalid_argument "Gdk.Truecolor.color_creator")
let color_parser visual =
match Visual.get_type visual with
`TRUE_COLOR | `DIRECT_COLOR ->
let shift_prec = shift_prec visual in
let red_lsr = 16 - shift_prec.red_prec
and green_lsr = 16 - shift_prec.green_prec
and blue_lsr = 16 - shift_prec.blue_prec in
let mask = 1 lsl 16 - 1 in
fun pixel ->
((pixel lsr shift_prec.red_shift) lsl red_lsr) land mask,
((pixel lsr shift_prec.green_shift) lsl green_lsr) land mask,
((pixel lsr shift_prec.blue_shift) lsl blue_lsr) land mask
| _ -> raise (Invalid_argument "Gdk.Truecolor.color_parser")
end
*)
module X = struct
(* X related functions *)
external flush : unit -> unit
= "ml_gdk_flush"
external beep : unit -> unit
= "ml_gdk_beep"
end
module Cursor = struct
type cursor_type = [
| `X_CURSOR
| `ARROW
| `BASED_ARROW_DOWN
| `BASED_ARROW_UP
| `BOAT
| `BOGOSITY
| `BOTTOM_LEFT_CORNER
| `BOTTOM_RIGHT_CORNER
| `BOTTOM_SIDE
| `BOTTOM_TEE
| `BOX_SPIRAL
| `CENTER_PTR
| `CIRCLE
| `CLOCK
| `COFFEE_MUG
| `CROSS
| `CROSS_REVERSE
| `CROSSHAIR
| `DIAMOND_CROSS
| `DOT
| `DOTBOX
| `DOUBLE_ARROW
| `DRAFT_LARGE
| `DRAFT_SMALL
| `DRAPED_BOX
| `EXCHANGE
| `FLEUR
| `GOBBLER
| `GUMBY
| `HAND1
| `HAND2
| `HEART
| `ICON
| `IRON_CROSS
| `LEFT_PTR
| `LEFT_SIDE
| `LEFT_TEE
| `LEFTBUTTON
| `LL_ANGLE
| `LR_ANGLE
| `MAN
| `MIDDLEBUTTON
| `MOUSE
| `PENCIL
| `PIRATE
| `PLUS
| `QUESTION_ARROW
| `RIGHT_PTR
| `RIGHT_SIDE
| `RIGHT_TEE
| `RIGHTBUTTON
| `RTL_LOGO
| `SAILBOAT
| `SB_DOWN_ARROW
| `SB_H_DOUBLE_ARROW
| `SB_LEFT_ARROW
| `SB_RIGHT_ARROW
| `SB_UP_ARROW
| `SB_V_DOUBLE_ARROW
| `SHUTTLE
| `SIZING
| `SPIDER
| `SPRAYCAN
| `STAR
| `TARGET
| `TCROSS
| `TOP_LEFT_ARROW
| `TOP_LEFT_CORNER
| `TOP_RIGHT_CORNER
| `TOP_SIDE
| `TOP_TEE
| `TREK
| `UL_ANGLE
| `UMBRELLA
| `UR_ANGLE
| `WATCH
| `XTERM
]
external create : cursor_type -> cursor = "ml_gdk_cursor_new"
external create_from_pixbuf :
[`pixbuf] obj -> x:int -> y:int -> cursor
* @since GTK 2.4
external get_image : cursor -> [`pixbuf] obj
* @since GTK 2.8
end
module Display = struct
(* since Gtk+-2.2 *)
external default :
unit -> display
= "ml_gdk_display_get_default"
external get_window_at_pointer :
display -> (window * int * int) option
= "ml_gdk_display_get_window_at_pointer"
let window_at_pointer ?display () =
get_window_at_pointer
(match display with None -> default ()
| Some disp -> disp)
end
module Cairo = struct
external create :
window -> cairo
= "ml_gdk_cairo_create"
end
| null | https://raw.githubusercontent.com/garrigue/lablgtk/504fac1257e900e6044c638025a4d6c5a321284c/src/gdk.ml | ocaml | ************************************************************************
Lablgtk
This program is free software; you can redistribute it
comes with the library.
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
************************************************************************
Only with Gtk-2.2
external root_parent : unit -> window = "ml_GDK_ROOT_PARENT"
external set_back_pixmap : window -> pixmap -> int -> unit =
"ml_gdk_window_set_back_pixmap"
let set_back_pixmap w pix =
let null_pixmap = (Obj.magic Gpointer.boxed_null : pixmap) in
match pix with
`NONE -> set_back_pixmap w null_pixmap 0
| `PARENT_RELATIVE -> set_back_pixmap w null_pixmap 1
| `PIXMAP(pixmap) -> set_back_pixmap w pixmap 0
(* anything OK, Maybe...
Truecolor quick color query
Format.eprintf "red : %d %d, "
shift_prec.red_shift shift_prec.red_prec;
Format.eprintf "green : %d %d, "
shift_prec.green_shift shift_prec.green_prec;
Format.eprintf "blue : %d %d"
shift_prec.blue_shift shift_prec.blue_prec;
Format.pp_print_newline Format.err_formatter ();
X related functions
since Gtk+-2.2 | and/or modify it under the terms of the GNU Library General
Public License as published by the Free Software Foundation
version 2 , with the exception described in file COPYING which
GNU Library General Public License for more details .
You should have received a copy of the GNU Library General
Public License along with this program ; if not , write to the
Free Software Foundation , Inc. , 59 Temple Place , Suite 330 ,
Boston , MA 02111 - 1307 USA
$ Id$
open StdLabels
open Gaux
open Gobject
type color
type rgba
Removed in gtk3
type colormap
type colormap
*)
type visual
type screen = [`gdkscreen] obj
type region
type gc
type window = [`gdkwindow] obj
type cairo = Cairo.context
type atom
type keysym = int
type +'a event
type drag_context = [`dragcontext] obj
type cursor
type xid = int32
type native_window
type device
type display
exception Error of string
let _ = Callback.register_exception "gdkerror" (Error"")
external _gdk_init : unit -> unit = "ml_gdk_init"
let () = _gdk_init ()
module Tags = struct
include (GdkEnums : module type of GdkEnums
with module Conv := GdkEnums.Conv and type xdata := GdkEnums.xdata)
type xdata =
[ `BYTES of string
| `SHORTS of int array
| `INT32S of int32 array ]
type xdata_ret = [ xdata | `NONE ]
end
open Tags
module Convert = struct
external test_modifier : modifier -> int -> bool
= "ml_test_GdkModifier_val"
let modifier i =
List.filter [`SHIFT;`LOCK;`CONTROL;`MOD1;`MOD2;`MOD3;`MOD4;`MOD5;
`BUTTON1;`BUTTON2;`BUTTON3;`BUTTON4;`BUTTON5;`SUPER;
`HYPER;`META;`RELEASE]
~f:(fun m -> test_modifier m i)
external test_window_state : window_state -> int -> bool
= "ml_test_GdkWindowState_val"
let window_state i =
List.filter [ `WITHDRAWN; `ICONIFIED; `MAXIMIZED; `STICKY ]
~f:(fun m -> test_window_state m i)
end
module Atom = struct
external intern : string -> bool -> atom = "ml_gdk_atom_intern"
let intern ?(dont_create=false) name = intern name dont_create
external name : atom -> string = "ml_gdk_atom_name"
let none = intern "NONE"
let primary = intern "PRIMARY"
let secondary = intern "SECONDARY"
let clipboard = intern "CLIPBOARD"
let string = intern "STRING"
end
module Property = struct
external change :
window ->
property:atom -> typ:atom -> mode:property_mode -> xdata -> unit
= "ml_gdk_property_change"
let change ~window ~typ ?(mode=`REPLACE) property data =
change window ~property ~typ ~mode data
external get :
window -> property:atom ->
max_length:int -> delete:bool -> (atom * xdata) option
= "ml_gdk_property_get"
let get ~window ?(max_length=65000) ?(delete=false) property =
get window ~property ~max_length ~delete
external delete : window:window -> atom -> unit
= "ml_gdk_property_delete"
end
module Screen = struct
external get_width : screen -> int = "ml_gdk_screen_get_width"
external width : unit -> int = "ml_gdk_screen_width"
let width ?screen () =
match screen with None -> width () | Some s -> get_width s
external get_height : screen -> int = "ml_gdk_screen_get_height"
external height : unit -> int = "ml_gdk_screen_height"
let height ?screen () =
match screen with None -> height () | Some s -> get_height s
external get_pango_context_for : screen -> Pango.context =
"ml_gdk_pango_context_get_for_screen"
external get_pango_context : unit -> Pango.context =
"ml_gdk_pango_context_get"
let get_pango_context ?screen () =
match screen with None -> get_pango_context ()
| Some s -> get_pango_context_for s
external default : unit -> screen = "ml_gdk_screen_get_default"
end
module Visual = struct
type visual_type =
[ `STATIC_GRAY|`GRAYSCALE|`STATIC_COLOR
|`PSEUDO_COLOR|`TRUE_COLOR|`DIRECT_COLOR ]
external get_best : ?depth:int -> ?kind:visual_type -> unit -> visual
= "ml_gdk_visual_get_best"
external get_screen : visual -> screen = "ml_gdk_visual_get_screen"
external get_type : visual -> visual_type = "ml_gdk_visual_get_visual_type"
external depth : visual -> int = "ml_gdk_visual_get_depth"
end
module Color = struct
Removed in GdkColor 3.0
external color_white : colormap - > color = " ml_gdk_color_white "
external color_black : colormap - > color = " ml_gdk_color_black "
external color_white : colormap -> color = "ml_gdk_color_white"
external color_black : colormap -> color = "ml_gdk_color_black"
*)
external color_parse : string -> color = "ml_gdk_color_parse"
external color_to_string : color -> string = "ml_gdk_color_to_string"
Removed in GdkColor 3.0
external color_alloc : colormap - > color - > bool = " ml_gdk_color_alloc "
external color_alloc : colormap -> color -> bool = "ml_gdk_color_alloc"
*)
external color_create : red:int -> green:int -> blue:int -> color
= "ml_GdkColor"
Removed in GdkColor 3.0
external get_system_colormap : unit - > colormap
= " ml_gdk_colormap_get_system "
external colormap_new : visual - > privat : bool - > colormap
= " ml_gdk_colormap_new "
let ? ( privat = false ) vis = colormap_new vis ~privat
external get_visual : colormap - > visual
= " ml_gdk_colormap_get_visual "
type spec = [ ` BLACK | ` NAME of string | ` RGB of int * int * int | ` WHITE ]
let color_alloc ~colormap color =
if not ( color_alloc colormap color ) then raise ( Error"Color.alloc " ) ;
color
let alloc ~colormap color =
match color with
` WHITE - > color_white colormap
| ` BLACK - > color_black colormap
| ` NAME s - > color_alloc ~colormap ( color_parse s )
| ` RGB ( red , green , blue ) - >
color_alloc ~colormap ( color_create ~red ~green ~blue )
external get_system_colormap : unit -> colormap
= "ml_gdk_colormap_get_system"
external colormap_new : visual -> privat:bool -> colormap
= "ml_gdk_colormap_new"
let get_colormap ?(privat=false) vis = colormap_new vis ~privat
external get_visual : colormap -> visual
= "ml_gdk_colormap_get_visual"
type spec = [ `BLACK | `NAME of string | `RGB of int * int * int | `WHITE]
let color_alloc ~colormap color =
if not (color_alloc colormap color) then raise (Error"Color.alloc");
color
let alloc ~colormap color =
match color with
`WHITE -> color_white colormap
| `BLACK -> color_black colormap
| `NAME s -> color_alloc ~colormap (color_parse s)
| `RGB (red,green,blue) ->
color_alloc ~colormap (color_create ~red ~green ~blue)
*)
deprecated in 3.14 in favor of RGBA
external red : color -> int = "ml_GdkColor_red"
external blue : color -> int = "ml_GdkColor_blue"
external green : color -> int = "ml_GdkColor_green"
external pixel : color -> int = "ml_GdkColor_pixel"
end
module Rectangle = struct
type t
external create : x:int -> y:int -> width:int -> height:int -> t
= "ml_GdkRectangle"
external x : t -> int = "ml_GdkRectangle_x"
external y : t -> int = "ml_GdkRectangle_y"
external width : t -> int = "ml_GdkRectangle_width"
external height : t -> int = "ml_GdkRectangle_height"
end
module Windowing = struct
external get : unit -> [`QUARTZ | `WIN32 | `X11] = "ml_gdk_get_platform"
let platform = get ()
end
module Window = struct
let cast w : window = Gobject.try_cast w "GdkWindow"
external create_foreign : display -> xid -> window =
"ml_gdk_x11_window_foreign_new_for_display"
external get_parent : window -> window = "ml_gdk_window_get_parent"
external get_position : window -> int * int = "ml_gdk_window_get_position"
external get_origin : window -> int * int = "ml_gdk_window_get_origin"
external get_pointer_location : window -> int * int =
"ml_gdk_window_get_pointer_location"
external set_cursor : window -> cursor -> unit =
"ml_gdk_window_set_cursor"
external clear : window - > unit = " ml_gdk_window_clear "
external :
window - > x : int - > y : int - > width : int - > height : int - > unit
= " ml_gdk_window_clear "
external clear_area :
window -> x:int -> y:int -> width:int -> height:int -> unit
= "ml_gdk_window_clear" *)
external get_xid : window -> xid = "ml_GDK_WINDOW_XID"
let get_xwindow = get_xid
external get_visual : window -> visual = "ml_gdk_window_get_visual"
let xid_of_native (w : native_window) : xid =
if Windowing.platform = `X11 then Obj.magic w else
failwith "Gdk.Window.xid_of_native only allowed for X11"
let native_of_xid (id : xid) : native_window =
if Windowing.platform = `X11 then Obj.magic id else
failwith "Gdk.Window.native_of_xid only allowed for X11"
external set_transient_for : window -> window -> unit = "ml_gdk_window_set_transient_for"
end
module DnD = struct
external drag_status : drag_context -> drag_action option -> time:int32 -> unit
= "ml_gdk_drag_status"
external drag_context_suggested_action : drag_context -> drag_action
= "ml_gdk_drag_context_get_suggested_action"
external drag_context_targets : drag_context -> atom list
= "ml_gdk_drag_context_list_targets"
end
module Truecolor = struct
( * Truecolor quick color query
module Truecolor = struct
type visual_shift_prec = {
red_shift : int;
red_prec : int;
green_shift : int;
green_prec : int;
blue_shift : int;
blue_prec : int
}
let shift_prec visual = {
red_shift = Visual.red_shift visual;
red_prec = Visual.red_prec visual;
green_shift = Visual.green_shift visual;
green_prec = Visual.green_prec visual;
blue_shift = Visual.blue_shift visual;
blue_prec = Visual.blue_prec visual;
}
let color_creator visual =
match Visual.get_type visual with
`TRUE_COLOR | `DIRECT_COLOR ->
let shift_prec = shift_prec visual in
let red_lsr = 16 - shift_prec.red_prec
and green_lsr = 16 - shift_prec.green_prec
and blue_lsr = 16 - shift_prec.blue_prec in
fun ~red: red ~green: green ~blue: blue ->
(((red lsr red_lsr) lsl shift_prec.red_shift) lor
((green lsr green_lsr) lsl shift_prec.green_shift) lor
((blue lsr blue_lsr) lsl shift_prec.blue_shift))
| _ -> raise (Invalid_argument "Gdk.Truecolor.color_creator")
let color_parser visual =
match Visual.get_type visual with
`TRUE_COLOR | `DIRECT_COLOR ->
let shift_prec = shift_prec visual in
let red_lsr = 16 - shift_prec.red_prec
and green_lsr = 16 - shift_prec.green_prec
and blue_lsr = 16 - shift_prec.blue_prec in
let mask = 1 lsl 16 - 1 in
fun pixel ->
((pixel lsr shift_prec.red_shift) lsl red_lsr) land mask,
((pixel lsr shift_prec.green_shift) lsl green_lsr) land mask,
((pixel lsr shift_prec.blue_shift) lsl blue_lsr) land mask
| _ -> raise (Invalid_argument "Gdk.Truecolor.color_parser")
end
*)
module X = struct
external flush : unit -> unit
= "ml_gdk_flush"
external beep : unit -> unit
= "ml_gdk_beep"
end
module Cursor = struct
type cursor_type = [
| `X_CURSOR
| `ARROW
| `BASED_ARROW_DOWN
| `BASED_ARROW_UP
| `BOAT
| `BOGOSITY
| `BOTTOM_LEFT_CORNER
| `BOTTOM_RIGHT_CORNER
| `BOTTOM_SIDE
| `BOTTOM_TEE
| `BOX_SPIRAL
| `CENTER_PTR
| `CIRCLE
| `CLOCK
| `COFFEE_MUG
| `CROSS
| `CROSS_REVERSE
| `CROSSHAIR
| `DIAMOND_CROSS
| `DOT
| `DOTBOX
| `DOUBLE_ARROW
| `DRAFT_LARGE
| `DRAFT_SMALL
| `DRAPED_BOX
| `EXCHANGE
| `FLEUR
| `GOBBLER
| `GUMBY
| `HAND1
| `HAND2
| `HEART
| `ICON
| `IRON_CROSS
| `LEFT_PTR
| `LEFT_SIDE
| `LEFT_TEE
| `LEFTBUTTON
| `LL_ANGLE
| `LR_ANGLE
| `MAN
| `MIDDLEBUTTON
| `MOUSE
| `PENCIL
| `PIRATE
| `PLUS
| `QUESTION_ARROW
| `RIGHT_PTR
| `RIGHT_SIDE
| `RIGHT_TEE
| `RIGHTBUTTON
| `RTL_LOGO
| `SAILBOAT
| `SB_DOWN_ARROW
| `SB_H_DOUBLE_ARROW
| `SB_LEFT_ARROW
| `SB_RIGHT_ARROW
| `SB_UP_ARROW
| `SB_V_DOUBLE_ARROW
| `SHUTTLE
| `SIZING
| `SPIDER
| `SPRAYCAN
| `STAR
| `TARGET
| `TCROSS
| `TOP_LEFT_ARROW
| `TOP_LEFT_CORNER
| `TOP_RIGHT_CORNER
| `TOP_SIDE
| `TOP_TEE
| `TREK
| `UL_ANGLE
| `UMBRELLA
| `UR_ANGLE
| `WATCH
| `XTERM
]
external create : cursor_type -> cursor = "ml_gdk_cursor_new"
external create_from_pixbuf :
[`pixbuf] obj -> x:int -> y:int -> cursor
* @since GTK 2.4
external get_image : cursor -> [`pixbuf] obj
* @since GTK 2.8
end
module Display = struct
external default :
unit -> display
= "ml_gdk_display_get_default"
external get_window_at_pointer :
display -> (window * int * int) option
= "ml_gdk_display_get_window_at_pointer"
let window_at_pointer ?display () =
get_window_at_pointer
(match display with None -> default ()
| Some disp -> disp)
end
module Cairo = struct
external create :
window -> cairo
= "ml_gdk_cairo_create"
end
|
9553aa4c06c6af20a7f1c96bbaf42ccea0bcd99cf80e206f1b87ec57788992c5 | oliyh/martian | test_runner.cljs | (ns martian.test-runner
(:require
[martian.re-frame-test]
[figwheel.main.testing :refer [run-tests-async]]))
(defn -main [& args]
(run-tests-async 5000))
| null | https://raw.githubusercontent.com/oliyh/martian/c20d3fad47709ecfc0493e2fb607d5b56ea3193d/re-frame/test/martian/test_runner.cljs | clojure | (ns martian.test-runner
(:require
[martian.re-frame-test]
[figwheel.main.testing :refer [run-tests-async]]))
(defn -main [& args]
(run-tests-async 5000))
| |
9b096c1200d2d6294e26d56a27b17482d20f4f5153bfed1ba5e5e2262ac61e5c | gojek/ziggurat | timestamp_transformer_test.clj | (ns ziggurat.timestamp-transformer-test
(:require [clojure.test :refer [deftest is testing]]
[ziggurat.metrics :as metrics]
[ziggurat.timestamp-transformer :refer [create]]
[ziggurat.util.time :refer [get-current-time-in-millis get-timestamp-from-record]])
(:import [org.apache.kafka.clients.consumer ConsumerRecord]
[org.apache.kafka.streams.processor ProcessorContext]
[ziggurat.timestamp_transformer IngestionTimeExtractor]
[org.apache.kafka.common.header.internals RecordHeaders]))
(deftest ingestion-time-extractor-test
(let [ingestion-time-extractor (IngestionTimeExtractor.)
topic "some-topic"
partition (int 1)
offset 1
previous-timestamp 1528720768771
key "some-key"
value "some-value"
record (ConsumerRecord. topic partition offset key value)]
(testing "extract timestamp of topic when it has valid timestamp"
(with-redefs [get-timestamp-from-record (constantly 1528720768777)]
(is (= (.extract ingestion-time-extractor record previous-timestamp)
1528720768777))))
(testing "extract timestamp of topic when it has invalid timestamp"
(with-redefs [get-timestamp-from-record (constantly -1)
get-current-time-in-millis (constantly 1528720768777)]
(is (= (.extract ingestion-time-extractor record previous-timestamp)
(get-current-time-in-millis)))))))
(deftest timestamp-transformer-test
(let [default-namespace "message-received-delay-histogram"
expected-metric-namespaces ["test" default-namespace]
record-timestamp 1528720767777
current-time 1528720768777
expected-delay 1000
test-partition 1337
test-topic "test-topic"
my-key "my-key"
my-value "my-value"]
(testing "creates a timestamp-transformer object that calculates and reports timestamp delay"
(let [context (reify ProcessorContext
(timestamp [_] record-timestamp)
(partition [_] test-partition)
(topic [_] test-topic))
expected-topic-entity-name "expected-topic-entity-name"
timestamp-transformer (create expected-metric-namespaces current-time expected-topic-entity-name)]
(.init timestamp-transformer context)
(with-redefs [get-current-time-in-millis (constantly current-time)
metrics/report-histogram (fn [metric-namespaces delay topic-entity-name]
(is (= delay expected-delay))
(is (or (= metric-namespaces expected-metric-namespaces)
(= metric-namespaces [default-namespace])))
(is (= expected-topic-entity-name topic-entity-name)))]
(.transform timestamp-transformer my-key my-value))))
(testing "creates a timestamp-transformer object that calculates and reports timestamp delay when topic-entity-name is nil"
(let [context (reify ProcessorContext
(timestamp [_] record-timestamp)
(partition [_] test-partition)
(topic [_] test-topic))
expected-topic-entity-name nil
timestamp-transformer (create expected-metric-namespaces current-time)]
(.init timestamp-transformer context)
(with-redefs [get-current-time-in-millis (constantly current-time)
metrics/report-histogram (fn [metric-namespaces delay topic-entity-name]
(is (= delay expected-delay))
(is (or (= metric-namespaces expected-metric-namespaces)
(= metric-namespaces [default-namespace])))
(is (= topic-entity-name expected-topic-entity-name)))]
(.transform timestamp-transformer my-key my-value))))))
| null | https://raw.githubusercontent.com/gojek/ziggurat/f5e0822af8410ea79b7734ef2f41bc98fad3c17f/test/ziggurat/timestamp_transformer_test.clj | clojure | (ns ziggurat.timestamp-transformer-test
(:require [clojure.test :refer [deftest is testing]]
[ziggurat.metrics :as metrics]
[ziggurat.timestamp-transformer :refer [create]]
[ziggurat.util.time :refer [get-current-time-in-millis get-timestamp-from-record]])
(:import [org.apache.kafka.clients.consumer ConsumerRecord]
[org.apache.kafka.streams.processor ProcessorContext]
[ziggurat.timestamp_transformer IngestionTimeExtractor]
[org.apache.kafka.common.header.internals RecordHeaders]))
(deftest ingestion-time-extractor-test
(let [ingestion-time-extractor (IngestionTimeExtractor.)
topic "some-topic"
partition (int 1)
offset 1
previous-timestamp 1528720768771
key "some-key"
value "some-value"
record (ConsumerRecord. topic partition offset key value)]
(testing "extract timestamp of topic when it has valid timestamp"
(with-redefs [get-timestamp-from-record (constantly 1528720768777)]
(is (= (.extract ingestion-time-extractor record previous-timestamp)
1528720768777))))
(testing "extract timestamp of topic when it has invalid timestamp"
(with-redefs [get-timestamp-from-record (constantly -1)
get-current-time-in-millis (constantly 1528720768777)]
(is (= (.extract ingestion-time-extractor record previous-timestamp)
(get-current-time-in-millis)))))))
(deftest timestamp-transformer-test
(let [default-namespace "message-received-delay-histogram"
expected-metric-namespaces ["test" default-namespace]
record-timestamp 1528720767777
current-time 1528720768777
expected-delay 1000
test-partition 1337
test-topic "test-topic"
my-key "my-key"
my-value "my-value"]
(testing "creates a timestamp-transformer object that calculates and reports timestamp delay"
(let [context (reify ProcessorContext
(timestamp [_] record-timestamp)
(partition [_] test-partition)
(topic [_] test-topic))
expected-topic-entity-name "expected-topic-entity-name"
timestamp-transformer (create expected-metric-namespaces current-time expected-topic-entity-name)]
(.init timestamp-transformer context)
(with-redefs [get-current-time-in-millis (constantly current-time)
metrics/report-histogram (fn [metric-namespaces delay topic-entity-name]
(is (= delay expected-delay))
(is (or (= metric-namespaces expected-metric-namespaces)
(= metric-namespaces [default-namespace])))
(is (= expected-topic-entity-name topic-entity-name)))]
(.transform timestamp-transformer my-key my-value))))
(testing "creates a timestamp-transformer object that calculates and reports timestamp delay when topic-entity-name is nil"
(let [context (reify ProcessorContext
(timestamp [_] record-timestamp)
(partition [_] test-partition)
(topic [_] test-topic))
expected-topic-entity-name nil
timestamp-transformer (create expected-metric-namespaces current-time)]
(.init timestamp-transformer context)
(with-redefs [get-current-time-in-millis (constantly current-time)
metrics/report-histogram (fn [metric-namespaces delay topic-entity-name]
(is (= delay expected-delay))
(is (or (= metric-namespaces expected-metric-namespaces)
(= metric-namespaces [default-namespace])))
(is (= topic-entity-name expected-topic-entity-name)))]
(.transform timestamp-transformer my-key my-value))))))
| |
382d2f9f3ffa3eaa3f99d8137c54758a7d2a9ccccb3331ad34112edfc3522498 | tezos/tezos-mirror | main.ml | (*****************************************************************************)
(* *)
(* Open Source License *)
Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < >
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
to deal in the Software without restriction , including without limitation
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
and/or sell copies of the Software , and to permit persons to whom the
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
(* Tezos Protocol Implementation - Protocol Signature Instance *)
type block_header_data = Alpha_context.Block_header.protocol_data
type block_header = Alpha_context.Block_header.t = {
shell : Block_header.shell_header;
protocol_data : block_header_data;
}
let block_header_data_encoding =
Alpha_context.Block_header.protocol_data_encoding
type block_header_metadata = Apply_results.block_metadata
let block_header_metadata_encoding = Apply_results.block_metadata_encoding
type operation_data = Alpha_context.packed_protocol_data =
| Operation_data :
'kind Alpha_context.Operation.protocol_data
-> operation_data
let operation_data_encoding = Alpha_context.Operation.protocol_data_encoding
type operation_receipt = Apply_results.packed_operation_metadata =
| Operation_metadata :
'kind Apply_results.operation_metadata
-> operation_receipt
| No_operation_metadata : operation_receipt
let operation_receipt_encoding = Apply_results.operation_metadata_encoding
let operation_data_and_receipt_encoding =
Apply_results.operation_data_and_metadata_encoding
type operation = Alpha_context.packed_operation = {
shell : Operation.shell_header;
protocol_data : operation_data;
}
let acceptable_pass = Alpha_context.Operation.acceptable_pass
let max_block_length = Alpha_context.Block_header.max_header_length
let max_operation_data_length =
Alpha_context.Constants.max_operation_data_length
let validation_passes =
let open Alpha_context.Constants in
Updater.
[
2048 endorsements
{max_size = 2048 * 2048; max_op = Some 2048};
32k of voting operations
{max_size = 32 * 1024; max_op = None};
(* revelations, wallet activations and denunciations *)
{
max_size = max_anon_ops_per_block * 1024;
max_op = Some max_anon_ops_per_block;
};
512kB
{max_size = 512 * 1024; max_op = None};
]
let rpc_services =
Alpha_services.register () ;
Services_registration.get_rpc_services ()
type validation_state = Validate.validation_state
type application_state = Apply.application_state
let init_allowed_consensus_operations ctxt ~endorsement_level
~preendorsement_level =
let open Lwt_result_syntax in
let open Alpha_context in
let* ctxt = Delegate.prepare_stake_distribution ctxt in
let* ctxt, allowed_endorsements, allowed_preendorsements =
if Level.(endorsement_level = preendorsement_level) then
let* ctxt, slots =
Baking.endorsing_rights_by_first_slot ctxt endorsement_level
in
let consensus_operations = slots in
return (ctxt, consensus_operations, consensus_operations)
else
let* ctxt, endorsements =
Baking.endorsing_rights_by_first_slot ctxt endorsement_level
in
let* ctxt, preendorsements =
Baking.endorsing_rights_by_first_slot ctxt preendorsement_level
in
return (ctxt, endorsements, preendorsements)
in
let ctxt =
Consensus.initialize_consensus_operation
ctxt
~allowed_endorsements
~allowed_preendorsements
in
return ctxt
(** Circumstances and relevant information for [begin_validation] and
[begin_application] below. *)
type mode =
| Application of block_header
| Partial_validation of block_header
| Construction of {
predecessor_hash : Block_hash.t;
timestamp : Time.t;
block_header_data : block_header_data;
}
| Partial_construction of {
predecessor_hash : Block_hash.t;
timestamp : Time.t;
}
let prepare_ctxt ctxt mode ~(predecessor : Block_header.shell_header) =
let open Lwt_result_syntax in
let open Alpha_context in
let level, timestamp =
match mode with
| Application block_header | Partial_validation block_header ->
(block_header.shell.level, block_header.shell.timestamp)
| Construction {timestamp; _} | Partial_construction {timestamp; _} ->
(Int32.succ predecessor.level, timestamp)
in
let* ctxt, migration_balance_updates, migration_operation_results =
prepare ctxt ~level ~predecessor_timestamp:predecessor.timestamp ~timestamp
in
let*? predecessor_raw_level = Raw_level.of_int32 predecessor.level in
let predecessor_level = Level.from_raw ctxt predecessor_raw_level in
During block ( full or partial ) application or full construction ,
endorsements must be for [ predecessor_level ] and preendorsements ,
if any , for the block 's level . In the ( partial
construction ) , only consensus operations for [ predecessor_level ]
( that is , head 's level ) are allowed ( except for grandparent
endorsements , which are handled differently ) .
endorsements must be for [predecessor_level] and preendorsements,
if any, for the block's level. In the mempool (partial
construction), only consensus operations for [predecessor_level]
(that is, head's level) are allowed (except for grandparent
endorsements, which are handled differently). *)
let preendorsement_level =
match mode with
| Application _ | Partial_validation _ | Construction _ ->
Level.current ctxt
| Partial_construction _ -> predecessor_level
in
let* ctxt =
init_allowed_consensus_operations
ctxt
~endorsement_level:predecessor_level
~preendorsement_level
in
Dal_apply.initialisation ~level:predecessor_level ctxt >>=? fun ctxt ->
return
( ctxt,
migration_balance_updates,
migration_operation_results,
predecessor_level,
predecessor_raw_level )
let begin_validation ctxt chain_id mode ~predecessor =
let open Lwt_result_syntax in
let open Alpha_context in
let* ( ctxt,
_migration_balance_updates,
_migration_operation_results,
predecessor_level,
_predecessor_raw_level ) =
prepare_ctxt ctxt ~predecessor mode
in
let predecessor_timestamp = predecessor.timestamp in
let predecessor_fitness = predecessor.fitness in
match mode with
| Application block_header ->
let*? fitness = Fitness.from_raw block_header.shell.fitness in
Validate.begin_application
ctxt
chain_id
~predecessor_level
~predecessor_timestamp
block_header
fitness
| Partial_validation block_header ->
let*? fitness = Fitness.from_raw block_header.shell.fitness in
Validate.begin_partial_validation
ctxt
chain_id
~predecessor_level
~predecessor_timestamp
block_header
fitness
| Construction {predecessor_hash; timestamp; block_header_data} ->
let*? predecessor_round = Fitness.round_from_raw predecessor_fitness in
let*? round =
Round.round_of_timestamp
(Constants.round_durations ctxt)
~predecessor_timestamp
~predecessor_round
~timestamp
in
Validate.begin_full_construction
ctxt
chain_id
~predecessor_level
~predecessor_round
~predecessor_timestamp
~predecessor_hash
round
block_header_data.contents
| Partial_construction _ ->
let*? predecessor_round = Fitness.round_from_raw predecessor_fitness in
let*? grandparent_round =
Fitness.predecessor_round_from_raw predecessor_fitness
in
return
(Validate.begin_partial_construction
ctxt
chain_id
~predecessor_level
~predecessor_round
~grandparent_round)
let validate_operation = Validate.validate_operation
let finalize_validation = Validate.finalize_block
type error += Cannot_apply_in_partial_validation
let () =
register_error_kind
`Permanent
~id:"main.begin_application.cannot_apply_in_partial_validation"
~title:"cannot_apply_in_partial_validation"
~description:
"Cannot instantiate an application state using the 'Partial_validation' \
mode."
~pp:(fun ppf () ->
Format.fprintf
ppf
"Cannot instantiate an application state using the \
'Partial_validation' mode.")
Data_encoding.(empty)
(function Cannot_apply_in_partial_validation -> Some () | _ -> None)
(fun () -> Cannot_apply_in_partial_validation)
let begin_application ctxt chain_id mode ~predecessor =
let open Lwt_result_syntax in
let open Alpha_context in
let* ( ctxt,
migration_balance_updates,
migration_operation_results,
predecessor_level,
predecessor_raw_level ) =
prepare_ctxt ctxt ~predecessor mode
in
let predecessor_timestamp = predecessor.timestamp in
let predecessor_fitness = predecessor.fitness in
match mode with
| Application block_header ->
Apply.begin_application
ctxt
chain_id
~migration_balance_updates
~migration_operation_results
~predecessor_fitness
block_header
| Partial_validation _ -> tzfail Cannot_apply_in_partial_validation
| Construction {predecessor_hash; timestamp; block_header_data; _} ->
let*? predecessor_round = Fitness.round_from_raw predecessor_fitness in
Apply.begin_full_construction
ctxt
chain_id
~migration_balance_updates
~migration_operation_results
~predecessor_timestamp
~predecessor_level
~predecessor_round
~predecessor_hash
~timestamp
block_header_data.contents
| Partial_construction {predecessor_hash; _} ->
Apply.begin_partial_construction
ctxt
chain_id
~migration_balance_updates
~migration_operation_results
~predecessor_level:predecessor_raw_level
~predecessor_hash
~predecessor_fitness
let apply_operation = Apply.apply_operation
let finalize_application = Apply.finalize_block
let compare_operations (oph1, op1) (oph2, op2) =
Alpha_context.Operation.compare (oph1, op1) (oph2, op2)
let init chain_id ctxt block_header =
let level = block_header.Block_header.level in
let timestamp = block_header.timestamp in
let predecessor = block_header.predecessor in
let typecheck (ctxt : Alpha_context.context) (script : Alpha_context.Script.t)
=
let allow_forged_in_storage =
false
(* There should be no forged value in bootstrap contracts. *)
in
Script_ir_translator.parse_script
ctxt
~elab_conf:Script_ir_translator_config.(make ~legacy:true ())
~allow_forged_in_storage
script
>>=? fun (Ex_script (Script parsed_script), ctxt) ->
Script_ir_translator.extract_lazy_storage_diff
ctxt
Optimized
parsed_script.storage_type
parsed_script.storage
~to_duplicate:Script_ir_translator.no_lazy_storage_id
~to_update:Script_ir_translator.no_lazy_storage_id
~temporary:false
>>=? fun (storage, lazy_storage_diff, ctxt) ->
Script_ir_translator.unparse_data
ctxt
Optimized
parsed_script.storage_type
storage
>|=? fun (storage, ctxt) ->
let storage = Alpha_context.Script.lazy_expr storage in
(({script with storage}, lazy_storage_diff), ctxt)
in
The cache must be synced at the end of block validation , so we do
so here for the first block in a protocol where ` finalize_block `
is not called .
so here for the first block in a protocol where `finalize_block`
is not called. *)
Alpha_context.Raw_level.of_int32 level >>?= fun raw_level ->
let init_fitness =
Alpha_context.Fitness.create_without_locked_round
~level:raw_level
~round:Alpha_context.Round.zero
~predecessor_round:Alpha_context.Round.zero
in
Alpha_context.prepare_first_block
chain_id
~typecheck
~level
~timestamp
~predecessor
ctxt
>>=? fun ctxt ->
let cache_nonce =
Alpha_context.Cache.cache_nonce_from_block_header
block_header
({
payload_hash = Block_payload_hash.zero;
payload_round = Alpha_context.Round.zero;
liquidity_baking_toggle_vote = Alpha_context.Liquidity_baking.LB_pass;
seed_nonce_hash = None;
proof_of_work_nonce =
Bytes.make Constants_repr.proof_of_work_nonce_size '0';
}
: Alpha_context.Block_header.contents)
in
Alpha_context.Cache.Admin.sync ctxt cache_nonce >>= fun ctxt ->
return
(Alpha_context.finalize ctxt (Alpha_context.Fitness.to_raw init_fitness))
let value_of_key ~chain_id:_ ~predecessor_context:ctxt ~predecessor_timestamp
~predecessor_level:pred_level ~predecessor_fitness:_ ~predecessor:_
~timestamp =
let level = Int32.succ pred_level in
Alpha_context.prepare ctxt ~level ~predecessor_timestamp ~timestamp
>>=? fun (ctxt, _, _) -> return (Apply.value_of_key ctxt)
module Mempool = struct
include Mempool_validation
let init ctxt chain_id ~head_hash ~(head : Block_header.shell_header) =
let open Lwt_result_syntax in
let open Alpha_context in
let* ( ctxt,
_migration_balance_updates,
_migration_operation_results,
head_level,
_head_raw_level ) =
(* We use Partial_construction to factorize the [prepare_ctxt]. *)
prepare_ctxt
ctxt
(Partial_construction
{predecessor_hash = head_hash; timestamp = head.timestamp})
~predecessor:head
in
let*? predecessor_round = Fitness.round_from_raw head.fitness in
let*? grandparent_round = Fitness.predecessor_round_from_raw head.fitness in
return
(init
ctxt
chain_id
~predecessor_level:head_level
~predecessor_round
~predecessor_hash:head_hash
~grandparent_round)
end
Vanity nonce : 7019123279060222
| null | https://raw.githubusercontent.com/tezos/tezos-mirror/c50423992947f9d3bf33f91ec8000f3a0a70bc2d/src/proto_016_PtMumbai/lib_protocol/main.ml | ocaml | ***************************************************************************
Open Source License
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
the rights to use, copy, modify, merge, publish, distribute, sublicense,
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
***************************************************************************
Tezos Protocol Implementation - Protocol Signature Instance
revelations, wallet activations and denunciations
* Circumstances and relevant information for [begin_validation] and
[begin_application] below.
There should be no forged value in bootstrap contracts.
We use Partial_construction to factorize the [prepare_ctxt]. | Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < >
to deal in the Software without restriction , including without limitation
and/or sell copies of the Software , and to permit persons to whom the
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
type block_header_data = Alpha_context.Block_header.protocol_data
type block_header = Alpha_context.Block_header.t = {
shell : Block_header.shell_header;
protocol_data : block_header_data;
}
let block_header_data_encoding =
Alpha_context.Block_header.protocol_data_encoding
type block_header_metadata = Apply_results.block_metadata
let block_header_metadata_encoding = Apply_results.block_metadata_encoding
type operation_data = Alpha_context.packed_protocol_data =
| Operation_data :
'kind Alpha_context.Operation.protocol_data
-> operation_data
let operation_data_encoding = Alpha_context.Operation.protocol_data_encoding
type operation_receipt = Apply_results.packed_operation_metadata =
| Operation_metadata :
'kind Apply_results.operation_metadata
-> operation_receipt
| No_operation_metadata : operation_receipt
let operation_receipt_encoding = Apply_results.operation_metadata_encoding
let operation_data_and_receipt_encoding =
Apply_results.operation_data_and_metadata_encoding
type operation = Alpha_context.packed_operation = {
shell : Operation.shell_header;
protocol_data : operation_data;
}
let acceptable_pass = Alpha_context.Operation.acceptable_pass
let max_block_length = Alpha_context.Block_header.max_header_length
let max_operation_data_length =
Alpha_context.Constants.max_operation_data_length
let validation_passes =
let open Alpha_context.Constants in
Updater.
[
2048 endorsements
{max_size = 2048 * 2048; max_op = Some 2048};
32k of voting operations
{max_size = 32 * 1024; max_op = None};
{
max_size = max_anon_ops_per_block * 1024;
max_op = Some max_anon_ops_per_block;
};
512kB
{max_size = 512 * 1024; max_op = None};
]
let rpc_services =
Alpha_services.register () ;
Services_registration.get_rpc_services ()
type validation_state = Validate.validation_state
type application_state = Apply.application_state
let init_allowed_consensus_operations ctxt ~endorsement_level
~preendorsement_level =
let open Lwt_result_syntax in
let open Alpha_context in
let* ctxt = Delegate.prepare_stake_distribution ctxt in
let* ctxt, allowed_endorsements, allowed_preendorsements =
if Level.(endorsement_level = preendorsement_level) then
let* ctxt, slots =
Baking.endorsing_rights_by_first_slot ctxt endorsement_level
in
let consensus_operations = slots in
return (ctxt, consensus_operations, consensus_operations)
else
let* ctxt, endorsements =
Baking.endorsing_rights_by_first_slot ctxt endorsement_level
in
let* ctxt, preendorsements =
Baking.endorsing_rights_by_first_slot ctxt preendorsement_level
in
return (ctxt, endorsements, preendorsements)
in
let ctxt =
Consensus.initialize_consensus_operation
ctxt
~allowed_endorsements
~allowed_preendorsements
in
return ctxt
type mode =
| Application of block_header
| Partial_validation of block_header
| Construction of {
predecessor_hash : Block_hash.t;
timestamp : Time.t;
block_header_data : block_header_data;
}
| Partial_construction of {
predecessor_hash : Block_hash.t;
timestamp : Time.t;
}
let prepare_ctxt ctxt mode ~(predecessor : Block_header.shell_header) =
let open Lwt_result_syntax in
let open Alpha_context in
let level, timestamp =
match mode with
| Application block_header | Partial_validation block_header ->
(block_header.shell.level, block_header.shell.timestamp)
| Construction {timestamp; _} | Partial_construction {timestamp; _} ->
(Int32.succ predecessor.level, timestamp)
in
let* ctxt, migration_balance_updates, migration_operation_results =
prepare ctxt ~level ~predecessor_timestamp:predecessor.timestamp ~timestamp
in
let*? predecessor_raw_level = Raw_level.of_int32 predecessor.level in
let predecessor_level = Level.from_raw ctxt predecessor_raw_level in
During block ( full or partial ) application or full construction ,
endorsements must be for [ predecessor_level ] and preendorsements ,
if any , for the block 's level . In the ( partial
construction ) , only consensus operations for [ predecessor_level ]
( that is , head 's level ) are allowed ( except for grandparent
endorsements , which are handled differently ) .
endorsements must be for [predecessor_level] and preendorsements,
if any, for the block's level. In the mempool (partial
construction), only consensus operations for [predecessor_level]
(that is, head's level) are allowed (except for grandparent
endorsements, which are handled differently). *)
let preendorsement_level =
match mode with
| Application _ | Partial_validation _ | Construction _ ->
Level.current ctxt
| Partial_construction _ -> predecessor_level
in
let* ctxt =
init_allowed_consensus_operations
ctxt
~endorsement_level:predecessor_level
~preendorsement_level
in
Dal_apply.initialisation ~level:predecessor_level ctxt >>=? fun ctxt ->
return
( ctxt,
migration_balance_updates,
migration_operation_results,
predecessor_level,
predecessor_raw_level )
let begin_validation ctxt chain_id mode ~predecessor =
let open Lwt_result_syntax in
let open Alpha_context in
let* ( ctxt,
_migration_balance_updates,
_migration_operation_results,
predecessor_level,
_predecessor_raw_level ) =
prepare_ctxt ctxt ~predecessor mode
in
let predecessor_timestamp = predecessor.timestamp in
let predecessor_fitness = predecessor.fitness in
match mode with
| Application block_header ->
let*? fitness = Fitness.from_raw block_header.shell.fitness in
Validate.begin_application
ctxt
chain_id
~predecessor_level
~predecessor_timestamp
block_header
fitness
| Partial_validation block_header ->
let*? fitness = Fitness.from_raw block_header.shell.fitness in
Validate.begin_partial_validation
ctxt
chain_id
~predecessor_level
~predecessor_timestamp
block_header
fitness
| Construction {predecessor_hash; timestamp; block_header_data} ->
let*? predecessor_round = Fitness.round_from_raw predecessor_fitness in
let*? round =
Round.round_of_timestamp
(Constants.round_durations ctxt)
~predecessor_timestamp
~predecessor_round
~timestamp
in
Validate.begin_full_construction
ctxt
chain_id
~predecessor_level
~predecessor_round
~predecessor_timestamp
~predecessor_hash
round
block_header_data.contents
| Partial_construction _ ->
let*? predecessor_round = Fitness.round_from_raw predecessor_fitness in
let*? grandparent_round =
Fitness.predecessor_round_from_raw predecessor_fitness
in
return
(Validate.begin_partial_construction
ctxt
chain_id
~predecessor_level
~predecessor_round
~grandparent_round)
let validate_operation = Validate.validate_operation
let finalize_validation = Validate.finalize_block
type error += Cannot_apply_in_partial_validation
let () =
register_error_kind
`Permanent
~id:"main.begin_application.cannot_apply_in_partial_validation"
~title:"cannot_apply_in_partial_validation"
~description:
"Cannot instantiate an application state using the 'Partial_validation' \
mode."
~pp:(fun ppf () ->
Format.fprintf
ppf
"Cannot instantiate an application state using the \
'Partial_validation' mode.")
Data_encoding.(empty)
(function Cannot_apply_in_partial_validation -> Some () | _ -> None)
(fun () -> Cannot_apply_in_partial_validation)
let begin_application ctxt chain_id mode ~predecessor =
let open Lwt_result_syntax in
let open Alpha_context in
let* ( ctxt,
migration_balance_updates,
migration_operation_results,
predecessor_level,
predecessor_raw_level ) =
prepare_ctxt ctxt ~predecessor mode
in
let predecessor_timestamp = predecessor.timestamp in
let predecessor_fitness = predecessor.fitness in
match mode with
| Application block_header ->
Apply.begin_application
ctxt
chain_id
~migration_balance_updates
~migration_operation_results
~predecessor_fitness
block_header
| Partial_validation _ -> tzfail Cannot_apply_in_partial_validation
| Construction {predecessor_hash; timestamp; block_header_data; _} ->
let*? predecessor_round = Fitness.round_from_raw predecessor_fitness in
Apply.begin_full_construction
ctxt
chain_id
~migration_balance_updates
~migration_operation_results
~predecessor_timestamp
~predecessor_level
~predecessor_round
~predecessor_hash
~timestamp
block_header_data.contents
| Partial_construction {predecessor_hash; _} ->
Apply.begin_partial_construction
ctxt
chain_id
~migration_balance_updates
~migration_operation_results
~predecessor_level:predecessor_raw_level
~predecessor_hash
~predecessor_fitness
let apply_operation = Apply.apply_operation
let finalize_application = Apply.finalize_block
let compare_operations (oph1, op1) (oph2, op2) =
Alpha_context.Operation.compare (oph1, op1) (oph2, op2)
let init chain_id ctxt block_header =
let level = block_header.Block_header.level in
let timestamp = block_header.timestamp in
let predecessor = block_header.predecessor in
let typecheck (ctxt : Alpha_context.context) (script : Alpha_context.Script.t)
=
let allow_forged_in_storage =
false
in
Script_ir_translator.parse_script
ctxt
~elab_conf:Script_ir_translator_config.(make ~legacy:true ())
~allow_forged_in_storage
script
>>=? fun (Ex_script (Script parsed_script), ctxt) ->
Script_ir_translator.extract_lazy_storage_diff
ctxt
Optimized
parsed_script.storage_type
parsed_script.storage
~to_duplicate:Script_ir_translator.no_lazy_storage_id
~to_update:Script_ir_translator.no_lazy_storage_id
~temporary:false
>>=? fun (storage, lazy_storage_diff, ctxt) ->
Script_ir_translator.unparse_data
ctxt
Optimized
parsed_script.storage_type
storage
>|=? fun (storage, ctxt) ->
let storage = Alpha_context.Script.lazy_expr storage in
(({script with storage}, lazy_storage_diff), ctxt)
in
The cache must be synced at the end of block validation , so we do
so here for the first block in a protocol where ` finalize_block `
is not called .
so here for the first block in a protocol where `finalize_block`
is not called. *)
Alpha_context.Raw_level.of_int32 level >>?= fun raw_level ->
let init_fitness =
Alpha_context.Fitness.create_without_locked_round
~level:raw_level
~round:Alpha_context.Round.zero
~predecessor_round:Alpha_context.Round.zero
in
Alpha_context.prepare_first_block
chain_id
~typecheck
~level
~timestamp
~predecessor
ctxt
>>=? fun ctxt ->
let cache_nonce =
Alpha_context.Cache.cache_nonce_from_block_header
block_header
({
payload_hash = Block_payload_hash.zero;
payload_round = Alpha_context.Round.zero;
liquidity_baking_toggle_vote = Alpha_context.Liquidity_baking.LB_pass;
seed_nonce_hash = None;
proof_of_work_nonce =
Bytes.make Constants_repr.proof_of_work_nonce_size '0';
}
: Alpha_context.Block_header.contents)
in
Alpha_context.Cache.Admin.sync ctxt cache_nonce >>= fun ctxt ->
return
(Alpha_context.finalize ctxt (Alpha_context.Fitness.to_raw init_fitness))
let value_of_key ~chain_id:_ ~predecessor_context:ctxt ~predecessor_timestamp
~predecessor_level:pred_level ~predecessor_fitness:_ ~predecessor:_
~timestamp =
let level = Int32.succ pred_level in
Alpha_context.prepare ctxt ~level ~predecessor_timestamp ~timestamp
>>=? fun (ctxt, _, _) -> return (Apply.value_of_key ctxt)
module Mempool = struct
include Mempool_validation
let init ctxt chain_id ~head_hash ~(head : Block_header.shell_header) =
let open Lwt_result_syntax in
let open Alpha_context in
let* ( ctxt,
_migration_balance_updates,
_migration_operation_results,
head_level,
_head_raw_level ) =
prepare_ctxt
ctxt
(Partial_construction
{predecessor_hash = head_hash; timestamp = head.timestamp})
~predecessor:head
in
let*? predecessor_round = Fitness.round_from_raw head.fitness in
let*? grandparent_round = Fitness.predecessor_round_from_raw head.fitness in
return
(init
ctxt
chain_id
~predecessor_level:head_level
~predecessor_round
~predecessor_hash:head_hash
~grandparent_round)
end
Vanity nonce : 7019123279060222
|
677b5a75926581973a8eb28b34a9ef46003150241460f5655245940fb9bf7e51 | racket/gui | mrtop.rkt | #lang racket/base
(require racket/class
racket/list
(prefix-in wx: "kernel.rkt")
"lock.rkt"
"helper.rkt"
"const.rkt"
"check.rkt"
"wx.rkt"
"wxtop.rkt"
"wxpanel.rkt"
"wxitem.rkt"
"mrwindow.rkt"
"mrcontainer.rkt"
"app.rkt")
(provide top-level-window<%>
frame%
dialog%
(protect-out root-menu-frame)
get-top-level-windows
get-top-level-focus-window
get-top-level-edit-target-window
send-message-to-window
(protect-out check-top-level-parent/false))
(define top-level-window<%>
(interface (area-container-window<%>)
get-eventspace
on-activate on-traverse-char on-system-menu-char
can-close? on-close
can-exit? on-exit
get-focus-window get-edit-target-window
get-focus-object get-edit-target-object
center move resize
on-message
display-changed))
(define-local-member-name
do-create-status-line
do-set-status-text)
(define basic-top-level-window%
(class* (make-area-container-window% (make-window% #t (make-container% area%))) (top-level-window<%>)
(init mk-wx mismatches label parent)
(init-rest)
(inherit show)
(rename-super [super-set-label set-label])
(private*
[wx-object->proxy
(lambda (o)
(if (is-a? o wx:window%)
(wx->proxy o)
o))])
(override*
[set-label (entry-point
(lambda (l)
(check-label-string/false '(method top-level-window<%> set-label) l)
(send wx set-title (or l ""))
(super-set-label l)))])
(public*
[on-traverse-char (entry-point
(lambda (e)
(check-instance '(method top-level-window<%> on-traverse-char)
wx:key-event% 'key-event% #f e)
(send wx handle-traverse-key e)))]
[on-system-menu-char (entry-point
(lambda (e)
(check-instance '(method top-level-window<%> on-system-menu-char)
wx:key-event% 'key-event% #f e)
(and (eq? #\space (send e get-key-code))
(send e get-meta-down)
(eq? 'windows (system-type))
(send wx system-menu) #t)))]
[get-eventspace (entry-point (lambda () (send wx get-eventspace)))])
(pubment*
[can-close? (lambda () (inner #t can-close?))]
[on-close (lambda () (inner (void) on-close))]
[display-changed (λ () (inner (void) display-changed))])
(public*
[can-exit? (lambda () (can-close?))]
[on-exit (lambda () (on-close) (show #f))]
[on-activate (lambda (x) (void))]
[set-icon (case-lambda
[(i) (send wx set-icon i)]
[(i b) (send wx set-icon i b)]
[(i b l?) (send wx set-icon i b l?)])]
[center (entry-point
(case-lambda
[() (send wx center 'both)]
[(dir) (send wx center dir)]))]
[move (entry-point
(lambda (x y)
(check-position '(method top-level-window<%> move) x)
(check-position '(method top-level-window<%> move) y)
(send wx move x y)))]
[resize (entry-point
(lambda (w h)
(check-dimension '(method top-level-window<%> resize) w)
(check-dimension '(method top-level-window<%> resize) h)
(send wx set-size #f #f w h)))]
[get-focus-window (entry-point
(lambda () (let ([w (send wx get-focus-window)])
(and w (wx->proxy w)))))]
[get-edit-target-window (entry-point
(lambda () (let ([w (send wx get-edit-target-window)])
(and w (wx->proxy w)))))]
[get-focus-object (entry-point
(lambda () (let ([o (send wx get-focus-object)])
(and o (wx-object->proxy o)))))]
[get-edit-target-object (entry-point
(lambda () (let ([o (send wx get-edit-target-object)])
(and o (wx-object->proxy o)))))]
[on-message (lambda (m) (void))])
(define wx #f)
(define mid-panel #f) ;; supports status line
(define wx-panel #f)
(define status-message #f)
(define finish (entry-point
(lambda (top-level hide-panel?)
(set! mid-panel (make-object wx-vertical-panel% #f this top-level null #f))
(send mid-panel skip-subwindow-events? #t)
(send mid-panel skip-enter-leave-events #t)
(send (send mid-panel area-parent) add-child mid-panel)
(set! wx-panel (make-object wx-vertical-panel% #f this mid-panel null #f))
(send wx-panel skip-subwindow-events? #t)
(send wx-panel skip-enter-leave-events #t)
(send (send wx-panel area-parent) add-child wx-panel)
(send top-level set-container wx-panel)
(when hide-panel?
(send mid-panel show #f))
top-level)))
(public*
[do-create-status-line (lambda ()
(unless status-message
(set! status-message (make-object wx-message% this this mid-panel "" -1 -1 null #f))
(send status-message stretchable-in-x #t)))]
[do-set-status-text (lambda (s)
(when status-message
(send status-message set-label s)))])
(override*
[get-client-handle (lambda () (send wx-panel get-client-handle))])
(super-make-object (lambda () (set! wx (mk-wx finish)) wx)
(lambda () wx-panel) (lambda () mid-panel)
mismatches label parent arrow-cursor)))
(define frame%
(class basic-top-level-window%
(init label [parent #f] [width #f] [height #f] [x #f] [y #f] [style null]
;; for inherited keywords
[enabled #t]
[border no-val]
[spacing no-val]
[alignment no-val]
[min-width no-val]
[min-height no-val]
[stretchable-width no-val]
[stretchable-height no-val])
(inherit on-traverse-char on-system-menu-char
do-create-status-line do-set-status-text)
(let ([cwho '(constructor frame)])
(check-label-string cwho label)
(check-top-level-parent/false cwho parent)
(check-init-dimension cwho width)
(check-init-dimension cwho height)
(check-init-position cwho x)
(check-init-position cwho y)
(check-style cwho #f '(no-resize-border no-caption no-system-menu
toolbar-button hide-menu-bar float metal
fullscreen-button fullscreen-aux)
style))
(rename-super [super-on-subwindow-char on-subwindow-char])
(define wx #f)
(define status-line? #f)
(define modified? #f)
(override*
[on-subwindow-char (lambda (w event)
(super-on-subwindow-char w event)
(or (on-menu-char event)
(on-system-menu-char event)
(on-traverse-char event)))])
(public*
[on-menu-char (entry-point
(lambda (e)
(check-instance '(method frame% on-menu-char) wx:key-event% 'key-event% #f e)
(send wx handle-menu-key e)))]
[on-toolbar-button-click (lambda () (void))]
[create-status-line (entry-point (lambda () (unless status-line? (do-create-status-line) (set! status-line? #t))))]
[set-status-text (lambda (s) (do-set-status-text s))]
[has-status-line? (lambda () status-line?)]
[iconize (entry-point (lambda (on?) (send wx iconize on?)))]
[is-iconized? (entry-point (lambda () (send wx iconized?)))]
[maximize (entry-point (lambda (on?) (send wx position-for-initial-show) (send wx maximize on?)))]
[is-maximized? (entry-point (lambda () (send wx is-maximized?)))]
[fullscreen (entry-point (lambda (on?) (send wx fullscreen on?)))]
[is-fullscreened? (entry-point (lambda () (send wx fullscreened?)))]
[get-menu-bar (entry-point (lambda () (let ([mb (send wx get-the-menu-bar)])
(and mb (wx->mred mb)))))]
[modified (entry-point
(case-lambda
[() modified?]
[(m)
(set! modified? m)
(send wx set-modified m)]))])
(as-entry
(lambda ()
(super-new
[mk-wx
(lambda (finish)
(set! wx (finish (make-object wx-frame% this this
(and parent (mred->wx parent)) label
x y ; each can be #f
(or width -1) (or height -1)
style)
#f))
(send wx set-mdi-parent #f)
wx)]
[mismatches
(lambda ()
(let ([cwho '(constructor frame)])
(check-container-ready cwho parent)))]
[label label]
[parent parent]
;; for inherited inits
[enabled enabled]
[border border]
[spacing spacing]
[alignment alignment]
[min-width min-width]
[min-height min-height]
[stretchable-width stretchable-width]
[stretchable-height stretchable-height])))))
(define dialog%
(class basic-top-level-window%
(init label [parent #f] [width #f] [height #f] [x #f] [y #f] [style null]
;; for inherited keywords
[enabled #t]
[border no-val]
[spacing no-val]
[alignment no-val]
[min-width no-val]
[min-height no-val]
[stretchable-width no-val]
[stretchable-height no-val])
(inherit on-traverse-char on-system-menu-char center)
(let ([cwho '(constructor dialog)])
(check-label-string cwho label)
(check-top-level-parent/false cwho parent)
(check-init-position cwho x)
(check-init-position cwho y)
(check-init-dimension cwho width)
(check-init-dimension cwho height)
(check-style cwho #f '(no-caption resize-border no-sheet close-button) style))
(rename-super [super-on-subwindow-char on-subwindow-char])
(define wx #f)
(public*
[show-without-yield (lambda ()
(as-entry
(lambda ()
(send wx call-show #t (lambda () (send wx show-without-yield))))))])
(override*
[on-subwindow-char (lambda (w event)
(super-on-subwindow-char w event)
(or (on-system-menu-char event)
(on-traverse-char event)))])
(as-entry
(lambda ()
(super-new
[mk-wx
(lambda (finish)
(set! wx (finish (make-object wx-dialog% this this
(and parent (mred->wx parent)) label
x y ; each can be #f
(or width 0) (or height 0)
style)
#f))
wx)]
[mismatches
(lambda ()
(let ([cwho '(constructor dialog)])
(check-container-ready cwho parent)))]
[label label]
[parent parent]
;; for inherited inits
[enabled enabled]
[border border]
[spacing spacing]
[alignment alignment]
[min-width min-width]
[min-height min-height]
[stretchable-width stretchable-width]
[stretchable-height stretchable-height])))))
(define (get-top-level-windows)
(remq root-menu-frame (map wx->mred (wx:get-top-level-windows))))
(define (get-top-level-focus-window)
(ormap (lambda (f) (and (send f is-act-on?)
(let ([f (wx->mred f)])
(and f
(not (eq? f root-menu-frame))
f))))
(wx:get-top-level-windows)))
(define (get-top-level-edit-target-window)
(let loop ([l (wx:get-top-level-windows)][f #f][s 0][ms 0])
(if (null? l)
f
(let* ([f2 (car l)]
[f2m (wx->mred f2)]
[s2 (send f2 get-act-date/seconds)]
[ms2 (send f2 get-act-date/milliseconds)])
(if (and (or (not f)
(> s2 s)
(and (= s2 s) (> ms2 ms)))
(not (eq? f2m root-menu-frame)))
(loop (cdr l) f2m s2 ms2)
(loop (cdr l) f s ms))))))
(define (send-message-to-window x y m)
(check-position 'send-message-to-window x)
(check-position 'send-message-to-window y)
(let ([w (wx:location->window x y)])
(and w (let ([f (wx->proxy w)])
(and f
(not (eq? f root-menu-frame))
(send f on-message m))))))
(define (check-top-level-parent/false who p)
(unless (or (not p) (is-a? p frame%) (is-a? p dialog%))
(raise-argument-error (who->name who) "(or/c (is-a?/c frame%) (is-a?/c dialog%) #f)" p)))
(define root-menu-frame
(and (current-eventspace-has-menu-root?)
The very first frame shown is somehow sticky under Cocoa ,
;; so create the root frame, show it , and hide it.
(let* ([f (make-object (class frame%
(define/override (on-exit)
(exit))
(super-make-object "Root" #f 0 0 -9000 -9000
'(no-resize-border no-caption))))]
[wx (mred->wx f)])
(set-root-menu-wx-frame! wx)
(send wx designate-root-frame)
f)))
| null | https://raw.githubusercontent.com/racket/gui/29fb0323b1a6172547d7d0422599137cc65256c3/gui-lib/mred/private/mrtop.rkt | racket | supports status line
for inherited keywords
each can be #f
for inherited inits
for inherited keywords
each can be #f
for inherited inits
so create the root frame, show it , and hide it. | #lang racket/base
(require racket/class
racket/list
(prefix-in wx: "kernel.rkt")
"lock.rkt"
"helper.rkt"
"const.rkt"
"check.rkt"
"wx.rkt"
"wxtop.rkt"
"wxpanel.rkt"
"wxitem.rkt"
"mrwindow.rkt"
"mrcontainer.rkt"
"app.rkt")
(provide top-level-window<%>
frame%
dialog%
(protect-out root-menu-frame)
get-top-level-windows
get-top-level-focus-window
get-top-level-edit-target-window
send-message-to-window
(protect-out check-top-level-parent/false))
(define top-level-window<%>
(interface (area-container-window<%>)
get-eventspace
on-activate on-traverse-char on-system-menu-char
can-close? on-close
can-exit? on-exit
get-focus-window get-edit-target-window
get-focus-object get-edit-target-object
center move resize
on-message
display-changed))
(define-local-member-name
do-create-status-line
do-set-status-text)
(define basic-top-level-window%
(class* (make-area-container-window% (make-window% #t (make-container% area%))) (top-level-window<%>)
(init mk-wx mismatches label parent)
(init-rest)
(inherit show)
(rename-super [super-set-label set-label])
(private*
[wx-object->proxy
(lambda (o)
(if (is-a? o wx:window%)
(wx->proxy o)
o))])
(override*
[set-label (entry-point
(lambda (l)
(check-label-string/false '(method top-level-window<%> set-label) l)
(send wx set-title (or l ""))
(super-set-label l)))])
(public*
[on-traverse-char (entry-point
(lambda (e)
(check-instance '(method top-level-window<%> on-traverse-char)
wx:key-event% 'key-event% #f e)
(send wx handle-traverse-key e)))]
[on-system-menu-char (entry-point
(lambda (e)
(check-instance '(method top-level-window<%> on-system-menu-char)
wx:key-event% 'key-event% #f e)
(and (eq? #\space (send e get-key-code))
(send e get-meta-down)
(eq? 'windows (system-type))
(send wx system-menu) #t)))]
[get-eventspace (entry-point (lambda () (send wx get-eventspace)))])
(pubment*
[can-close? (lambda () (inner #t can-close?))]
[on-close (lambda () (inner (void) on-close))]
[display-changed (λ () (inner (void) display-changed))])
(public*
[can-exit? (lambda () (can-close?))]
[on-exit (lambda () (on-close) (show #f))]
[on-activate (lambda (x) (void))]
[set-icon (case-lambda
[(i) (send wx set-icon i)]
[(i b) (send wx set-icon i b)]
[(i b l?) (send wx set-icon i b l?)])]
[center (entry-point
(case-lambda
[() (send wx center 'both)]
[(dir) (send wx center dir)]))]
[move (entry-point
(lambda (x y)
(check-position '(method top-level-window<%> move) x)
(check-position '(method top-level-window<%> move) y)
(send wx move x y)))]
[resize (entry-point
(lambda (w h)
(check-dimension '(method top-level-window<%> resize) w)
(check-dimension '(method top-level-window<%> resize) h)
(send wx set-size #f #f w h)))]
[get-focus-window (entry-point
(lambda () (let ([w (send wx get-focus-window)])
(and w (wx->proxy w)))))]
[get-edit-target-window (entry-point
(lambda () (let ([w (send wx get-edit-target-window)])
(and w (wx->proxy w)))))]
[get-focus-object (entry-point
(lambda () (let ([o (send wx get-focus-object)])
(and o (wx-object->proxy o)))))]
[get-edit-target-object (entry-point
(lambda () (let ([o (send wx get-edit-target-object)])
(and o (wx-object->proxy o)))))]
[on-message (lambda (m) (void))])
(define wx #f)
(define wx-panel #f)
(define status-message #f)
(define finish (entry-point
(lambda (top-level hide-panel?)
(set! mid-panel (make-object wx-vertical-panel% #f this top-level null #f))
(send mid-panel skip-subwindow-events? #t)
(send mid-panel skip-enter-leave-events #t)
(send (send mid-panel area-parent) add-child mid-panel)
(set! wx-panel (make-object wx-vertical-panel% #f this mid-panel null #f))
(send wx-panel skip-subwindow-events? #t)
(send wx-panel skip-enter-leave-events #t)
(send (send wx-panel area-parent) add-child wx-panel)
(send top-level set-container wx-panel)
(when hide-panel?
(send mid-panel show #f))
top-level)))
(public*
[do-create-status-line (lambda ()
(unless status-message
(set! status-message (make-object wx-message% this this mid-panel "" -1 -1 null #f))
(send status-message stretchable-in-x #t)))]
[do-set-status-text (lambda (s)
(when status-message
(send status-message set-label s)))])
(override*
[get-client-handle (lambda () (send wx-panel get-client-handle))])
(super-make-object (lambda () (set! wx (mk-wx finish)) wx)
(lambda () wx-panel) (lambda () mid-panel)
mismatches label parent arrow-cursor)))
(define frame%
(class basic-top-level-window%
(init label [parent #f] [width #f] [height #f] [x #f] [y #f] [style null]
[enabled #t]
[border no-val]
[spacing no-val]
[alignment no-val]
[min-width no-val]
[min-height no-val]
[stretchable-width no-val]
[stretchable-height no-val])
(inherit on-traverse-char on-system-menu-char
do-create-status-line do-set-status-text)
(let ([cwho '(constructor frame)])
(check-label-string cwho label)
(check-top-level-parent/false cwho parent)
(check-init-dimension cwho width)
(check-init-dimension cwho height)
(check-init-position cwho x)
(check-init-position cwho y)
(check-style cwho #f '(no-resize-border no-caption no-system-menu
toolbar-button hide-menu-bar float metal
fullscreen-button fullscreen-aux)
style))
(rename-super [super-on-subwindow-char on-subwindow-char])
(define wx #f)
(define status-line? #f)
(define modified? #f)
(override*
[on-subwindow-char (lambda (w event)
(super-on-subwindow-char w event)
(or (on-menu-char event)
(on-system-menu-char event)
(on-traverse-char event)))])
(public*
[on-menu-char (entry-point
(lambda (e)
(check-instance '(method frame% on-menu-char) wx:key-event% 'key-event% #f e)
(send wx handle-menu-key e)))]
[on-toolbar-button-click (lambda () (void))]
[create-status-line (entry-point (lambda () (unless status-line? (do-create-status-line) (set! status-line? #t))))]
[set-status-text (lambda (s) (do-set-status-text s))]
[has-status-line? (lambda () status-line?)]
[iconize (entry-point (lambda (on?) (send wx iconize on?)))]
[is-iconized? (entry-point (lambda () (send wx iconized?)))]
[maximize (entry-point (lambda (on?) (send wx position-for-initial-show) (send wx maximize on?)))]
[is-maximized? (entry-point (lambda () (send wx is-maximized?)))]
[fullscreen (entry-point (lambda (on?) (send wx fullscreen on?)))]
[is-fullscreened? (entry-point (lambda () (send wx fullscreened?)))]
[get-menu-bar (entry-point (lambda () (let ([mb (send wx get-the-menu-bar)])
(and mb (wx->mred mb)))))]
[modified (entry-point
(case-lambda
[() modified?]
[(m)
(set! modified? m)
(send wx set-modified m)]))])
(as-entry
(lambda ()
(super-new
[mk-wx
(lambda (finish)
(set! wx (finish (make-object wx-frame% this this
(and parent (mred->wx parent)) label
(or width -1) (or height -1)
style)
#f))
(send wx set-mdi-parent #f)
wx)]
[mismatches
(lambda ()
(let ([cwho '(constructor frame)])
(check-container-ready cwho parent)))]
[label label]
[parent parent]
[enabled enabled]
[border border]
[spacing spacing]
[alignment alignment]
[min-width min-width]
[min-height min-height]
[stretchable-width stretchable-width]
[stretchable-height stretchable-height])))))
(define dialog%
(class basic-top-level-window%
(init label [parent #f] [width #f] [height #f] [x #f] [y #f] [style null]
[enabled #t]
[border no-val]
[spacing no-val]
[alignment no-val]
[min-width no-val]
[min-height no-val]
[stretchable-width no-val]
[stretchable-height no-val])
(inherit on-traverse-char on-system-menu-char center)
(let ([cwho '(constructor dialog)])
(check-label-string cwho label)
(check-top-level-parent/false cwho parent)
(check-init-position cwho x)
(check-init-position cwho y)
(check-init-dimension cwho width)
(check-init-dimension cwho height)
(check-style cwho #f '(no-caption resize-border no-sheet close-button) style))
(rename-super [super-on-subwindow-char on-subwindow-char])
(define wx #f)
(public*
[show-without-yield (lambda ()
(as-entry
(lambda ()
(send wx call-show #t (lambda () (send wx show-without-yield))))))])
(override*
[on-subwindow-char (lambda (w event)
(super-on-subwindow-char w event)
(or (on-system-menu-char event)
(on-traverse-char event)))])
(as-entry
(lambda ()
(super-new
[mk-wx
(lambda (finish)
(set! wx (finish (make-object wx-dialog% this this
(and parent (mred->wx parent)) label
(or width 0) (or height 0)
style)
#f))
wx)]
[mismatches
(lambda ()
(let ([cwho '(constructor dialog)])
(check-container-ready cwho parent)))]
[label label]
[parent parent]
[enabled enabled]
[border border]
[spacing spacing]
[alignment alignment]
[min-width min-width]
[min-height min-height]
[stretchable-width stretchable-width]
[stretchable-height stretchable-height])))))
(define (get-top-level-windows)
(remq root-menu-frame (map wx->mred (wx:get-top-level-windows))))
(define (get-top-level-focus-window)
(ormap (lambda (f) (and (send f is-act-on?)
(let ([f (wx->mred f)])
(and f
(not (eq? f root-menu-frame))
f))))
(wx:get-top-level-windows)))
(define (get-top-level-edit-target-window)
(let loop ([l (wx:get-top-level-windows)][f #f][s 0][ms 0])
(if (null? l)
f
(let* ([f2 (car l)]
[f2m (wx->mred f2)]
[s2 (send f2 get-act-date/seconds)]
[ms2 (send f2 get-act-date/milliseconds)])
(if (and (or (not f)
(> s2 s)
(and (= s2 s) (> ms2 ms)))
(not (eq? f2m root-menu-frame)))
(loop (cdr l) f2m s2 ms2)
(loop (cdr l) f s ms))))))
(define (send-message-to-window x y m)
(check-position 'send-message-to-window x)
(check-position 'send-message-to-window y)
(let ([w (wx:location->window x y)])
(and w (let ([f (wx->proxy w)])
(and f
(not (eq? f root-menu-frame))
(send f on-message m))))))
(define (check-top-level-parent/false who p)
(unless (or (not p) (is-a? p frame%) (is-a? p dialog%))
(raise-argument-error (who->name who) "(or/c (is-a?/c frame%) (is-a?/c dialog%) #f)" p)))
(define root-menu-frame
(and (current-eventspace-has-menu-root?)
The very first frame shown is somehow sticky under Cocoa ,
(let* ([f (make-object (class frame%
(define/override (on-exit)
(exit))
(super-make-object "Root" #f 0 0 -9000 -9000
'(no-resize-border no-caption))))]
[wx (mred->wx f)])
(set-root-menu-wx-frame! wx)
(send wx designate-root-frame)
f)))
|
0b4c8c31200fcd688a21fa3dca9bd61510b1ece0a1c6a12e022b3dff3fc9fe95 | backtracking/mlpost | metaPath.ml | (**************************************************************************)
(* *)
Copyright ( C ) Johannes Kanig ,
, 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 S = Point
open Types
module BaseDefs = struct
type direction = Types.direction
let vec = mkVec
let curl = mkCurl
let noDir = mkNoDir
type joint = Types.joint
let jLine = mkJLine
let jCurve = mkJCurve
let jCurveNoInflex = mkJCurveNoInflex
let jTension = mkJTension
let jControls = mkJControls
type knot = Types.knot
the intention is to add new knots in front ,
* the list has to be reversed for printing
* i. e. the list has to be reversed for printing *)
let of_path p = mkMPAofPA p
let of_metapath p = mkPAofMPA p
let to_path = of_metapath
let to_metapath = of_path
let start k = mkMPAKnot k
let metacycle d j p = mkMPACycle d j p
let fullcircle = mkPAFullCircle
let halfcircle = mkPAHalfCircle
let quartercircle = mkPAQuarterCircle
let unitsquare = mkPAUnitSquare
let cut_after p1 p2 = mkPACutAfter p1 p2
let cut_before p1 p2 = mkPACutBefore p1 p2
let build_cycle l = mkPABuildCycle l
let subpath (f1 : float) (f2 : float) p = mkPASub f1 f2 p
(* let point (f: float) p = mkPTPointOf f p *)
(* let direction (f: float) p = mkPTDirectionOf f p *)
let subpathn = subpath
let length p =
let p = Compute.path p in
float (Spline_lib.length p)
let defaultjoint = jCurve
let defaultdir = noDir
end
include BaseDefs
type t = metapath
type path = Types.path
let knotp ?(l = defaultdir) ?(r = defaultdir) p = Types.mkKnot l p r
let knot ?l ?r ?scale p = knotp ?l (S.p ?scale p) ?r
let knotn ?l ?r p = knotp ?l (S.pt p) ?r
let knotlist = List.map (fun (x, y, z) -> Types.mkKnot x y z)
let cycle ?(dir = defaultdir) ?(style = defaultjoint) p = metacycle dir style p
let concat ?(style = defaultjoint) p k = mkMPAConcat k style p
(* construct a path with a given style from a knot list *)
let pathk ?style = function
| [] -> failwith "empty path is not allowed"
| x :: xs -> List.fold_left (fun p knot -> concat ?style p knot) (start x) xs
let pathp ?style l = pathk ?style (List.map knotp l)
let pathn ?style l = pathp ?style (List.map Point.pt l)
let path ?style ?scale l =
let sc = S.ptlist ?scale in
pathp ?style (sc l)
(* construct a path with knot list and joint list *)
let jointpathk lp lj =
try
List.fold_left2
(fun acc j k -> mkMPAConcat k j acc)
(start (List.hd lp))
lj (List.tl lp)
with Invalid_argument _ ->
invalid_arg
"jointpathk : the list of knot must be one more than the list of join"
let jointpathp lp lj = jointpathk (List.map knotp lp) lj
let jointpathn lp lj = jointpathk (List.map knotn lp) lj
let jointpath ?scale lp lj = jointpathk (List.map (knot ?scale) lp) lj
let append ?(style = defaultjoint) p1 p2 = mkMPAAppend p1 style p2
| null | https://raw.githubusercontent.com/backtracking/mlpost/bd4305289fd64d531b9f42d64dd641d72ab82fd5/src/metaPath.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.
************************************************************************
let point (f: float) p = mkPTPointOf f p
let direction (f: float) p = mkPTDirectionOf f p
construct a path with a given style from a knot list
construct a path with knot list and joint list | Copyright ( C ) Johannes Kanig ,
, and
modify it under the terms of the GNU Library General Public
License version 2.1 , with the special exception on linking
module S = Point
open Types
module BaseDefs = struct
type direction = Types.direction
let vec = mkVec
let curl = mkCurl
let noDir = mkNoDir
type joint = Types.joint
let jLine = mkJLine
let jCurve = mkJCurve
let jCurveNoInflex = mkJCurveNoInflex
let jTension = mkJTension
let jControls = mkJControls
type knot = Types.knot
the intention is to add new knots in front ,
* the list has to be reversed for printing
* i. e. the list has to be reversed for printing *)
let of_path p = mkMPAofPA p
let of_metapath p = mkPAofMPA p
let to_path = of_metapath
let to_metapath = of_path
let start k = mkMPAKnot k
let metacycle d j p = mkMPACycle d j p
let fullcircle = mkPAFullCircle
let halfcircle = mkPAHalfCircle
let quartercircle = mkPAQuarterCircle
let unitsquare = mkPAUnitSquare
let cut_after p1 p2 = mkPACutAfter p1 p2
let cut_before p1 p2 = mkPACutBefore p1 p2
let build_cycle l = mkPABuildCycle l
let subpath (f1 : float) (f2 : float) p = mkPASub f1 f2 p
let subpathn = subpath
let length p =
let p = Compute.path p in
float (Spline_lib.length p)
let defaultjoint = jCurve
let defaultdir = noDir
end
include BaseDefs
type t = metapath
type path = Types.path
let knotp ?(l = defaultdir) ?(r = defaultdir) p = Types.mkKnot l p r
let knot ?l ?r ?scale p = knotp ?l (S.p ?scale p) ?r
let knotn ?l ?r p = knotp ?l (S.pt p) ?r
let knotlist = List.map (fun (x, y, z) -> Types.mkKnot x y z)
let cycle ?(dir = defaultdir) ?(style = defaultjoint) p = metacycle dir style p
let concat ?(style = defaultjoint) p k = mkMPAConcat k style p
let pathk ?style = function
| [] -> failwith "empty path is not allowed"
| x :: xs -> List.fold_left (fun p knot -> concat ?style p knot) (start x) xs
let pathp ?style l = pathk ?style (List.map knotp l)
let pathn ?style l = pathp ?style (List.map Point.pt l)
let path ?style ?scale l =
let sc = S.ptlist ?scale in
pathp ?style (sc l)
let jointpathk lp lj =
try
List.fold_left2
(fun acc j k -> mkMPAConcat k j acc)
(start (List.hd lp))
lj (List.tl lp)
with Invalid_argument _ ->
invalid_arg
"jointpathk : the list of knot must be one more than the list of join"
let jointpathp lp lj = jointpathk (List.map knotp lp) lj
let jointpathn lp lj = jointpathk (List.map knotn lp) lj
let jointpath ?scale lp lj = jointpathk (List.map (knot ?scale) lp) lj
let append ?(style = defaultjoint) p1 p2 = mkMPAAppend p1 style p2
|
88cc2fba7c14f711997a5f4fa7705af7b6675dc582fdf9be3a35edfe087f460d | dnadales/sandbox | CloudFilesExceptions.hs | # LANGUAGE DeriveFunctor #
-- | How do we deal with fatal errors at the IO layer?
--
module CloudFilesExceptions where
import Control.Monad.Free
| Consider the files DSL again , assume we want to deal with two kinds
-- of errors:
--
-- - A file that we want to list does not exist
-- - The connection with the server is refused
--
The first kind of errors seem to be specific to the domain logic , so it
could be encoded in the DSL . The second kind of error seems to be fatal and
-- dependent on the implementation (we might not be using the network at all in
-- our interpreter).
--
-- So the question is how do we encode the error handling logic, and how do we
-- deal with the fatal errors?
--
-- The fact that non-fatal errors can arise as the result of a command can be
-- modeled by changing the return type in the command that can originate
errors . Assume that can fail . Then we have the following
-- functor:
data CloudFilesF a = SaveFile Path Bytes a
| ListFiles Path (Result -> a)
deriving Functor
type Path = String
type Bytes = String
type Result = Either String [Path]
type ClouldFilesM = Free CloudFilesF
saveFile :: Path -> Bytes -> ClouldFilesM ()
saveFile path bytes = liftF $ SaveFile path bytes ()
-- Free (SaveFile path bytes (Pure ()))
listFiles :: Path -> ClouldFilesM Result
listFiles path = Free (ListFiles path Pure)
-- | Some sample program
prog0 :: ClouldFilesM [Path]
prog0 = do
saveFile "/myfolder/pepino" "verde"
saveFile "/myfolder/tomate" "rojo"
res <- listFiles "/myfolder"
case res of
Left err -> return []
Right xs -> return xs
-- | A simple interpreter.
interp :: CloudFilesF a -> IO a
interp (SaveFile path bytes next) = do
-- What if a fatal exception would occur here?
putStrLn $ "Saving " ++ bytes ++ " to " ++ path
return next
| null | https://raw.githubusercontent.com/dnadales/sandbox/401c4f0fac5f8044fb6e2e443bacddce6f135b4b/free-monads/src/CloudFilesExceptions.hs | haskell | | How do we deal with fatal errors at the IO layer?
of errors:
- A file that we want to list does not exist
- The connection with the server is refused
dependent on the implementation (we might not be using the network at all in
our interpreter).
So the question is how do we encode the error handling logic, and how do we
deal with the fatal errors?
The fact that non-fatal errors can arise as the result of a command can be
modeled by changing the return type in the command that can originate
functor:
Free (SaveFile path bytes (Pure ()))
| Some sample program
| A simple interpreter.
What if a fatal exception would occur here? | # LANGUAGE DeriveFunctor #
module CloudFilesExceptions where
import Control.Monad.Free
| Consider the files DSL again , assume we want to deal with two kinds
The first kind of errors seem to be specific to the domain logic , so it
could be encoded in the DSL . The second kind of error seems to be fatal and
errors . Assume that can fail . Then we have the following
data CloudFilesF a = SaveFile Path Bytes a
| ListFiles Path (Result -> a)
deriving Functor
type Path = String
type Bytes = String
type Result = Either String [Path]
type ClouldFilesM = Free CloudFilesF
saveFile :: Path -> Bytes -> ClouldFilesM ()
saveFile path bytes = liftF $ SaveFile path bytes ()
listFiles :: Path -> ClouldFilesM Result
listFiles path = Free (ListFiles path Pure)
prog0 :: ClouldFilesM [Path]
prog0 = do
saveFile "/myfolder/pepino" "verde"
saveFile "/myfolder/tomate" "rojo"
res <- listFiles "/myfolder"
case res of
Left err -> return []
Right xs -> return xs
interp :: CloudFilesF a -> IO a
interp (SaveFile path bytes next) = do
putStrLn $ "Saving " ++ bytes ++ " to " ++ path
return next
|
9073005da18d622ce464658a6d7e91c2cae17ada461fe788c4e8e430cb308471 | walmartlabs/lacinia | tracing.clj | Copyright ( c ) 2020 - present Walmart , Inc.
;
Licensed under the Apache License , Version 2.0 ( the " License " )
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; -2.0
;
; Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
(ns com.walmartlabs.lacinia.tracing
"Support for tracing of requests, as per the
[Apollo tracing specification](-tracing)."
{:added "0.38.0"}
(:import
(java.time.format DateTimeFormatter)
(java.time ZonedDateTime ZoneOffset)))
(defn timestamp
"Returns the current time as a RFC-3339 string."
[]
(.format DateTimeFormatter/ISO_INSTANT (ZonedDateTime/now ZoneOffset/UTC)))
(defn duration
"Returns the number of nanoseconds since the start offset."
[start-offset]
(- (System/nanoTime) start-offset))
(defn create-timing-start
"Captures the initial timing information that is used later to calculate
offset from the start time (via [[offset-from-start]])."
[]
{:start-time (timestamp)
:start-nanos (System/nanoTime)})
(defn offset-from-start
"Given the initial timing information from [[create-timing-start]], calculates
the start offset for an operation, as a number of nanoseconds."
[timing-start]
(-> timing-start :start-nanos duration))
(defn ^:private xf-phase
[phase]
(let [{:keys [start-offset duration]} phase]
{:startOffset start-offset
:duration duration}))
(defn inject-tracing
"Injects the tracing data into result map, under :extensions."
[result timing-start parse-phase validation-phase resolver-timings]
(let [{:keys [start-time start-nanos]} timing-start]
(assoc-in result [:extensions :tracing]
{:version 1
:startTime start-time
:endTime (timestamp)
:duration (duration start-nanos)
:parsing (xf-phase parse-phase)
:validation (xf-phase validation-phase)
:execution {:resolvers resolver-timings}})))
(defn enable-tracing
"Modifies the application context to enable tracing.
Tracing can signficantly slow down execution of the query document, both because
of the essential overhead, and because certain optimizations are disabled during a traced
request."
[context]
(assoc context ::enabled? true))
| null | https://raw.githubusercontent.com/walmartlabs/lacinia/88bf46f197bfed645d7767fcfe2bfa39e8b00b27/src/com/walmartlabs/lacinia/tracing.clj | clojure |
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. | Copyright ( c ) 2020 - present Walmart , Inc.
Licensed under the Apache License , Version 2.0 ( the " License " )
distributed under the License is distributed on an " AS IS " BASIS ,
(ns com.walmartlabs.lacinia.tracing
"Support for tracing of requests, as per the
[Apollo tracing specification](-tracing)."
{:added "0.38.0"}
(:import
(java.time.format DateTimeFormatter)
(java.time ZonedDateTime ZoneOffset)))
(defn timestamp
"Returns the current time as a RFC-3339 string."
[]
(.format DateTimeFormatter/ISO_INSTANT (ZonedDateTime/now ZoneOffset/UTC)))
(defn duration
"Returns the number of nanoseconds since the start offset."
[start-offset]
(- (System/nanoTime) start-offset))
(defn create-timing-start
"Captures the initial timing information that is used later to calculate
offset from the start time (via [[offset-from-start]])."
[]
{:start-time (timestamp)
:start-nanos (System/nanoTime)})
(defn offset-from-start
"Given the initial timing information from [[create-timing-start]], calculates
the start offset for an operation, as a number of nanoseconds."
[timing-start]
(-> timing-start :start-nanos duration))
(defn ^:private xf-phase
[phase]
(let [{:keys [start-offset duration]} phase]
{:startOffset start-offset
:duration duration}))
(defn inject-tracing
"Injects the tracing data into result map, under :extensions."
[result timing-start parse-phase validation-phase resolver-timings]
(let [{:keys [start-time start-nanos]} timing-start]
(assoc-in result [:extensions :tracing]
{:version 1
:startTime start-time
:endTime (timestamp)
:duration (duration start-nanos)
:parsing (xf-phase parse-phase)
:validation (xf-phase validation-phase)
:execution {:resolvers resolver-timings}})))
(defn enable-tracing
"Modifies the application context to enable tracing.
Tracing can signficantly slow down execution of the query document, both because
of the essential overhead, and because certain optimizations are disabled during a traced
request."
[context]
(assoc context ::enabled? true))
|
c7cfe139ba47d2a2f41f22ab3678fd15e5243ddce87d6ca6a94c2379d879e0d6 | thierry-martinez/stdcompat | printexc.mli | type t = exn = ..
val to_string : exn -> string
val print : ('a -> 'b) -> 'a -> 'b
val catch : ('a -> 'b) -> 'a -> 'b
val print_backtrace : out_channel -> unit
val get_backtrace : unit -> string
val record_backtrace : bool -> unit
val backtrace_status : unit -> bool
val register_printer : (exn -> string option) -> unit
type raw_backtrace
val get_raw_backtrace : unit -> raw_backtrace
val print_raw_backtrace : out_channel -> raw_backtrace -> unit
val raw_backtrace_to_string : raw_backtrace -> string
external raise_with_backtrace :
exn -> raw_backtrace -> 'a = "%raise_with_backtrace"
val get_callstack : int -> raw_backtrace
val set_uncaught_exception_handler : (exn -> raw_backtrace -> unit) -> unit
type backtrace_slot
val backtrace_slots : raw_backtrace -> backtrace_slot array option
type location =
{
filename: string ;
line_number: int ;
start_char: int ;
end_char: int }
module Slot :
sig
type t = backtrace_slot
val is_raise : t -> bool
val is_inline : t -> bool
val location : t -> location option
val format : int -> t -> string option
end
type raw_backtrace_slot
val raw_backtrace_length : raw_backtrace -> int
val get_raw_backtrace_slot : raw_backtrace -> int -> raw_backtrace_slot
val convert_raw_backtrace_slot : raw_backtrace_slot -> backtrace_slot
val get_raw_backtrace_next_slot :
raw_backtrace_slot -> raw_backtrace_slot option
val exn_slot_id : exn -> int
val exn_slot_name : exn -> string
| null | https://raw.githubusercontent.com/thierry-martinez/stdcompat/83d786cdb17fae0caadf5c342e283c3dcfee2279/interfaces/4.08/printexc.mli | ocaml | type t = exn = ..
val to_string : exn -> string
val print : ('a -> 'b) -> 'a -> 'b
val catch : ('a -> 'b) -> 'a -> 'b
val print_backtrace : out_channel -> unit
val get_backtrace : unit -> string
val record_backtrace : bool -> unit
val backtrace_status : unit -> bool
val register_printer : (exn -> string option) -> unit
type raw_backtrace
val get_raw_backtrace : unit -> raw_backtrace
val print_raw_backtrace : out_channel -> raw_backtrace -> unit
val raw_backtrace_to_string : raw_backtrace -> string
external raise_with_backtrace :
exn -> raw_backtrace -> 'a = "%raise_with_backtrace"
val get_callstack : int -> raw_backtrace
val set_uncaught_exception_handler : (exn -> raw_backtrace -> unit) -> unit
type backtrace_slot
val backtrace_slots : raw_backtrace -> backtrace_slot array option
type location =
{
filename: string ;
line_number: int ;
start_char: int ;
end_char: int }
module Slot :
sig
type t = backtrace_slot
val is_raise : t -> bool
val is_inline : t -> bool
val location : t -> location option
val format : int -> t -> string option
end
type raw_backtrace_slot
val raw_backtrace_length : raw_backtrace -> int
val get_raw_backtrace_slot : raw_backtrace -> int -> raw_backtrace_slot
val convert_raw_backtrace_slot : raw_backtrace_slot -> backtrace_slot
val get_raw_backtrace_next_slot :
raw_backtrace_slot -> raw_backtrace_slot option
val exn_slot_id : exn -> int
val exn_slot_name : exn -> string
| |
afee2f8f7fd30bd419dcf1c6254c56af54cb1628c10a0ce366b1284b23e5c077 | vereis/jarlang | dict.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 2000 - 2016 . All Rights Reserved .
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% %CopyrightEnd%
%%
We use the dynamic hashing techniques by Per - as
described in " The Design and Implementation of Dynamic Hashing for
Sets and Tables in Icon " by and Townsend . Much of the
%% terminology comes from that paper as well.
%%
%% The segments are all of the same fixed size and we just keep
%% increasing the size of the top tuple as the table grows. At the
%% end of the segments tuple we keep an empty segment which we use
%% when we expand the segments. The segments are expanded by doubling
every time n reaches instead of increasing the tuple one
%% element at a time. It is easier and does not seem detrimental to
%% speed. The same applies when contracting the segments.
%%
%% Note that as the order of the keys is undefined we may freely
%% reorder keys within a bucket.
-module(dict).
%% Standard interface.
-export([new/0,is_key/2,to_list/1,from_list/1,size/1,is_empty/1]).
-export([fetch/2,find/2,fetch_keys/1,erase/2,take/2]).
-export([store/3,append/3,append_list/3,update/3,update/4,update_counter/3]).
-export([fold/3,map/2,filter/2,merge/3]).
-export_type([dict/0, dict/2]).
%% Low-level interface.
%%-export([get_slot/2,get_bucket/2,on_bucket/3,fold_dict/3,
] ) .
%% Note: mk_seg/1 must be changed too if seg_size is changed.
-define(seg_size, 16).
-define(max_seg, 32).
-define(expand_load, 5).
-define(contract_load, 3).
-define(exp_size, (?seg_size * ?expand_load)).
-define(con_size, (?seg_size * ?contract_load)).
-type segs(_Key, _Value) :: tuple().
%% Define a hashtable. The default values are the standard ones.
-record(dict,
{size=0 :: non_neg_integer(), % Number of elements
n=?seg_size :: non_neg_integer(), % Number of active slots
maxn=?seg_size :: non_neg_integer(), % Maximum slots
Buddy slot offset
exp_size=?exp_size :: non_neg_integer(), % Size to expand at
con_size=?con_size :: non_neg_integer(), % Size to contract at
empty :: tuple(), % Empty segment
segs :: segs(_, _) % Segments
}).
-type dict() :: dict(_, _).
-opaque dict(Key, Value) :: #dict{segs :: segs(Key, Value)}.
-define(kv(K,V), [K|V]). % Key-Value pair format
-define(kv(K , V ) , { K , V } ) . % Key - Value pair format
-spec new() -> dict().
new() ->
Empty = mk_seg(?seg_size),
#dict{empty=Empty,segs={Empty}}.
-spec is_key(Key, Dict) -> boolean() when
Dict :: dict(Key, Value :: term()).
is_key(Key, D) ->
Slot = get_slot(D, Key),
Bkt = get_bucket(D, Slot),
find_key(Key, Bkt).
find_key(K, [?kv(K,_Val)|_]) -> true;
find_key(K, [_|Bkt]) -> find_key(K, Bkt);
find_key(_, []) -> false.
-spec to_list(Dict) -> List when
Dict :: dict(Key, Value),
List :: [{Key, Value}].
to_list(D) ->
fold(fun (Key, Val, List) -> [{Key,Val}|List] end, [], D).
-spec from_list(List) -> Dict when
Dict :: dict(Key, Value),
List :: [{Key, Value}].
from_list(L) ->
lists:foldl(fun ({K,V}, D) -> store(K, V, D) end, new(), L).
-spec size(Dict) -> non_neg_integer() when
Dict :: dict().
size(#dict{size=N}) when is_integer(N), N >= 0 -> N.
-spec is_empty(Dict) -> boolean() when
Dict :: dict().
is_empty(#dict{size=N}) -> N =:= 0.
-spec fetch(Key, Dict) -> Value when
Dict :: dict(Key, Value).
fetch(Key, D) ->
Slot = get_slot(D, Key),
Bkt = get_bucket(D, Slot),
try fetch_val(Key, Bkt)
catch
badarg -> erlang:error(badarg, [Key, D])
end.
fetch_val(K, [?kv(K,Val)|_]) -> Val;
fetch_val(K, [_|Bkt]) -> fetch_val(K, Bkt);
fetch_val(_, []) -> throw(badarg).
-spec find(Key, Dict) -> {'ok', Value} | 'error' when
Dict :: dict(Key, Value).
find(Key, D) ->
Slot = get_slot(D, Key),
Bkt = get_bucket(D, Slot),
find_val(Key, Bkt).
find_val(K, [?kv(K,Val)|_]) -> {ok,Val};
find_val(K, [_|Bkt]) -> find_val(K, Bkt);
find_val(_, []) -> error.
-spec fetch_keys(Dict) -> Keys when
Dict :: dict(Key, Value :: term()),
Keys :: [Key].
fetch_keys(D) ->
fold(fun (Key, _Val, Keys) -> [Key|Keys] end, [], D).
-spec erase(Key, Dict1) -> Dict2 when
Dict1 :: dict(Key, Value),
Dict2 :: dict(Key, Value).
%% Erase all elements with key Key.
erase(Key, D0) ->
Slot = get_slot(D0, Key),
{D1,Dc} = on_bucket(fun (B0) -> erase_key(Key, B0) end,
D0, Slot),
maybe_contract(D1, Dc).
erase_key(Key, [?kv(Key,_Val)|Bkt]) -> {Bkt,1};
erase_key(Key, [E|Bkt0]) ->
{Bkt1,Dc} = erase_key(Key, Bkt0),
{[E|Bkt1],Dc};
erase_key(_, []) -> {[],0}.
-spec take(Key, Dict) -> {Value, Dict1} | error when
Dict :: dict(Key, Value),
Dict1 :: dict(Key, Value),
Key :: term(),
Value :: term().
take(Key, D0) ->
Slot = get_slot(D0, Key),
case on_bucket(fun (B0) -> take_key(Key, B0) end, D0, Slot) of
{D1,{Value,Dc}} ->
{Value, maybe_contract(D1, Dc)};
{_,error} -> error
end.
take_key(Key, [?kv(Key,Val)|Bkt]) ->
{Bkt,{Val,1}};
take_key(Key, [E|Bkt0]) ->
{Bkt1,Res} = take_key(Key, Bkt0),
{[E|Bkt1],Res};
take_key(_, []) -> {[],error}.
-spec store(Key, Value, Dict1) -> Dict2 when
Dict1 :: dict(Key, Value),
Dict2 :: dict(Key, Value).
store(Key, Val, D0) ->
Slot = get_slot(D0, Key),
{D1,Ic} = on_bucket(fun (B0) -> store_bkt_val(Key, Val, B0) end,
D0, Slot),
maybe_expand(D1, Ic).
store_bkt_val(Key , , Bucket ) - > { NewBucket , PutCount } .
store_bkt_val(Key, New, [?kv(Key,_Old)|Bkt]) -> {[?kv(Key,New)|Bkt],0};
store_bkt_val(Key, New, [Other|Bkt0]) ->
{Bkt1,Ic} = store_bkt_val(Key, New, Bkt0),
{[Other|Bkt1],Ic};
store_bkt_val(Key, New, []) -> {[?kv(Key,New)],1}.
-spec append(Key, Value, Dict1) -> Dict2 when
Dict1 :: dict(Key, Value),
Dict2 :: dict(Key, Value).
append(Key, Val, D0) ->
Slot = get_slot(D0, Key),
{D1,Ic} = on_bucket(fun (B0) -> append_bkt(Key, Val, B0) end,
D0, Slot),
maybe_expand(D1, Ic).
append_bkt(Key , , Bucket ) - > { NewBucket , PutCount } .
append_bkt(Key, Val, [?kv(Key,Bag)|Bkt]) -> {[?kv(Key,Bag ++ [Val])|Bkt],0};
append_bkt(Key, Val, [Other|Bkt0]) ->
{Bkt1,Ic} = append_bkt(Key, Val, Bkt0),
{[Other|Bkt1],Ic};
append_bkt(Key, Val, []) -> {[?kv(Key,[Val])],1}.
-spec append_list(Key, ValList, Dict1) -> Dict2 when
Dict1 :: dict(Key, Value),
Dict2 :: dict(Key, Value),
ValList :: [Value].
append_list(Key, L, D0) ->
Slot = get_slot(D0, Key),
{D1,Ic} = on_bucket(fun (B0) -> app_list_bkt(Key, L, B0) end,
D0, Slot),
maybe_expand(D1, Ic).
app_list_bkt(Key , L , Bucket ) - > { NewBucket , PutCount } .
app_list_bkt(Key, L, [?kv(Key,Bag)|Bkt]) -> {[?kv(Key,Bag ++ L)|Bkt],0};
app_list_bkt(Key, L, [Other|Bkt0]) ->
{Bkt1,Ic} = app_list_bkt(Key, L, Bkt0),
{[Other|Bkt1],Ic};
app_list_bkt(Key, L, []) -> {[?kv(Key,L)],1}.
%% %% first_key(Table) -> {ok,Key} | error.
% % Find the " first " key in a Table .
first_key(T ) - >
case next_bucket(T , 1 ) of
[ ? kv(K , Val)|Bkt ] - > { ok , K } ;
%% [] -> error %No elements
%% end.
%% next_bucket(T, Slot) when Slot > T#dict.n -> [];
%% next_bucket(T, Slot) ->
%% case get_bucket(T, Slot) of
[ ] - > next_bucket(T , Slot+1 ) ; % Empty bucket
%% B -> B
%% end.
% % next_key(Table , Key ) - > { ok , NextKey } | error .
%% next_key(T, Key) ->
%% Slot = get_slot(T, Key),
%% B = get_bucket(T, Slot),
%% %% Find a bucket with something in it.
%% Bkt = case bucket_after_key(Key, B) of
%% no_key -> exit(badarg);
[ ] - > next_bucket(T , Slot+1 ) ;
%% Rest -> Rest
%% end,
case of
[ ? kv(Next , Val)| _ ] - > { ok , Next } ;
%% [] -> error %We have reached the end!
%% end.
bucket_after_key(Key , [ ? kv(Key , Val)|Bkt ] ) - > Bkt ;
%% bucket_after_key(Key, [Other|Bkt]) ->
bucket_after_key(Key , ) ;
%% bucket_after_key(Key, []) -> no_key. %Key not found!
% % on_key(Fun , Key , Dictionary ) - > Dictionary .
on_key(F , Key , D0 ) - >
Slot = get_slot(D0 , Key ) ,
{ D1,Dc } = on_bucket(fun ( ) - > on_key_bkt(Key , F , ) end ,
D0 , Slot ) ,
%% maybe_contract(D1, Dc).
on_key_bkt(Key , F , [ ? kv(Key , Val)|Bkt ] ) - >
case F(Val ) of
{ ok , New } - > { [ ? kv(Key , New)|Bkt],0 } ;
%% erase -> {Bkt,1}
%% end;
%% on_key_bkt(Key, F, [Other|Bkt0]) ->
%% {Bkt1,Dc} = on_key_bkt(Key, F, Bkt0),
%% {[Other|Bkt1],Dc}.
-spec update(Key, Fun, Dict1) -> Dict2 when
Dict1 :: dict(Key, Value),
Dict2 :: dict(Key, Value),
Fun :: fun((Value1 :: Value) -> Value2 :: Value).
update(Key, F, D0) ->
Slot = get_slot(D0, Key),
try on_bucket(fun (B0) -> update_bkt(Key, F, B0) end, D0, Slot) of
{D1,_Uv} -> D1
catch
badarg -> erlang:error(badarg, [Key, F, D0])
end.
update_bkt(Key, F, [?kv(Key,Val)|Bkt]) ->
Upd = F(Val),
{[?kv(Key,Upd)|Bkt],Upd};
update_bkt(Key, F, [Other|Bkt0]) ->
{Bkt1,Upd} = update_bkt(Key, F, Bkt0),
{[Other|Bkt1],Upd};
update_bkt(_Key, _F, []) ->
throw(badarg).
-spec update(Key, Fun, Initial, Dict1) -> Dict2 when
Dict1 :: dict(Key, Value),
Dict2 :: dict(Key, Value),
Fun :: fun((Value1 :: Value) -> Value2 :: Value),
Initial :: Value.
update(Key, F, Init, D0) ->
Slot = get_slot(D0, Key),
{D1,Ic} = on_bucket(fun (B0) -> update_bkt(Key, F, Init, B0) end,
D0, Slot),
maybe_expand(D1, Ic).
update_bkt(Key, F, _, [?kv(Key,Val)|Bkt]) ->
{[?kv(Key,F(Val))|Bkt],0};
update_bkt(Key, F, I, [Other|Bkt0]) ->
{Bkt1,Ic} = update_bkt(Key, F, I, Bkt0),
{[Other|Bkt1],Ic};
update_bkt(Key, F, I, []) when is_function(F, 1) -> {[?kv(Key,I)],1}.
-spec update_counter(Key, Increment, Dict1) -> Dict2 when
Dict1 :: dict(Key, Value),
Dict2 :: dict(Key, Value),
Increment :: number().
update_counter(Key, Incr, D0) when is_number(Incr) ->
Slot = get_slot(D0, Key),
{D1,Ic} = on_bucket(fun (B0) -> counter_bkt(Key, Incr, B0) end,
D0, Slot),
maybe_expand(D1, Ic).
-dialyzer({no_improper_lists, counter_bkt/3}).
counter_bkt(Key, I, [?kv(Key,Val)|Bkt]) ->
{[?kv(Key,Val+I)|Bkt],0};
counter_bkt(Key, I, [Other|Bkt0]) ->
{Bkt1,Ic} = counter_bkt(Key, I, Bkt0),
{[Other|Bkt1],Ic};
counter_bkt(Key, I, []) -> {[?kv(Key,I)],1}.
-spec fold(Fun, Acc0, Dict) -> Acc1 when
Fun :: fun((Key, Value, AccIn) -> AccOut),
Dict :: dict(Key, Value),
Acc0 :: Acc,
Acc1 :: Acc,
AccIn :: Acc,
AccOut :: Acc.
Fold function Fun over all " bags " in Table and return Accumulator .
fold(F, Acc, D) -> fold_dict(F, Acc, D).
-spec map(Fun, Dict1) -> Dict2 when
Fun :: fun((Key, Value1) -> Value2),
Dict1 :: dict(Key, Value1),
Dict2 :: dict(Key, Value2).
map(F, D) -> map_dict(F, D).
-spec filter(Pred, Dict1) -> Dict2 when
Pred :: fun((Key , Value) -> boolean()),
Dict1 :: dict(Key, Value),
Dict2 :: dict(Key, Value).
filter(F, D) -> filter_dict(F, D).
-spec merge(Fun, Dict1, Dict2) -> Dict3 when
Fun :: fun((Key, Value1, Value2) -> Value),
Dict1 :: dict(Key, Value1),
Dict2 :: dict(Key, Value2),
Dict3 :: dict(Key, Value).
merge(F, D1, D2) when D1#dict.size < D2#dict.size ->
fold_dict(fun (K, V1, D) ->
update(K, fun (V2) -> F(K, V1, V2) end, V1, D)
end, D2, D1);
merge(F, D1, D2) ->
fold_dict(fun (K, V2, D) ->
update(K, fun (V1) -> F(K, V1, V2) end, V2, D)
end, D1, D2).
%% get_slot(Hashdb, Key) -> Slot.
Get the slot . First hash on the new range , if we hit a bucket
%% which has not been split use the unsplit buddy bucket.
get_slot(T, Key) ->
H = erlang:phash(Key, T#dict.maxn),
if
H > T#dict.n -> H - T#dict.bso;
true -> H
end.
%% get_bucket(Hashdb, Slot) -> Bucket.
get_bucket(T, Slot) -> get_bucket_s(T#dict.segs, Slot).
on_bucket(Fun , Hashdb , Slot ) - > { NewHashDb , Result } .
%% Apply Fun to the bucket in Slot and replace the returned bucket.
on_bucket(F, T, Slot) ->
SegI = ((Slot-1) div ?seg_size) + 1,
BktI = ((Slot-1) rem ?seg_size) + 1,
Segs = T#dict.segs,
Seg = element(SegI, Segs),
B0 = element(BktI, Seg),
{B1,Res} = F(B0), %Op on the bucket.
{T#dict{segs=setelement(SegI, Segs, setelement(BktI, Seg, B1))},Res}.
fold_dict(Fun , Acc , Dictionary ) - > Acc .
%% map_dict(Fun, Dictionary) -> Dictionary.
%% filter_dict(Fun, Dictionary) -> Dictionary.
%%
%% Work functions for fold, map and filter operations. These
%% traverse the hash structure rebuilding as necessary. Note we
%% could have implemented map and filter using fold but these are
%% faster. We hope!
fold_dict(F, Acc, #dict{size=0}) when is_function(F, 3) ->
Acc;
fold_dict(F, Acc, D) ->
Segs = D#dict.segs,
fold_segs(F, Acc, Segs, tuple_size(Segs)).
fold_segs(F, Acc, Segs, I) when I >= 1 ->
Seg = element(I, Segs),
fold_segs(F, fold_seg(F, Acc, Seg, tuple_size(Seg)), Segs, I-1);
fold_segs(F, Acc, _, 0) when is_function(F, 3) -> Acc.
fold_seg(F, Acc, Seg, I) when I >= 1 ->
fold_seg(F, fold_bucket(F, Acc, element(I, Seg)), Seg, I-1);
fold_seg(F, Acc, _, 0) when is_function(F, 3) -> Acc.
fold_bucket(F, Acc, [?kv(Key,Val)|Bkt]) ->
fold_bucket(F, F(Key, Val, Acc), Bkt);
fold_bucket(F, Acc, []) when is_function(F, 3) -> Acc.
map_dict(F, #dict{size=0} = Dict) when is_function(F, 2) ->
Dict;
map_dict(F, D) ->
Segs0 = tuple_to_list(D#dict.segs),
Segs1 = map_seg_list(F, Segs0),
D#dict{segs=list_to_tuple(Segs1)}.
map_seg_list(F, [Seg|Segs]) ->
Bkts0 = tuple_to_list(Seg),
Bkts1 = map_bkt_list(F, Bkts0),
[list_to_tuple(Bkts1)|map_seg_list(F, Segs)];
map_seg_list(F, []) when is_function(F, 2) -> [].
map_bkt_list(F, [Bkt0|Bkts]) ->
[map_bucket(F, Bkt0)|map_bkt_list(F, Bkts)];
map_bkt_list(F, []) when is_function(F, 2) -> [].
map_bucket(F, [?kv(Key,Val)|Bkt]) ->
[?kv(Key,F(Key, Val))|map_bucket(F, Bkt)];
map_bucket(F, []) when is_function(F, 2) -> [].
filter_dict(F, #dict{size=0} = Dict) when is_function(F, 2) ->
Dict;
filter_dict(F, D) ->
Segs0 = tuple_to_list(D#dict.segs),
{Segs1,Fc} = filter_seg_list(F, Segs0, [], 0),
maybe_contract(D#dict{segs=list_to_tuple(Segs1)}, Fc).
filter_seg_list(F, [Seg|Segs], Fss, Fc0) ->
Bkts0 = tuple_to_list(Seg),
{Bkts1,Fc1} = filter_bkt_list(F, Bkts0, [], Fc0),
filter_seg_list(F, Segs, [list_to_tuple(Bkts1)|Fss], Fc1);
filter_seg_list(F, [], Fss, Fc) when is_function(F, 2) ->
{lists:reverse(Fss, []),Fc}.
filter_bkt_list(F, [Bkt0|Bkts], Fbs, Fc0) ->
{Bkt1,Fc1} = filter_bucket(F, Bkt0, [], Fc0),
filter_bkt_list(F, Bkts, [Bkt1|Fbs], Fc1);
filter_bkt_list(F, [], Fbs, Fc) when is_function(F, 2) ->
{lists:reverse(Fbs),Fc}.
filter_bucket(F, [?kv(Key,Val)=E|Bkt], Fb, Fc) ->
case F(Key, Val) of
true -> filter_bucket(F, Bkt, [E|Fb], Fc);
false -> filter_bucket(F, Bkt, Fb, Fc+1)
end;
filter_bucket(F, [], Fb, Fc) when is_function(F, 2) ->
{lists:reverse(Fb),Fc}.
get_bucket_s(Segments , Slot ) - > Bucket .
%% put_bucket_s(Segments, Slot, Bucket) -> NewSegments.
get_bucket_s(Segs, Slot) ->
SegI = ((Slot-1) div ?seg_size) + 1,
BktI = ((Slot-1) rem ?seg_size) + 1,
element(BktI, element(SegI, Segs)).
put_bucket_s(Segs, Slot, Bkt) ->
SegI = ((Slot-1) div ?seg_size) + 1,
BktI = ((Slot-1) rem ?seg_size) + 1,
Seg = setelement(BktI, element(SegI, Segs), Bkt),
setelement(SegI, Segs, Seg).
In maybe_expand ( ) , the variable Ic only takes the values 0 or 1 ,
%% but type inference is not strong enough to infer this. Thus, the
%% use of explicit pattern matching and an auxiliary function.
maybe_expand(T, 0) -> maybe_expand_aux(T, 0);
maybe_expand(T, 1) -> maybe_expand_aux(T, 1).
maybe_expand_aux(T0, Ic) when T0#dict.size + Ic > T0#dict.exp_size ->
T = maybe_expand_segs(T0), %Do we need more segments.
N = T#dict.n + 1, %Next slot to expand into
Segs0 = T#dict.segs,
Slot1 = N - T#dict.bso,
B = get_bucket_s(Segs0, Slot1),
Slot2 = N,
[B1|B2] = rehash(B, Slot1, Slot2, T#dict.maxn),
Segs1 = put_bucket_s(Segs0, Slot1, B1),
Segs2 = put_bucket_s(Segs1, Slot2, B2),
T#dict{size=T#dict.size + Ic,
n=N,
exp_size=N * ?expand_load,
con_size=N * ?contract_load,
segs=Segs2};
maybe_expand_aux(T, Ic) -> T#dict{size=T#dict.size + Ic}.
maybe_expand_segs(T) when T#dict.n =:= T#dict.maxn ->
T#dict{maxn=2 * T#dict.maxn,
bso=2 * T#dict.bso,
segs=expand_segs(T#dict.segs, T#dict.empty)};
maybe_expand_segs(T) -> T.
maybe_contract(T, Dc) when T#dict.size - Dc < T#dict.con_size,
T#dict.n > ?seg_size ->
N = T#dict.n,
Slot1 = N - T#dict.bso,
Segs0 = T#dict.segs,
B1 = get_bucket_s(Segs0, Slot1),
Slot2 = N,
B2 = get_bucket_s(Segs0, Slot2),
Segs1 = put_bucket_s(Segs0, Slot1, B1 ++ B2),
Segs2 = put_bucket_s(Segs1, Slot2, []), %Clear the upper bucket
N1 = N - 1,
maybe_contract_segs(T#dict{size=T#dict.size - Dc,
n=N1,
exp_size=N1 * ?expand_load,
con_size=N1 * ?contract_load,
segs=Segs2});
maybe_contract(T, Dc) -> T#dict{size=T#dict.size - Dc}.
maybe_contract_segs(T) when T#dict.n =:= T#dict.bso ->
T#dict{maxn=T#dict.maxn div 2,
bso=T#dict.bso div 2,
segs=contract_segs(T#dict.segs)};
maybe_contract_segs(T) -> T.
rehash(Bucket , , Slot2 , MaxN ) - > [ ] .
%% Yes, we should return a tuple, but this is more fun.
rehash([?kv(Key,_Bag)=KeyBag|T], Slot1, Slot2, MaxN) ->
[L1|L2] = rehash(T, Slot1, Slot2, MaxN),
case erlang:phash(Key, MaxN) of
Slot1 -> [[KeyBag|L1]|L2];
Slot2 -> [L1|[KeyBag|L2]]
end;
rehash([], _Slot1, _Slot2, _MaxN) -> [[]|[]].
%% mk_seg(Size) -> Segment.
mk_seg(16) -> {[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]}.
expand_segs(Segs , EmptySeg ) - > NewSegs .
%% contract_segs(Segs) -> NewSegs.
%% Expand/contract the segment tuple by doubling/halving the number
of segments . We special case the powers of 2 upto 32 , this should
%% catch most case. N.B. the last element in the segments tuple is
%% an extra element containing a default empty segment.
expand_segs({B1}, Empty) ->
{B1,Empty};
expand_segs({B1,B2}, Empty) ->
{B1,B2,Empty,Empty};
expand_segs({B1,B2,B3,B4}, Empty) ->
{B1,B2,B3,B4,Empty,Empty,Empty,Empty};
expand_segs({B1,B2,B3,B4,B5,B6,B7,B8}, Empty) ->
{B1,B2,B3,B4,B5,B6,B7,B8,
Empty,Empty,Empty,Empty,Empty,Empty,Empty,Empty};
expand_segs({B1,B2,B3,B4,B5,B6,B7,B8,B9,B10,B11,B12,B13,B14,B15,B16}, Empty) ->
{B1,B2,B3,B4,B5,B6,B7,B8,B9,B10,B11,B12,B13,B14,B15,B16,
Empty,Empty,Empty,Empty,Empty,Empty,Empty,Empty,
Empty,Empty,Empty,Empty,Empty,Empty,Empty,Empty};
expand_segs(Segs, Empty) ->
list_to_tuple(tuple_to_list(Segs)
++ lists:duplicate(tuple_size(Segs), Empty)).
contract_segs({B1,_}) ->
{B1};
contract_segs({B1,B2,_,_}) ->
{B1,B2};
contract_segs({B1,B2,B3,B4,_,_,_,_}) ->
{B1,B2,B3,B4};
contract_segs({B1,B2,B3,B4,B5,B6,B7,B8,_,_,_,_,_,_,_,_}) ->
{B1,B2,B3,B4,B5,B6,B7,B8};
contract_segs({B1,B2,B3,B4,B5,B6,B7,B8,B9,B10,B11,B12,B13,B14,B15,B16,
_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_}) ->
{B1,B2,B3,B4,B5,B6,B7,B8,B9,B10,B11,B12,B13,B14,B15,B16};
contract_segs(Segs) ->
Ss = tuple_size(Segs) div 2,
list_to_tuple(lists:sublist(tuple_to_list(Segs), 1, Ss)).
| null | https://raw.githubusercontent.com/vereis/jarlang/72105b79c1861aa6c4f51c3b50ba695338aafba4/src/erl/lib/stdlib/dict.erl | erlang |
%CopyrightBegin%
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
%CopyrightEnd%
terminology comes from that paper as well.
The segments are all of the same fixed size and we just keep
increasing the size of the top tuple as the table grows. At the
end of the segments tuple we keep an empty segment which we use
when we expand the segments. The segments are expanded by doubling
element at a time. It is easier and does not seem detrimental to
speed. The same applies when contracting the segments.
Note that as the order of the keys is undefined we may freely
reorder keys within a bucket.
Standard interface.
Low-level interface.
-export([get_slot/2,get_bucket/2,on_bucket/3,fold_dict/3,
Note: mk_seg/1 must be changed too if seg_size is changed.
Define a hashtable. The default values are the standard ones.
Number of elements
Number of active slots
Maximum slots
Size to expand at
Size to contract at
Empty segment
Segments
Key-Value pair format
Key - Value pair format
Erase all elements with key Key.
%% first_key(Table) -> {ok,Key} | error.
% Find the " first " key in a Table .
[] -> error %No elements
end.
next_bucket(T, Slot) when Slot > T#dict.n -> [];
next_bucket(T, Slot) ->
case get_bucket(T, Slot) of
Empty bucket
B -> B
end.
% next_key(Table , Key ) - > { ok , NextKey } | error .
next_key(T, Key) ->
Slot = get_slot(T, Key),
B = get_bucket(T, Slot),
%% Find a bucket with something in it.
Bkt = case bucket_after_key(Key, B) of
no_key -> exit(badarg);
Rest -> Rest
end,
[] -> error %We have reached the end!
end.
bucket_after_key(Key, [Other|Bkt]) ->
bucket_after_key(Key, []) -> no_key. %Key not found!
% on_key(Fun , Key , Dictionary ) - > Dictionary .
maybe_contract(D1, Dc).
erase -> {Bkt,1}
end;
on_key_bkt(Key, F, [Other|Bkt0]) ->
{Bkt1,Dc} = on_key_bkt(Key, F, Bkt0),
{[Other|Bkt1],Dc}.
get_slot(Hashdb, Key) -> Slot.
which has not been split use the unsplit buddy bucket.
get_bucket(Hashdb, Slot) -> Bucket.
Apply Fun to the bucket in Slot and replace the returned bucket.
Op on the bucket.
map_dict(Fun, Dictionary) -> Dictionary.
filter_dict(Fun, Dictionary) -> Dictionary.
Work functions for fold, map and filter operations. These
traverse the hash structure rebuilding as necessary. Note we
could have implemented map and filter using fold but these are
faster. We hope!
put_bucket_s(Segments, Slot, Bucket) -> NewSegments.
but type inference is not strong enough to infer this. Thus, the
use of explicit pattern matching and an auxiliary function.
Do we need more segments.
Next slot to expand into
Clear the upper bucket
Yes, we should return a tuple, but this is more fun.
mk_seg(Size) -> Segment.
contract_segs(Segs) -> NewSegs.
Expand/contract the segment tuple by doubling/halving the number
catch most case. N.B. the last element in the segments tuple is
an extra element containing a default empty segment. | Copyright Ericsson AB 2000 - 2016 . All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
We use the dynamic hashing techniques by Per - as
described in " The Design and Implementation of Dynamic Hashing for
Sets and Tables in Icon " by and Townsend . Much of the
every time n reaches instead of increasing the tuple one
-module(dict).
-export([new/0,is_key/2,to_list/1,from_list/1,size/1,is_empty/1]).
-export([fetch/2,find/2,fetch_keys/1,erase/2,take/2]).
-export([store/3,append/3,append_list/3,update/3,update/4,update_counter/3]).
-export([fold/3,map/2,filter/2,merge/3]).
-export_type([dict/0, dict/2]).
] ) .
-define(seg_size, 16).
-define(max_seg, 32).
-define(expand_load, 5).
-define(contract_load, 3).
-define(exp_size, (?seg_size * ?expand_load)).
-define(con_size, (?seg_size * ?contract_load)).
-type segs(_Key, _Value) :: tuple().
-record(dict,
Buddy slot offset
}).
-type dict() :: dict(_, _).
-opaque dict(Key, Value) :: #dict{segs :: segs(Key, Value)}.
-spec new() -> dict().
new() ->
Empty = mk_seg(?seg_size),
#dict{empty=Empty,segs={Empty}}.
-spec is_key(Key, Dict) -> boolean() when
Dict :: dict(Key, Value :: term()).
is_key(Key, D) ->
Slot = get_slot(D, Key),
Bkt = get_bucket(D, Slot),
find_key(Key, Bkt).
find_key(K, [?kv(K,_Val)|_]) -> true;
find_key(K, [_|Bkt]) -> find_key(K, Bkt);
find_key(_, []) -> false.
-spec to_list(Dict) -> List when
Dict :: dict(Key, Value),
List :: [{Key, Value}].
to_list(D) ->
fold(fun (Key, Val, List) -> [{Key,Val}|List] end, [], D).
-spec from_list(List) -> Dict when
Dict :: dict(Key, Value),
List :: [{Key, Value}].
from_list(L) ->
lists:foldl(fun ({K,V}, D) -> store(K, V, D) end, new(), L).
-spec size(Dict) -> non_neg_integer() when
Dict :: dict().
size(#dict{size=N}) when is_integer(N), N >= 0 -> N.
-spec is_empty(Dict) -> boolean() when
Dict :: dict().
is_empty(#dict{size=N}) -> N =:= 0.
-spec fetch(Key, Dict) -> Value when
Dict :: dict(Key, Value).
fetch(Key, D) ->
Slot = get_slot(D, Key),
Bkt = get_bucket(D, Slot),
try fetch_val(Key, Bkt)
catch
badarg -> erlang:error(badarg, [Key, D])
end.
fetch_val(K, [?kv(K,Val)|_]) -> Val;
fetch_val(K, [_|Bkt]) -> fetch_val(K, Bkt);
fetch_val(_, []) -> throw(badarg).
-spec find(Key, Dict) -> {'ok', Value} | 'error' when
Dict :: dict(Key, Value).
find(Key, D) ->
Slot = get_slot(D, Key),
Bkt = get_bucket(D, Slot),
find_val(Key, Bkt).
find_val(K, [?kv(K,Val)|_]) -> {ok,Val};
find_val(K, [_|Bkt]) -> find_val(K, Bkt);
find_val(_, []) -> error.
-spec fetch_keys(Dict) -> Keys when
Dict :: dict(Key, Value :: term()),
Keys :: [Key].
fetch_keys(D) ->
fold(fun (Key, _Val, Keys) -> [Key|Keys] end, [], D).
-spec erase(Key, Dict1) -> Dict2 when
Dict1 :: dict(Key, Value),
Dict2 :: dict(Key, Value).
erase(Key, D0) ->
Slot = get_slot(D0, Key),
{D1,Dc} = on_bucket(fun (B0) -> erase_key(Key, B0) end,
D0, Slot),
maybe_contract(D1, Dc).
erase_key(Key, [?kv(Key,_Val)|Bkt]) -> {Bkt,1};
erase_key(Key, [E|Bkt0]) ->
{Bkt1,Dc} = erase_key(Key, Bkt0),
{[E|Bkt1],Dc};
erase_key(_, []) -> {[],0}.
-spec take(Key, Dict) -> {Value, Dict1} | error when
Dict :: dict(Key, Value),
Dict1 :: dict(Key, Value),
Key :: term(),
Value :: term().
take(Key, D0) ->
Slot = get_slot(D0, Key),
case on_bucket(fun (B0) -> take_key(Key, B0) end, D0, Slot) of
{D1,{Value,Dc}} ->
{Value, maybe_contract(D1, Dc)};
{_,error} -> error
end.
take_key(Key, [?kv(Key,Val)|Bkt]) ->
{Bkt,{Val,1}};
take_key(Key, [E|Bkt0]) ->
{Bkt1,Res} = take_key(Key, Bkt0),
{[E|Bkt1],Res};
take_key(_, []) -> {[],error}.
-spec store(Key, Value, Dict1) -> Dict2 when
Dict1 :: dict(Key, Value),
Dict2 :: dict(Key, Value).
store(Key, Val, D0) ->
Slot = get_slot(D0, Key),
{D1,Ic} = on_bucket(fun (B0) -> store_bkt_val(Key, Val, B0) end,
D0, Slot),
maybe_expand(D1, Ic).
store_bkt_val(Key , , Bucket ) - > { NewBucket , PutCount } .
store_bkt_val(Key, New, [?kv(Key,_Old)|Bkt]) -> {[?kv(Key,New)|Bkt],0};
store_bkt_val(Key, New, [Other|Bkt0]) ->
{Bkt1,Ic} = store_bkt_val(Key, New, Bkt0),
{[Other|Bkt1],Ic};
store_bkt_val(Key, New, []) -> {[?kv(Key,New)],1}.
-spec append(Key, Value, Dict1) -> Dict2 when
Dict1 :: dict(Key, Value),
Dict2 :: dict(Key, Value).
append(Key, Val, D0) ->
Slot = get_slot(D0, Key),
{D1,Ic} = on_bucket(fun (B0) -> append_bkt(Key, Val, B0) end,
D0, Slot),
maybe_expand(D1, Ic).
append_bkt(Key , , Bucket ) - > { NewBucket , PutCount } .
append_bkt(Key, Val, [?kv(Key,Bag)|Bkt]) -> {[?kv(Key,Bag ++ [Val])|Bkt],0};
append_bkt(Key, Val, [Other|Bkt0]) ->
{Bkt1,Ic} = append_bkt(Key, Val, Bkt0),
{[Other|Bkt1],Ic};
append_bkt(Key, Val, []) -> {[?kv(Key,[Val])],1}.
-spec append_list(Key, ValList, Dict1) -> Dict2 when
Dict1 :: dict(Key, Value),
Dict2 :: dict(Key, Value),
ValList :: [Value].
append_list(Key, L, D0) ->
Slot = get_slot(D0, Key),
{D1,Ic} = on_bucket(fun (B0) -> app_list_bkt(Key, L, B0) end,
D0, Slot),
maybe_expand(D1, Ic).
app_list_bkt(Key , L , Bucket ) - > { NewBucket , PutCount } .
app_list_bkt(Key, L, [?kv(Key,Bag)|Bkt]) -> {[?kv(Key,Bag ++ L)|Bkt],0};
app_list_bkt(Key, L, [Other|Bkt0]) ->
{Bkt1,Ic} = app_list_bkt(Key, L, Bkt0),
{[Other|Bkt1],Ic};
app_list_bkt(Key, L, []) -> {[?kv(Key,L)],1}.
first_key(T ) - >
case next_bucket(T , 1 ) of
[ ? kv(K , Val)|Bkt ] - > { ok , K } ;
[ ] - > next_bucket(T , Slot+1 ) ;
case of
[ ? kv(Next , Val)| _ ] - > { ok , Next } ;
bucket_after_key(Key , [ ? kv(Key , Val)|Bkt ] ) - > Bkt ;
bucket_after_key(Key , ) ;
on_key(F , Key , D0 ) - >
Slot = get_slot(D0 , Key ) ,
{ D1,Dc } = on_bucket(fun ( ) - > on_key_bkt(Key , F , ) end ,
D0 , Slot ) ,
on_key_bkt(Key , F , [ ? kv(Key , Val)|Bkt ] ) - >
case F(Val ) of
{ ok , New } - > { [ ? kv(Key , New)|Bkt],0 } ;
-spec update(Key, Fun, Dict1) -> Dict2 when
Dict1 :: dict(Key, Value),
Dict2 :: dict(Key, Value),
Fun :: fun((Value1 :: Value) -> Value2 :: Value).
update(Key, F, D0) ->
Slot = get_slot(D0, Key),
try on_bucket(fun (B0) -> update_bkt(Key, F, B0) end, D0, Slot) of
{D1,_Uv} -> D1
catch
badarg -> erlang:error(badarg, [Key, F, D0])
end.
update_bkt(Key, F, [?kv(Key,Val)|Bkt]) ->
Upd = F(Val),
{[?kv(Key,Upd)|Bkt],Upd};
update_bkt(Key, F, [Other|Bkt0]) ->
{Bkt1,Upd} = update_bkt(Key, F, Bkt0),
{[Other|Bkt1],Upd};
update_bkt(_Key, _F, []) ->
throw(badarg).
-spec update(Key, Fun, Initial, Dict1) -> Dict2 when
Dict1 :: dict(Key, Value),
Dict2 :: dict(Key, Value),
Fun :: fun((Value1 :: Value) -> Value2 :: Value),
Initial :: Value.
update(Key, F, Init, D0) ->
Slot = get_slot(D0, Key),
{D1,Ic} = on_bucket(fun (B0) -> update_bkt(Key, F, Init, B0) end,
D0, Slot),
maybe_expand(D1, Ic).
update_bkt(Key, F, _, [?kv(Key,Val)|Bkt]) ->
{[?kv(Key,F(Val))|Bkt],0};
update_bkt(Key, F, I, [Other|Bkt0]) ->
{Bkt1,Ic} = update_bkt(Key, F, I, Bkt0),
{[Other|Bkt1],Ic};
update_bkt(Key, F, I, []) when is_function(F, 1) -> {[?kv(Key,I)],1}.
-spec update_counter(Key, Increment, Dict1) -> Dict2 when
Dict1 :: dict(Key, Value),
Dict2 :: dict(Key, Value),
Increment :: number().
update_counter(Key, Incr, D0) when is_number(Incr) ->
Slot = get_slot(D0, Key),
{D1,Ic} = on_bucket(fun (B0) -> counter_bkt(Key, Incr, B0) end,
D0, Slot),
maybe_expand(D1, Ic).
-dialyzer({no_improper_lists, counter_bkt/3}).
counter_bkt(Key, I, [?kv(Key,Val)|Bkt]) ->
{[?kv(Key,Val+I)|Bkt],0};
counter_bkt(Key, I, [Other|Bkt0]) ->
{Bkt1,Ic} = counter_bkt(Key, I, Bkt0),
{[Other|Bkt1],Ic};
counter_bkt(Key, I, []) -> {[?kv(Key,I)],1}.
-spec fold(Fun, Acc0, Dict) -> Acc1 when
Fun :: fun((Key, Value, AccIn) -> AccOut),
Dict :: dict(Key, Value),
Acc0 :: Acc,
Acc1 :: Acc,
AccIn :: Acc,
AccOut :: Acc.
Fold function Fun over all " bags " in Table and return Accumulator .
fold(F, Acc, D) -> fold_dict(F, Acc, D).
-spec map(Fun, Dict1) -> Dict2 when
Fun :: fun((Key, Value1) -> Value2),
Dict1 :: dict(Key, Value1),
Dict2 :: dict(Key, Value2).
map(F, D) -> map_dict(F, D).
-spec filter(Pred, Dict1) -> Dict2 when
Pred :: fun((Key , Value) -> boolean()),
Dict1 :: dict(Key, Value),
Dict2 :: dict(Key, Value).
filter(F, D) -> filter_dict(F, D).
-spec merge(Fun, Dict1, Dict2) -> Dict3 when
Fun :: fun((Key, Value1, Value2) -> Value),
Dict1 :: dict(Key, Value1),
Dict2 :: dict(Key, Value2),
Dict3 :: dict(Key, Value).
merge(F, D1, D2) when D1#dict.size < D2#dict.size ->
fold_dict(fun (K, V1, D) ->
update(K, fun (V2) -> F(K, V1, V2) end, V1, D)
end, D2, D1);
merge(F, D1, D2) ->
fold_dict(fun (K, V2, D) ->
update(K, fun (V1) -> F(K, V1, V2) end, V2, D)
end, D1, D2).
Get the slot . First hash on the new range , if we hit a bucket
get_slot(T, Key) ->
H = erlang:phash(Key, T#dict.maxn),
if
H > T#dict.n -> H - T#dict.bso;
true -> H
end.
get_bucket(T, Slot) -> get_bucket_s(T#dict.segs, Slot).
on_bucket(Fun , Hashdb , Slot ) - > { NewHashDb , Result } .
on_bucket(F, T, Slot) ->
SegI = ((Slot-1) div ?seg_size) + 1,
BktI = ((Slot-1) rem ?seg_size) + 1,
Segs = T#dict.segs,
Seg = element(SegI, Segs),
B0 = element(BktI, Seg),
{T#dict{segs=setelement(SegI, Segs, setelement(BktI, Seg, B1))},Res}.
fold_dict(Fun , Acc , Dictionary ) - > Acc .
fold_dict(F, Acc, #dict{size=0}) when is_function(F, 3) ->
Acc;
fold_dict(F, Acc, D) ->
Segs = D#dict.segs,
fold_segs(F, Acc, Segs, tuple_size(Segs)).
fold_segs(F, Acc, Segs, I) when I >= 1 ->
Seg = element(I, Segs),
fold_segs(F, fold_seg(F, Acc, Seg, tuple_size(Seg)), Segs, I-1);
fold_segs(F, Acc, _, 0) when is_function(F, 3) -> Acc.
fold_seg(F, Acc, Seg, I) when I >= 1 ->
fold_seg(F, fold_bucket(F, Acc, element(I, Seg)), Seg, I-1);
fold_seg(F, Acc, _, 0) when is_function(F, 3) -> Acc.
fold_bucket(F, Acc, [?kv(Key,Val)|Bkt]) ->
fold_bucket(F, F(Key, Val, Acc), Bkt);
fold_bucket(F, Acc, []) when is_function(F, 3) -> Acc.
map_dict(F, #dict{size=0} = Dict) when is_function(F, 2) ->
Dict;
map_dict(F, D) ->
Segs0 = tuple_to_list(D#dict.segs),
Segs1 = map_seg_list(F, Segs0),
D#dict{segs=list_to_tuple(Segs1)}.
map_seg_list(F, [Seg|Segs]) ->
Bkts0 = tuple_to_list(Seg),
Bkts1 = map_bkt_list(F, Bkts0),
[list_to_tuple(Bkts1)|map_seg_list(F, Segs)];
map_seg_list(F, []) when is_function(F, 2) -> [].
map_bkt_list(F, [Bkt0|Bkts]) ->
[map_bucket(F, Bkt0)|map_bkt_list(F, Bkts)];
map_bkt_list(F, []) when is_function(F, 2) -> [].
map_bucket(F, [?kv(Key,Val)|Bkt]) ->
[?kv(Key,F(Key, Val))|map_bucket(F, Bkt)];
map_bucket(F, []) when is_function(F, 2) -> [].
filter_dict(F, #dict{size=0} = Dict) when is_function(F, 2) ->
Dict;
filter_dict(F, D) ->
Segs0 = tuple_to_list(D#dict.segs),
{Segs1,Fc} = filter_seg_list(F, Segs0, [], 0),
maybe_contract(D#dict{segs=list_to_tuple(Segs1)}, Fc).
filter_seg_list(F, [Seg|Segs], Fss, Fc0) ->
Bkts0 = tuple_to_list(Seg),
{Bkts1,Fc1} = filter_bkt_list(F, Bkts0, [], Fc0),
filter_seg_list(F, Segs, [list_to_tuple(Bkts1)|Fss], Fc1);
filter_seg_list(F, [], Fss, Fc) when is_function(F, 2) ->
{lists:reverse(Fss, []),Fc}.
filter_bkt_list(F, [Bkt0|Bkts], Fbs, Fc0) ->
{Bkt1,Fc1} = filter_bucket(F, Bkt0, [], Fc0),
filter_bkt_list(F, Bkts, [Bkt1|Fbs], Fc1);
filter_bkt_list(F, [], Fbs, Fc) when is_function(F, 2) ->
{lists:reverse(Fbs),Fc}.
filter_bucket(F, [?kv(Key,Val)=E|Bkt], Fb, Fc) ->
case F(Key, Val) of
true -> filter_bucket(F, Bkt, [E|Fb], Fc);
false -> filter_bucket(F, Bkt, Fb, Fc+1)
end;
filter_bucket(F, [], Fb, Fc) when is_function(F, 2) ->
{lists:reverse(Fb),Fc}.
get_bucket_s(Segments , Slot ) - > Bucket .
get_bucket_s(Segs, Slot) ->
SegI = ((Slot-1) div ?seg_size) + 1,
BktI = ((Slot-1) rem ?seg_size) + 1,
element(BktI, element(SegI, Segs)).
put_bucket_s(Segs, Slot, Bkt) ->
SegI = ((Slot-1) div ?seg_size) + 1,
BktI = ((Slot-1) rem ?seg_size) + 1,
Seg = setelement(BktI, element(SegI, Segs), Bkt),
setelement(SegI, Segs, Seg).
In maybe_expand ( ) , the variable Ic only takes the values 0 or 1 ,
maybe_expand(T, 0) -> maybe_expand_aux(T, 0);
maybe_expand(T, 1) -> maybe_expand_aux(T, 1).
maybe_expand_aux(T0, Ic) when T0#dict.size + Ic > T0#dict.exp_size ->
Segs0 = T#dict.segs,
Slot1 = N - T#dict.bso,
B = get_bucket_s(Segs0, Slot1),
Slot2 = N,
[B1|B2] = rehash(B, Slot1, Slot2, T#dict.maxn),
Segs1 = put_bucket_s(Segs0, Slot1, B1),
Segs2 = put_bucket_s(Segs1, Slot2, B2),
T#dict{size=T#dict.size + Ic,
n=N,
exp_size=N * ?expand_load,
con_size=N * ?contract_load,
segs=Segs2};
maybe_expand_aux(T, Ic) -> T#dict{size=T#dict.size + Ic}.
maybe_expand_segs(T) when T#dict.n =:= T#dict.maxn ->
T#dict{maxn=2 * T#dict.maxn,
bso=2 * T#dict.bso,
segs=expand_segs(T#dict.segs, T#dict.empty)};
maybe_expand_segs(T) -> T.
maybe_contract(T, Dc) when T#dict.size - Dc < T#dict.con_size,
T#dict.n > ?seg_size ->
N = T#dict.n,
Slot1 = N - T#dict.bso,
Segs0 = T#dict.segs,
B1 = get_bucket_s(Segs0, Slot1),
Slot2 = N,
B2 = get_bucket_s(Segs0, Slot2),
Segs1 = put_bucket_s(Segs0, Slot1, B1 ++ B2),
N1 = N - 1,
maybe_contract_segs(T#dict{size=T#dict.size - Dc,
n=N1,
exp_size=N1 * ?expand_load,
con_size=N1 * ?contract_load,
segs=Segs2});
maybe_contract(T, Dc) -> T#dict{size=T#dict.size - Dc}.
maybe_contract_segs(T) when T#dict.n =:= T#dict.bso ->
T#dict{maxn=T#dict.maxn div 2,
bso=T#dict.bso div 2,
segs=contract_segs(T#dict.segs)};
maybe_contract_segs(T) -> T.
rehash(Bucket , , Slot2 , MaxN ) - > [ ] .
rehash([?kv(Key,_Bag)=KeyBag|T], Slot1, Slot2, MaxN) ->
[L1|L2] = rehash(T, Slot1, Slot2, MaxN),
case erlang:phash(Key, MaxN) of
Slot1 -> [[KeyBag|L1]|L2];
Slot2 -> [L1|[KeyBag|L2]]
end;
rehash([], _Slot1, _Slot2, _MaxN) -> [[]|[]].
mk_seg(16) -> {[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]}.
expand_segs(Segs , EmptySeg ) - > NewSegs .
of segments . We special case the powers of 2 upto 32 , this should
expand_segs({B1}, Empty) ->
{B1,Empty};
expand_segs({B1,B2}, Empty) ->
{B1,B2,Empty,Empty};
expand_segs({B1,B2,B3,B4}, Empty) ->
{B1,B2,B3,B4,Empty,Empty,Empty,Empty};
expand_segs({B1,B2,B3,B4,B5,B6,B7,B8}, Empty) ->
{B1,B2,B3,B4,B5,B6,B7,B8,
Empty,Empty,Empty,Empty,Empty,Empty,Empty,Empty};
expand_segs({B1,B2,B3,B4,B5,B6,B7,B8,B9,B10,B11,B12,B13,B14,B15,B16}, Empty) ->
{B1,B2,B3,B4,B5,B6,B7,B8,B9,B10,B11,B12,B13,B14,B15,B16,
Empty,Empty,Empty,Empty,Empty,Empty,Empty,Empty,
Empty,Empty,Empty,Empty,Empty,Empty,Empty,Empty};
expand_segs(Segs, Empty) ->
list_to_tuple(tuple_to_list(Segs)
++ lists:duplicate(tuple_size(Segs), Empty)).
contract_segs({B1,_}) ->
{B1};
contract_segs({B1,B2,_,_}) ->
{B1,B2};
contract_segs({B1,B2,B3,B4,_,_,_,_}) ->
{B1,B2,B3,B4};
contract_segs({B1,B2,B3,B4,B5,B6,B7,B8,_,_,_,_,_,_,_,_}) ->
{B1,B2,B3,B4,B5,B6,B7,B8};
contract_segs({B1,B2,B3,B4,B5,B6,B7,B8,B9,B10,B11,B12,B13,B14,B15,B16,
_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_}) ->
{B1,B2,B3,B4,B5,B6,B7,B8,B9,B10,B11,B12,B13,B14,B15,B16};
contract_segs(Segs) ->
Ss = tuple_size(Segs) div 2,
list_to_tuple(lists:sublist(tuple_to_list(Segs), 1, Ss)).
|
b48c0f7870a926e017b91c287e084b01beb68fc31deea97f66df5c48c4540d6b | lehins/Color | HSI.hs | # LANGUAGE DataKinds #
{-# LANGUAGE DeriveTraversable #-}
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE PatternSynonyms #
# LANGUAGE PolyKinds #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
# LANGUAGE ViewPatterns #
-- |
Module : Graphics . Color . Space . RGB.Alternative . HSI
Copyright : ( c ) 2019 - 2020
-- License : BSD3
Maintainer : < >
-- Stability : experimental
-- Portability : non-portable
--
module Graphics.Color.Space.RGB.Alternative.HSI
( pattern ColorHSI
, pattern ColorHSIA
, pattern ColorH360SI
, HSI
, Color(HSI)
) where
import Data.Coerce
import Data.Proxy
import Foreign.Storable
import qualified Graphics.Color.Model.HSI as CM
import Graphics.Color.Model.Internal
import Graphics.Color.Space.Internal
import Graphics.Color.Space.RGB.Internal
| ` HSI ` representation for some ( @`RedGreenBlue ` cs i@ ) color space
data HSI cs
| ` HSI ` representation for some ( @`RedGreenBlue ` cs i@ ) color space
newtype instance Color (HSI cs) e = HSI (Color CM.HSI e)
| ` HSI ` representation for some ( @`RedGreenBlue ` cs i@ ) color space
deriving instance Eq e => Eq (Color (HSI cs) e)
| ` HSI ` representation for some ( @`RedGreenBlue ` cs i@ ) color space
deriving instance Ord e => Ord (Color (HSI cs) e)
| ` HSI ` representation for some ( @`RedGreenBlue ` cs i@ ) color space
deriving instance Functor (Color (HSI cs))
| ` HSI ` representation for some ( @`RedGreenBlue ` cs i@ ) color space
deriving instance Applicative (Color (HSI cs))
| ` HSI ` representation for some ( @`RedGreenBlue ` cs i@ ) color space
deriving instance Foldable (Color (HSI cs))
| ` HSI ` representation for some ( @`RedGreenBlue ` cs i@ ) color space
deriving instance Traversable (Color (HSI cs))
| ` HSI ` representation for some ( @`RedGreenBlue ` cs i@ ) color space
deriving instance Storable e => Storable (Color (HSI cs) e)
| ` HSI ` representation for some ( @`RedGreenBlue ` cs i@ ) color space
instance ColorModel cs e => Show (Color (HSI cs) e) where
showsPrec _ = showsColorModel
| Constructor for an RGB color space in an alternative HSI color model
pattern ColorHSI :: e -> e -> e -> Color (HSI cs) e
pattern ColorHSI h s i = HSI (CM.ColorHSI h s i)
{-# COMPLETE ColorHSI #-}
-- | Constructor for @HSI@ with alpha channel.
pattern ColorHSIA :: e -> e -> e -> e -> Color (Alpha (HSI cs)) e
pattern ColorHSIA h s i a = Alpha (HSI (CM.ColorHSI h s i)) a
# COMPLETE ColorHSIA #
| Constructor for an RGB color space in an alternative HSI color model . Difference from
` ColorHSI ` is that the hue is specified in 0 to 360 degree range , rather than 0 to
1 . Note , that this is not checked .
pattern ColorH360SI :: Fractional e => e -> e -> e -> Color (HSI cs) e
pattern ColorH360SI h s i <- ColorHSI ((* 360) -> h) s i where
ColorH360SI h s i = ColorHSI (h / 360) s i
{-# COMPLETE ColorH360SI #-}
| ` HSI ` representation for some ( @`RedGreenBlue ` cs i@ ) color space
instance ColorModel cs e => ColorModel (HSI cs) e where
type Components (HSI cs) e = (e, e, e)
toComponents = toComponents . coerce
# INLINE toComponents #
fromComponents = coerce . fromComponents
# INLINE fromComponents #
showsColorModelName _ = ("HSI-" ++) . showsColorModelName (Proxy :: Proxy (Color cs e))
| ` HSI ` representation for some ( @`RedGreenBlue ` cs i@ ) color space
instance (ColorSpace (cs l) i e, RedGreenBlue cs i) => ColorSpace (HSI (cs l)) i e where
type BaseModel (HSI (cs l)) = CM.HSI
type BaseSpace (HSI (cs l)) = cs l
toBaseSpace = mkColorRGB . fmap fromDouble . CM.hsi2rgb . fmap toDouble . coerce
# INLINE toBaseSpace #
fromBaseSpace = coerce . fmap fromDouble . CM.rgb2hsi . fmap toDouble . unColorRGB
# INLINE fromBaseSpace #
luminance = luminance . toBaseSpace
# INLINE luminance #
| null | https://raw.githubusercontent.com/lehins/Color/8f17d4d17dc9b899af702f54b69d49f3a5752e7b/Color/src/Graphics/Color/Space/RGB/Alternative/HSI.hs | haskell | # LANGUAGE DeriveTraversable #
|
License : BSD3
Stability : experimental
Portability : non-portable
# COMPLETE ColorHSI #
| Constructor for @HSI@ with alpha channel.
# COMPLETE ColorH360SI # | # LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE PatternSynonyms #
# LANGUAGE PolyKinds #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
# LANGUAGE ViewPatterns #
Module : Graphics . Color . Space . RGB.Alternative . HSI
Copyright : ( c ) 2019 - 2020
Maintainer : < >
module Graphics.Color.Space.RGB.Alternative.HSI
( pattern ColorHSI
, pattern ColorHSIA
, pattern ColorH360SI
, HSI
, Color(HSI)
) where
import Data.Coerce
import Data.Proxy
import Foreign.Storable
import qualified Graphics.Color.Model.HSI as CM
import Graphics.Color.Model.Internal
import Graphics.Color.Space.Internal
import Graphics.Color.Space.RGB.Internal
| ` HSI ` representation for some ( @`RedGreenBlue ` cs i@ ) color space
data HSI cs
| ` HSI ` representation for some ( @`RedGreenBlue ` cs i@ ) color space
newtype instance Color (HSI cs) e = HSI (Color CM.HSI e)
| ` HSI ` representation for some ( @`RedGreenBlue ` cs i@ ) color space
deriving instance Eq e => Eq (Color (HSI cs) e)
| ` HSI ` representation for some ( @`RedGreenBlue ` cs i@ ) color space
deriving instance Ord e => Ord (Color (HSI cs) e)
| ` HSI ` representation for some ( @`RedGreenBlue ` cs i@ ) color space
deriving instance Functor (Color (HSI cs))
| ` HSI ` representation for some ( @`RedGreenBlue ` cs i@ ) color space
deriving instance Applicative (Color (HSI cs))
| ` HSI ` representation for some ( @`RedGreenBlue ` cs i@ ) color space
deriving instance Foldable (Color (HSI cs))
| ` HSI ` representation for some ( @`RedGreenBlue ` cs i@ ) color space
deriving instance Traversable (Color (HSI cs))
| ` HSI ` representation for some ( @`RedGreenBlue ` cs i@ ) color space
deriving instance Storable e => Storable (Color (HSI cs) e)
| ` HSI ` representation for some ( @`RedGreenBlue ` cs i@ ) color space
instance ColorModel cs e => Show (Color (HSI cs) e) where
showsPrec _ = showsColorModel
| Constructor for an RGB color space in an alternative HSI color model
pattern ColorHSI :: e -> e -> e -> Color (HSI cs) e
pattern ColorHSI h s i = HSI (CM.ColorHSI h s i)
pattern ColorHSIA :: e -> e -> e -> e -> Color (Alpha (HSI cs)) e
pattern ColorHSIA h s i a = Alpha (HSI (CM.ColorHSI h s i)) a
# COMPLETE ColorHSIA #
| Constructor for an RGB color space in an alternative HSI color model . Difference from
` ColorHSI ` is that the hue is specified in 0 to 360 degree range , rather than 0 to
1 . Note , that this is not checked .
pattern ColorH360SI :: Fractional e => e -> e -> e -> Color (HSI cs) e
pattern ColorH360SI h s i <- ColorHSI ((* 360) -> h) s i where
ColorH360SI h s i = ColorHSI (h / 360) s i
| ` HSI ` representation for some ( @`RedGreenBlue ` cs i@ ) color space
instance ColorModel cs e => ColorModel (HSI cs) e where
type Components (HSI cs) e = (e, e, e)
toComponents = toComponents . coerce
# INLINE toComponents #
fromComponents = coerce . fromComponents
# INLINE fromComponents #
showsColorModelName _ = ("HSI-" ++) . showsColorModelName (Proxy :: Proxy (Color cs e))
| ` HSI ` representation for some ( @`RedGreenBlue ` cs i@ ) color space
instance (ColorSpace (cs l) i e, RedGreenBlue cs i) => ColorSpace (HSI (cs l)) i e where
type BaseModel (HSI (cs l)) = CM.HSI
type BaseSpace (HSI (cs l)) = cs l
toBaseSpace = mkColorRGB . fmap fromDouble . CM.hsi2rgb . fmap toDouble . coerce
# INLINE toBaseSpace #
fromBaseSpace = coerce . fmap fromDouble . CM.rgb2hsi . fmap toDouble . unColorRGB
# INLINE fromBaseSpace #
luminance = luminance . toBaseSpace
# INLINE luminance #
|
7356ddaccc7348eb33e58642c8f5918cc4f39b3aa798c4c01495bfa9af3f1ba0 | guildhall/guile-haunt | utils.scm | Haunt --- Static site generator for GNU
Copyright © 2015 < >
Copyright © 2012 , 2013 , 2014 < >
;;;
This file is part of Haunt .
;;;
Haunt 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.
;;;
Haunt 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 Haunt . If not , see < / > .
;;; Commentary:
;;
;; Miscellaneous utility procedures.
;;
;;; Code:
(define-module (haunt utils)
#:use-module (ice-9 ftw)
#:use-module (ice-9 match)
#:use-module (srfi srfi-1)
#:use-module (srfi srfi-19)
#:use-module (srfi srfi-26)
#:export (flatten
flat-map
string-split-at
file-name-components
join-file-name-components
absolute-file-name
delete-file-recursively
mkdir-p
string->date*
take-up-to))
(define* (flatten lst #:optional depth)
"Return a list that recursively concatenates the sub-lists of LST,
up to DEPTH levels deep. When DEPTH is #f, the entire tree is
flattened."
(if (and (number? depth) (zero? depth))
lst
(fold-right (match-lambda*
(((sub-list ...) memo)
(append (flatten sub-list (and depth (1- depth)))
memo))
((elem memo)
(cons elem memo)))
'()
lst)))
(define (flat-map proc . lsts)
(flatten (apply map proc lsts) 1))
(define (string-split-at str char-pred)
(let ((i (string-index str char-pred)))
(if i
(list (string-take str i)
(string-drop str (1+ i)))
(list str))))
(define (file-name-components file-name)
"Split FILE-NAME into the components delimited by '/'."
(if (string-null? file-name)
'()
(string-split file-name #\/)))
(define (join-file-name-components components)
"Join COMPONENTS into a file name string."
(string-join components "/"))
(define (absolute-file-name file-name)
(if (absolute-file-name? file-name)
file-name
(string-append (getcwd) "/" file-name)))
Written by for GNU Guix .
(define* (delete-file-recursively dir
#:key follow-mounts?)
"Delete DIR recursively, like `rm -rf', without following symlinks. Don't
follow mount points either, unless FOLLOW-MOUNTS? is true. Report but ignore
errors."
(let ((dev (stat:dev (lstat dir))))
(file-system-fold (lambda (dir stat result) ; enter?
(or follow-mounts?
(= dev (stat:dev stat))))
(lambda (file stat result) ; leaf
(delete-file file))
(const #t) ; down
(lambda (dir stat result) ; up
(rmdir dir))
(const #t) ; skip
(lambda (file stat errno result)
(format (current-error-port)
"warning: failed to delete ~a: ~a~%"
file (strerror errno)))
#t
dir
;; Don't follow symlinks.
lstat)))
Written by for GNU Guix .
(define (mkdir-p dir)
"Create directory DIR and all its ancestors."
(define absolute?
(string-prefix? "/" dir))
(define not-slash
(char-set-complement (char-set #\/)))
(let loop ((components (string-tokenize dir not-slash))
(root (if absolute?
""
".")))
(match components
((head tail ...)
(let ((path (string-append root "/" head)))
(catch 'system-error
(lambda ()
(mkdir path)
(loop tail path))
(lambda args
(if (= EEXIST (system-error-errno args))
(loop tail path)
(apply throw args))))))
(() #t))))
(define (string->date* str)
"Convert STR, a string in '~Y~m~d ~H:~M' format, into a SRFI-19 date
object."
(string->date str "~Y~m~d ~H:~M"))
(define (take-up-to n lst)
"Return the first N elements of LST or an equivalent list if there
are fewer than N elements."
(if (zero? n)
'()
(match lst
(() '())
((head . tail)
(cons head (take-up-to (1- n) tail))))))
| null | https://raw.githubusercontent.com/guildhall/guile-haunt/c67e8e924c664ae4035862cc7b439cd7ec4bcef6/haunt/utils.scm | scheme |
you can redistribute it and/or modify it
either version 3 of the License , or
(at your option) any later version.
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.
Commentary:
Miscellaneous utility procedures.
Code:
enter?
leaf
down
up
skip
Don't follow symlinks. | Haunt --- Static site generator for GNU
Copyright © 2015 < >
Copyright © 2012 , 2013 , 2014 < >
This file is part of Haunt .
under the terms of the GNU General Public License as published by
Haunt is distributed in the hope that it will be useful , but
You should have received a copy of the GNU General Public License
along with Haunt . If not , see < / > .
(define-module (haunt utils)
#:use-module (ice-9 ftw)
#:use-module (ice-9 match)
#:use-module (srfi srfi-1)
#:use-module (srfi srfi-19)
#:use-module (srfi srfi-26)
#:export (flatten
flat-map
string-split-at
file-name-components
join-file-name-components
absolute-file-name
delete-file-recursively
mkdir-p
string->date*
take-up-to))
(define* (flatten lst #:optional depth)
"Return a list that recursively concatenates the sub-lists of LST,
up to DEPTH levels deep. When DEPTH is #f, the entire tree is
flattened."
(if (and (number? depth) (zero? depth))
lst
(fold-right (match-lambda*
(((sub-list ...) memo)
(append (flatten sub-list (and depth (1- depth)))
memo))
((elem memo)
(cons elem memo)))
'()
lst)))
(define (flat-map proc . lsts)
(flatten (apply map proc lsts) 1))
(define (string-split-at str char-pred)
(let ((i (string-index str char-pred)))
(if i
(list (string-take str i)
(string-drop str (1+ i)))
(list str))))
(define (file-name-components file-name)
"Split FILE-NAME into the components delimited by '/'."
(if (string-null? file-name)
'()
(string-split file-name #\/)))
(define (join-file-name-components components)
"Join COMPONENTS into a file name string."
(string-join components "/"))
(define (absolute-file-name file-name)
(if (absolute-file-name? file-name)
file-name
(string-append (getcwd) "/" file-name)))
Written by for GNU Guix .
(define* (delete-file-recursively dir
#:key follow-mounts?)
"Delete DIR recursively, like `rm -rf', without following symlinks. Don't
follow mount points either, unless FOLLOW-MOUNTS? is true. Report but ignore
errors."
(let ((dev (stat:dev (lstat dir))))
(or follow-mounts?
(= dev (stat:dev stat))))
(delete-file file))
(rmdir dir))
(lambda (file stat errno result)
(format (current-error-port)
"warning: failed to delete ~a: ~a~%"
file (strerror errno)))
#t
dir
lstat)))
Written by for GNU Guix .
(define (mkdir-p dir)
"Create directory DIR and all its ancestors."
(define absolute?
(string-prefix? "/" dir))
(define not-slash
(char-set-complement (char-set #\/)))
(let loop ((components (string-tokenize dir not-slash))
(root (if absolute?
""
".")))
(match components
((head tail ...)
(let ((path (string-append root "/" head)))
(catch 'system-error
(lambda ()
(mkdir path)
(loop tail path))
(lambda args
(if (= EEXIST (system-error-errno args))
(loop tail path)
(apply throw args))))))
(() #t))))
(define (string->date* str)
"Convert STR, a string in '~Y~m~d ~H:~M' format, into a SRFI-19 date
object."
(string->date str "~Y~m~d ~H:~M"))
(define (take-up-to n lst)
"Return the first N elements of LST or an equivalent list if there
are fewer than N elements."
(if (zero? n)
'()
(match lst
(() '())
((head . tail)
(cons head (take-up-to (1- n) tail))))))
|
5b4b59021af07b2efe8215bd334be96d63b3a68d51f5297dee1f0203feb16ab9 | nikomatsakis/a-mir-formality | borrow-check.rkt | #lang racket
(require redex/reduction-semantics
"grammar.rkt"
"../check/prove-goal.rkt"
"borrow-check/initialization-check.rkt"
"borrow-check/initialization-infer.rkt"
"borrow-check/loan-check.rkt"
)
(provide borrow-check
)
(define-judgment-form
formality-body
#:mode (borrow-check I I I)
#:contract (borrow-check Γ Env GoalAtLocations)
[(initialization-check Γ (infer-initialization Γ))
(loan-check Γ Env GoalAtLocations)
----------------------------------------
(borrow-check Γ Env GoalAtLocations)
]
)
| null | https://raw.githubusercontent.com/nikomatsakis/a-mir-formality/bc951e21bff2bae1ccab8cc05b2b39cfb6365bfd/racket-src/body/borrow-check.rkt | racket | #lang racket
(require redex/reduction-semantics
"grammar.rkt"
"../check/prove-goal.rkt"
"borrow-check/initialization-check.rkt"
"borrow-check/initialization-infer.rkt"
"borrow-check/loan-check.rkt"
)
(provide borrow-check
)
(define-judgment-form
formality-body
#:mode (borrow-check I I I)
#:contract (borrow-check Γ Env GoalAtLocations)
[(initialization-check Γ (infer-initialization Γ))
(loan-check Γ Env GoalAtLocations)
----------------------------------------
(borrow-check Γ Env GoalAtLocations)
]
)
| |
dc7d0af24b920997352fc09e2e32e7168dccab154659418167cdd2d5654a7dce | takikawa/racket-ppa | racket-tests.rkt | ; Surface syntax for check-expect & friends in Racket-like languages.
#lang racket/base
(provide check-expect ;; syntax : (check-expect <expression> <expression>)
check-random ;; syntax : (check-random <expression> <expression>)
check-within ;; syntax : (check-within <expression> <expression> <expression>)
check-member-of ;; syntax : (check-member-of <expression> <expression>)
check-range ;; syntax : (check-range <expression> <expression> <expression>)
check-error ;; syntax : (check-error <expression> [<expression>])
check-satisfied ;; syntax : (check-satisfied <expression> <expression>)
;; re-exports from test-engine/syntax
test-execute test-silence
test
test-engine-is-using-error-display-handler?)
(require lang/private/teachprims
racket/match
; racket/function
htdp/error
(for-syntax racket/base
#;"requiring from" lang/private/firstorder #;"avoids load cycle")
test-engine/test-engine
(only-in test-engine/test-markup get-rewritten-error-message)
test-engine/syntax
racket/class
simple-tree-text-markup/construct
simple-tree-text-markup/port)
(define INEXACT-NUMBERS-FMT
"check-expect cannot compare inexact numbers. Try (check-within test ~a range).")
(define FUNCTION-FMT
"check-expect cannot compare functions.")
(define SATISFIED-FMT
"check-satisfied: expects function of one argument in second position. Given ~a")
(define CHECK-ERROR-STR-FMT
"check-error: expects a string (the expected error message) for the second argument. Given ~s")
(define CHECK-WITHIN-INEXACT-FMT
"check-within: expects an inexact number for the range. ~a is not inexact.")
(define CHECK-WITHIN-FUNCTION-FMT
"check-within cannot compare functions.")
(define LIST-FMT
"check-member-of: expects a list for the second argument (the possible outcomes). Given ~s")
(define CHECK-MEMBER-OF-FUNCTION-FMT
"check-member-of: cannot compare functions.")
(define RANGE-MIN-FMT
"check-range: expects a number for the minimum value. Given ~a")
(define RANGE-MAX-FMT
"check-range: expects a number for the maximum value. Given ~a")
(define CHECK-RANGE-FUNCTION-FMT
"check-range: cannot compare functions.")
(define-for-syntax CHECK-EXPECT-DEFN-STR
"found a test that is not at the top level")
(define-for-syntax CHECK-WITHIN-DEFN-STR
CHECK-EXPECT-DEFN-STR)
(define-for-syntax CHECK-ERROR-DEFN-STR
CHECK-EXPECT-DEFN-STR)
(define-for-syntax (check-context! kind message stx)
(let ([c (syntax-local-context)])
(unless (memq c '(module top-level module-begin))
(raise-syntax-error kind message stx))))
; note that rewrite-error-message might be sensitive to the exact format here
(define-for-syntax (argcount-error-message/stx arity stx [at-least #f])
(let* ((ls (syntax->list stx))
(found (if ls (sub1 (length ls)) 0))
(fn-is-large (> arity found)))
(format "expects ~a~a~a argument~a, but found ~a~a"
(if at-least "at least " "")
(if (or (= arity 0) fn-is-large) "" "only ")
(if (= arity 0) "no" arity) (if (> arity 1) "s" "")
(if (and (not (= found 0)) fn-is-large) "only " "")
(if (= found 0) "none" found))))
; The stepper needs this: it binds error-display-handler to get notified of an error.
; However, we call (error-display-handler) just to generate markup, and the stepper
; needs to ignore that.
(define test-engine-is-using-error-display-handler? (make-parameter #f))
(define (exn->markup exn)
(let-values (([port get-markup] (make-markup-output-port/unsafe (lambda (special)
(cond
[(and (object? special)
(is-a? special srclocs-special<%>)
(send special get-srclocs))
=> (lambda (srclocs)
(if (and (pair? srclocs)
(srcloc? (car srclocs)))
(srcloc-markup (car srclocs) (srcloc->string (car srclocs)))
empty-markup))]
[else empty-markup])))))
(parameterize ([current-error-port port]
[test-engine-is-using-error-display-handler? #t])
((error-display-handler) (exn-message exn) exn)
(get-markup))))
(define (make-exn->unexpected-error src expected)
(lambda (exn)
(unexpected-error/markup src expected exn (exn->markup exn))))
(define-syntax (check-expect stx)
(check-context! 'check-expect CHECK-EXPECT-DEFN-STR stx)
(syntax-case stx ()
[(_ test expected)
(check-expect-maker stx #'do-check-expect #`test (list #`expected) 'comes-from-check-expect)]
[_ (raise-syntax-error 'check-expect (argcount-error-message/stx 2 stx) stx)]))
(define (do-check-expect test expected src)
(error-check (lambda (v) (if (number? v) (exact? v) #t))
expected INEXACT-NUMBERS-FMT #t)
(error-check (lambda (v) (not (procedure? v)))
expected FUNCTION-FMT #f)
(execute-test
src
(lambda ()
(let ((actual (test)))
(if (teach-equal? actual expected)
#t
(unequal src actual expected))))
(make-exn->unexpected-error src expected)))
(define-syntax (check-random stx)
(syntax-case stx ()
[(check-random e1 e2)
(let ([test #`(lambda () e1)]
[expected (list #`(lambda () e2))])
(check-expect-maker stx #'do-check-random test expected 'comes-from-check-random))]
[_ (raise-syntax-error 'check-random (argcount-error-message/stx 2 stx) stx)]))
(define (do-check-random test expected-thunk src)
(let ((rng (make-pseudo-random-generator))
(k (modulo (current-milliseconds) (sub1 (expt 2 31)))))
(let ((expected (parameterize ([current-pseudo-random-generator rng])
(random-seed k)
(expected-thunk))))
(error-check (lambda (v) (if (number? v) (exact? v) #t))
expected INEXACT-NUMBERS-FMT #t)
(execute-test
src
(lambda ()
(let ((actual (parameterize ([current-pseudo-random-generator rng])
(random-seed k)
((test)))))
(if (teach-equal? actual expected)
#t
(unequal src actual expected))))
(make-exn->unexpected-error src expected)))))
(define-syntax (check-satisfied stx)
(syntax-case stx ()
[(_ actual:exp expected-predicate:id)
(identifier? #'expected-predicate:id)
(let* ([prop1 (first-order->higher-order #'expected-predicate:id)]
[name (symbol->string (syntax-e #'expected-predicate:id))]
[code #`(lambda (x)
(with-handlers ([exn:fail:contract:arity?
(lambda (exn)
(let* ((msg (exn-message exn))
(msg1 (regexp-match #px"(.*): arity mismatch" msg)))
(cond
[msg1
(let ((raised-name (cadr msg1)))
(if (equal? #,name raised-name)
(error-check (lambda (v) #f) #,name SATISFIED-FMT #t)
(raise exn)))]
[else (raise exn)])))])
(#,prop1 x)))])
(check-expect-maker stx
#'do-check-satisfied
#'actual:exp
(list code name)
'comes-from-check-satisfied))]
[(_ actual:exp expected-predicate:exp)
(let ([pred #`(let ([p? expected-predicate:exp])
(let ((name (object-name p?)))
(unless (and (procedure? p?) (procedure-arity-includes? p? 1))
this produces the BSL / ISL name
(error-check (lambda (v) #f) name SATISFIED-FMT #t)
(error-check (lambda (v) #f) p? SATISFIED-FMT #t))))
p?)])
(check-expect-maker stx
#'do-check-satisfied
#'actual:exp
(list pred "unknown name")
'comes-from-check-satisfied))]
[(_ actual:exp expected-predicate:exp)
(raise-syntax-error 'check-satisfied "expects named function in second position." stx)]
[_ (raise-syntax-error 'check-satisfied (argcount-error-message/stx 2 stx) stx)]))
(define (do-check-satisfied test p? name src)
(execute-test
src
(lambda ()
(unless (and (procedure? p?) (procedure-arity-includes? p? 1))
(error-check (lambda (v) #f) name SATISFIED-FMT #t))
(let* ((actual (test))
(ok? (p? actual)))
(cond
[(not (boolean? ok?))
;; (error-check (lambda (v) #f) name "expected a boolean" #t)
(check-result (format "~a [as predicate in check-satisfied]" name) boolean? "boolean" ok?)]
[(not ok?)
(satisfied-failed src actual name)]
[else #t])))
(lambda (exn)
(unsatisfied-error/markup src name exn (exn->markup exn)))))
(define-syntax (check-within stx)
(check-context! 'check-within CHECK-WITHIN-DEFN-STR stx)
(syntax-case stx ()
[(_ test expected within)
(check-expect-maker stx #'do-check-within #`test (list #`expected #`within)
'comes-from-check-within)]
[_ (raise-syntax-error 'check-within (argcount-error-message/stx 3 stx) stx)]))
(define (do-check-within test expected within src)
(error-check number? within CHECK-WITHIN-INEXACT-FMT #t)
(error-check (lambda (v) (not (procedure? v))) expected CHECK-WITHIN-FUNCTION-FMT #f)
(execute-test
src
(lambda ()
(let ((actual (test)))
(if (beginner-equal~? actual expected within)
#t
(not-within src actual expected within))))
(make-exn->unexpected-error src expected)))
(define-syntax (check-error stx)
(check-context! 'check-error CHECK-ERROR-DEFN-STR stx)
(syntax-case stx ()
[(_ test error)
(check-expect-maker stx #'do-check-error #`test (list #`error)
'comes-from-check-error)]
[(_ test)
(check-expect-maker stx #'do-check-error/no-message #`test '()
'comes-from-check-error)]
[(_) (raise-syntax-error 'check-error (argcount-error-message/stx 1 stx #t) stx)]
[_ (raise-syntax-error 'check-error (argcount-error-message/stx 2 stx) stx)]))
(define (do-check-error test error src)
(error-check string? error CHECK-ERROR-STR-FMT #t)
(execute-test
src
(lambda ()
(with-handlers ([exn:fail?
(lambda (exn)
(let ((msg (get-rewritten-error-message exn)))
(if (equal? msg error)
#t
(incorrect-error/markup src error exn (exn->markup exn)))))])
(let ([actual (test)])
(expected-error src error actual))))
(make-exn->unexpected-error src error))) ; probably can't happen
(define (do-check-error/no-message test src)
(execute-test
src
(lambda ()
(with-handlers ([exn:fail?
(lambda (exn) #t)])
(let ([actual (test)])
(expected-error src #f actual))))
(make-exn->unexpected-error src "any error"))) ; probably can't happen
(define-syntax (check-member-of stx)
(check-context! 'check-member-of CHECK-EXPECT-DEFN-STR stx)
(syntax-case stx ()
[(_ test expected expecteds ...)
(check-expect-maker stx
#'do-check-member-of
#`test
(list #`(list expected expecteds ...))
'comes-from-check-member-of)]
[_ (raise-syntax-error 'check-member-of (argcount-error-message/stx 2 stx #t) stx)]))
(define (do-check-member-of test expecteds src)
(for-each
(lambda (expected)
(error-check (lambda (v) (not (procedure? v))) expected CHECK-MEMBER-OF-FUNCTION-FMT #f))
expecteds)
(execute-test
src
(lambda ()
(let ((actual (test)))
(if (memf (lambda (expected) (teach-equal? actual expected)) expecteds)
#t
(not-mem src actual expecteds))))
(make-exn->unexpected-error src expecteds)))
(define-syntax (check-range stx)
(check-context! 'check-member-of CHECK-EXPECT-DEFN-STR stx)
(syntax-case stx ()
[(_ test min max)
(check-expect-maker stx #'do-check-range #`test (list #`min #`max)
'comes-from-check-range)]
[_ (raise-syntax-error 'check-range (argcount-error-message/stx 3 stx) stx)]))
(define (do-check-range test min max src)
(error-check number? min RANGE-MIN-FMT #t)
(error-check number? max RANGE-MAX-FMT #t)
(error-check (lambda (v) (not (procedure? v))) min CHECK-RANGE-FUNCTION-FMT #f)
(error-check (lambda (v) (not (procedure? v))) max CHECK-RANGE-FUNCTION-FMT #f)
(execute-test
src
(lambda ()
(let ((val (test)))
(if (and (number? val)
(<= min val max))
#t
(not-range src val min max))))
(make-exn->unexpected-error src (format "[~a, ~a]" min max))))
(define (error-check pred? actual fmt fmt-act?)
(unless (pred? actual)
(raise
(make-exn:fail:contract (if fmt-act? (format fmt actual) fmt)
(current-continuation-marks)))))
| null | https://raw.githubusercontent.com/takikawa/racket-ppa/26d6ae74a1b19258c9789b7c14c074d867a4b56b/share/pkgs/htdp-lib/test-engine/racket-tests.rkt | racket | Surface syntax for check-expect & friends in Racket-like languages.
syntax : (check-expect <expression> <expression>)
syntax : (check-random <expression> <expression>)
syntax : (check-within <expression> <expression> <expression>)
syntax : (check-member-of <expression> <expression>)
syntax : (check-range <expression> <expression> <expression>)
syntax : (check-error <expression> [<expression>])
syntax : (check-satisfied <expression> <expression>)
re-exports from test-engine/syntax
racket/function
"requiring from" lang/private/firstorder #;"avoids load cycle")
note that rewrite-error-message might be sensitive to the exact format here
The stepper needs this: it binds error-display-handler to get notified of an error.
However, we call (error-display-handler) just to generate markup, and the stepper
needs to ignore that.
(error-check (lambda (v) #f) name "expected a boolean" #t)
probably can't happen
probably can't happen | #lang racket/base
test-execute test-silence
test
test-engine-is-using-error-display-handler?)
(require lang/private/teachprims
racket/match
htdp/error
(for-syntax racket/base
test-engine/test-engine
(only-in test-engine/test-markup get-rewritten-error-message)
test-engine/syntax
racket/class
simple-tree-text-markup/construct
simple-tree-text-markup/port)
(define INEXACT-NUMBERS-FMT
"check-expect cannot compare inexact numbers. Try (check-within test ~a range).")
(define FUNCTION-FMT
"check-expect cannot compare functions.")
(define SATISFIED-FMT
"check-satisfied: expects function of one argument in second position. Given ~a")
(define CHECK-ERROR-STR-FMT
"check-error: expects a string (the expected error message) for the second argument. Given ~s")
(define CHECK-WITHIN-INEXACT-FMT
"check-within: expects an inexact number for the range. ~a is not inexact.")
(define CHECK-WITHIN-FUNCTION-FMT
"check-within cannot compare functions.")
(define LIST-FMT
"check-member-of: expects a list for the second argument (the possible outcomes). Given ~s")
(define CHECK-MEMBER-OF-FUNCTION-FMT
"check-member-of: cannot compare functions.")
(define RANGE-MIN-FMT
"check-range: expects a number for the minimum value. Given ~a")
(define RANGE-MAX-FMT
"check-range: expects a number for the maximum value. Given ~a")
(define CHECK-RANGE-FUNCTION-FMT
"check-range: cannot compare functions.")
(define-for-syntax CHECK-EXPECT-DEFN-STR
"found a test that is not at the top level")
(define-for-syntax CHECK-WITHIN-DEFN-STR
CHECK-EXPECT-DEFN-STR)
(define-for-syntax CHECK-ERROR-DEFN-STR
CHECK-EXPECT-DEFN-STR)
(define-for-syntax (check-context! kind message stx)
(let ([c (syntax-local-context)])
(unless (memq c '(module top-level module-begin))
(raise-syntax-error kind message stx))))
(define-for-syntax (argcount-error-message/stx arity stx [at-least #f])
(let* ((ls (syntax->list stx))
(found (if ls (sub1 (length ls)) 0))
(fn-is-large (> arity found)))
(format "expects ~a~a~a argument~a, but found ~a~a"
(if at-least "at least " "")
(if (or (= arity 0) fn-is-large) "" "only ")
(if (= arity 0) "no" arity) (if (> arity 1) "s" "")
(if (and (not (= found 0)) fn-is-large) "only " "")
(if (= found 0) "none" found))))
(define test-engine-is-using-error-display-handler? (make-parameter #f))
(define (exn->markup exn)
(let-values (([port get-markup] (make-markup-output-port/unsafe (lambda (special)
(cond
[(and (object? special)
(is-a? special srclocs-special<%>)
(send special get-srclocs))
=> (lambda (srclocs)
(if (and (pair? srclocs)
(srcloc? (car srclocs)))
(srcloc-markup (car srclocs) (srcloc->string (car srclocs)))
empty-markup))]
[else empty-markup])))))
(parameterize ([current-error-port port]
[test-engine-is-using-error-display-handler? #t])
((error-display-handler) (exn-message exn) exn)
(get-markup))))
(define (make-exn->unexpected-error src expected)
(lambda (exn)
(unexpected-error/markup src expected exn (exn->markup exn))))
(define-syntax (check-expect stx)
(check-context! 'check-expect CHECK-EXPECT-DEFN-STR stx)
(syntax-case stx ()
[(_ test expected)
(check-expect-maker stx #'do-check-expect #`test (list #`expected) 'comes-from-check-expect)]
[_ (raise-syntax-error 'check-expect (argcount-error-message/stx 2 stx) stx)]))
(define (do-check-expect test expected src)
(error-check (lambda (v) (if (number? v) (exact? v) #t))
expected INEXACT-NUMBERS-FMT #t)
(error-check (lambda (v) (not (procedure? v)))
expected FUNCTION-FMT #f)
(execute-test
src
(lambda ()
(let ((actual (test)))
(if (teach-equal? actual expected)
#t
(unequal src actual expected))))
(make-exn->unexpected-error src expected)))
(define-syntax (check-random stx)
(syntax-case stx ()
[(check-random e1 e2)
(let ([test #`(lambda () e1)]
[expected (list #`(lambda () e2))])
(check-expect-maker stx #'do-check-random test expected 'comes-from-check-random))]
[_ (raise-syntax-error 'check-random (argcount-error-message/stx 2 stx) stx)]))
(define (do-check-random test expected-thunk src)
(let ((rng (make-pseudo-random-generator))
(k (modulo (current-milliseconds) (sub1 (expt 2 31)))))
(let ((expected (parameterize ([current-pseudo-random-generator rng])
(random-seed k)
(expected-thunk))))
(error-check (lambda (v) (if (number? v) (exact? v) #t))
expected INEXACT-NUMBERS-FMT #t)
(execute-test
src
(lambda ()
(let ((actual (parameterize ([current-pseudo-random-generator rng])
(random-seed k)
((test)))))
(if (teach-equal? actual expected)
#t
(unequal src actual expected))))
(make-exn->unexpected-error src expected)))))
(define-syntax (check-satisfied stx)
(syntax-case stx ()
[(_ actual:exp expected-predicate:id)
(identifier? #'expected-predicate:id)
(let* ([prop1 (first-order->higher-order #'expected-predicate:id)]
[name (symbol->string (syntax-e #'expected-predicate:id))]
[code #`(lambda (x)
(with-handlers ([exn:fail:contract:arity?
(lambda (exn)
(let* ((msg (exn-message exn))
(msg1 (regexp-match #px"(.*): arity mismatch" msg)))
(cond
[msg1
(let ((raised-name (cadr msg1)))
(if (equal? #,name raised-name)
(error-check (lambda (v) #f) #,name SATISFIED-FMT #t)
(raise exn)))]
[else (raise exn)])))])
(#,prop1 x)))])
(check-expect-maker stx
#'do-check-satisfied
#'actual:exp
(list code name)
'comes-from-check-satisfied))]
[(_ actual:exp expected-predicate:exp)
(let ([pred #`(let ([p? expected-predicate:exp])
(let ((name (object-name p?)))
(unless (and (procedure? p?) (procedure-arity-includes? p? 1))
this produces the BSL / ISL name
(error-check (lambda (v) #f) name SATISFIED-FMT #t)
(error-check (lambda (v) #f) p? SATISFIED-FMT #t))))
p?)])
(check-expect-maker stx
#'do-check-satisfied
#'actual:exp
(list pred "unknown name")
'comes-from-check-satisfied))]
[(_ actual:exp expected-predicate:exp)
(raise-syntax-error 'check-satisfied "expects named function in second position." stx)]
[_ (raise-syntax-error 'check-satisfied (argcount-error-message/stx 2 stx) stx)]))
(define (do-check-satisfied test p? name src)
(execute-test
src
(lambda ()
(unless (and (procedure? p?) (procedure-arity-includes? p? 1))
(error-check (lambda (v) #f) name SATISFIED-FMT #t))
(let* ((actual (test))
(ok? (p? actual)))
(cond
[(not (boolean? ok?))
(check-result (format "~a [as predicate in check-satisfied]" name) boolean? "boolean" ok?)]
[(not ok?)
(satisfied-failed src actual name)]
[else #t])))
(lambda (exn)
(unsatisfied-error/markup src name exn (exn->markup exn)))))
(define-syntax (check-within stx)
(check-context! 'check-within CHECK-WITHIN-DEFN-STR stx)
(syntax-case stx ()
[(_ test expected within)
(check-expect-maker stx #'do-check-within #`test (list #`expected #`within)
'comes-from-check-within)]
[_ (raise-syntax-error 'check-within (argcount-error-message/stx 3 stx) stx)]))
(define (do-check-within test expected within src)
(error-check number? within CHECK-WITHIN-INEXACT-FMT #t)
(error-check (lambda (v) (not (procedure? v))) expected CHECK-WITHIN-FUNCTION-FMT #f)
(execute-test
src
(lambda ()
(let ((actual (test)))
(if (beginner-equal~? actual expected within)
#t
(not-within src actual expected within))))
(make-exn->unexpected-error src expected)))
(define-syntax (check-error stx)
(check-context! 'check-error CHECK-ERROR-DEFN-STR stx)
(syntax-case stx ()
[(_ test error)
(check-expect-maker stx #'do-check-error #`test (list #`error)
'comes-from-check-error)]
[(_ test)
(check-expect-maker stx #'do-check-error/no-message #`test '()
'comes-from-check-error)]
[(_) (raise-syntax-error 'check-error (argcount-error-message/stx 1 stx #t) stx)]
[_ (raise-syntax-error 'check-error (argcount-error-message/stx 2 stx) stx)]))
(define (do-check-error test error src)
(error-check string? error CHECK-ERROR-STR-FMT #t)
(execute-test
src
(lambda ()
(with-handlers ([exn:fail?
(lambda (exn)
(let ((msg (get-rewritten-error-message exn)))
(if (equal? msg error)
#t
(incorrect-error/markup src error exn (exn->markup exn)))))])
(let ([actual (test)])
(expected-error src error actual))))
(define (do-check-error/no-message test src)
(execute-test
src
(lambda ()
(with-handlers ([exn:fail?
(lambda (exn) #t)])
(let ([actual (test)])
(expected-error src #f actual))))
(define-syntax (check-member-of stx)
(check-context! 'check-member-of CHECK-EXPECT-DEFN-STR stx)
(syntax-case stx ()
[(_ test expected expecteds ...)
(check-expect-maker stx
#'do-check-member-of
#`test
(list #`(list expected expecteds ...))
'comes-from-check-member-of)]
[_ (raise-syntax-error 'check-member-of (argcount-error-message/stx 2 stx #t) stx)]))
(define (do-check-member-of test expecteds src)
(for-each
(lambda (expected)
(error-check (lambda (v) (not (procedure? v))) expected CHECK-MEMBER-OF-FUNCTION-FMT #f))
expecteds)
(execute-test
src
(lambda ()
(let ((actual (test)))
(if (memf (lambda (expected) (teach-equal? actual expected)) expecteds)
#t
(not-mem src actual expecteds))))
(make-exn->unexpected-error src expecteds)))
(define-syntax (check-range stx)
(check-context! 'check-member-of CHECK-EXPECT-DEFN-STR stx)
(syntax-case stx ()
[(_ test min max)
(check-expect-maker stx #'do-check-range #`test (list #`min #`max)
'comes-from-check-range)]
[_ (raise-syntax-error 'check-range (argcount-error-message/stx 3 stx) stx)]))
(define (do-check-range test min max src)
(error-check number? min RANGE-MIN-FMT #t)
(error-check number? max RANGE-MAX-FMT #t)
(error-check (lambda (v) (not (procedure? v))) min CHECK-RANGE-FUNCTION-FMT #f)
(error-check (lambda (v) (not (procedure? v))) max CHECK-RANGE-FUNCTION-FMT #f)
(execute-test
src
(lambda ()
(let ((val (test)))
(if (and (number? val)
(<= min val max))
#t
(not-range src val min max))))
(make-exn->unexpected-error src (format "[~a, ~a]" min max))))
(define (error-check pred? actual fmt fmt-act?)
(unless (pred? actual)
(raise
(make-exn:fail:contract (if fmt-act? (format fmt actual) fmt)
(current-continuation-marks)))))
|
12c5a74917711fc727e4f1e3e2706e2c2794fc1965a1f2a60517d8e9e5e969c9 | TrustInSoft/tis-kernel | mark_noresults.ml | (**************************************************************************)
(* *)
This file is part of .
(* *)
is a fork of Frama - C. All the differences are :
Copyright ( C ) 2016 - 2017
(* *)
is released under GPLv2
(* *)
(**************************************************************************)
(**************************************************************************)
(* *)
This file is part of Frama - C.
(* *)
Copyright ( C ) 2007 - 2015
CEA ( Commissariat à l'énergie atomique et aux énergies
(* alternatives) *)
(* *)
(* you can redistribute it and/or modify it under the terms of the GNU *)
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
(* *)
(* It is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU Lesser General Public License for more details. *)
(* *)
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
(* *)
(**************************************************************************)
let should_memorize_function kf =
not
(Value_parameters.NoResultsAll.get() ||
Value_parameters.ObviouslyTerminatesAll.get () ||
Kernel_function.Set.mem kf (Value_parameters.NoResultsFunctions.get ()) ||
begin match kf.Cil_types.fundec with
| Cil_types.Declaration _ -> false
| Cil_types.Definition (f, _) ->
Cil_datatype.Fundec.Set.mem
f (Value_parameters.ObviouslyTerminatesFunctions.get ())
end)
let () = Db.Value.no_results :=
(fun kf -> not (should_memorize_function kf))
Signal that some results are not stored . The gui , or some calls to
Db . Value , may fail ungracefully
Db.Value, may fail ungracefully *)
let no_memoization_enabled () =
Value_parameters.NoResultsAll.get() ||
Value_parameters.ObviouslyTerminatesAll.get() ||
not (Value_parameters.NoResultsFunctions.is_empty ()) ||
not (Value_parameters.ObviouslyTerminatesFunctions.is_empty ())
(*
Local Variables:
compile-command: "make -C ../../../.."
End:
*)
| null | https://raw.githubusercontent.com/TrustInSoft/tis-kernel/748d28baba90c03c0f5f4654d2e7bb47dfbe4e7d/src/plugins/value/utils/mark_noresults.ml | ocaml | ************************************************************************
************************************************************************
************************************************************************
alternatives)
you can redistribute it and/or modify it under the terms of the GNU
It is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
************************************************************************
Local Variables:
compile-command: "make -C ../../../.."
End:
| This file is part of .
is a fork of Frama - C. All the differences are :
Copyright ( C ) 2016 - 2017
is released under GPLv2
This file is part of Frama - C.
Copyright ( C ) 2007 - 2015
CEA ( Commissariat à l'énergie atomique et aux énergies
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
let should_memorize_function kf =
not
(Value_parameters.NoResultsAll.get() ||
Value_parameters.ObviouslyTerminatesAll.get () ||
Kernel_function.Set.mem kf (Value_parameters.NoResultsFunctions.get ()) ||
begin match kf.Cil_types.fundec with
| Cil_types.Declaration _ -> false
| Cil_types.Definition (f, _) ->
Cil_datatype.Fundec.Set.mem
f (Value_parameters.ObviouslyTerminatesFunctions.get ())
end)
let () = Db.Value.no_results :=
(fun kf -> not (should_memorize_function kf))
Signal that some results are not stored . The gui , or some calls to
Db . Value , may fail ungracefully
Db.Value, may fail ungracefully *)
let no_memoization_enabled () =
Value_parameters.NoResultsAll.get() ||
Value_parameters.ObviouslyTerminatesAll.get() ||
not (Value_parameters.NoResultsFunctions.is_empty ()) ||
not (Value_parameters.ObviouslyTerminatesFunctions.is_empty ())
|
881de50d61b55bf8f6a4eecb4c9fa401636f31db5404690aa1d09bedf02dd508 | chris-emerson/rest_demo | project.clj | (defproject rest-demo "0.1.0-SNAPSHOT"
:description "An example Clojure REST API Implementation"
:url "/@functionalhuman/building-a-rest-api-in-clojure-3a1e1ae096e"
:license {:name "EPL-2.0 OR GPL-2.0-or-later WITH Classpath-exception-2.0"
:url "-2.0/"}
:dependencies [[org.clojure/clojure "1.10.0"]
Compojure - A basic routing library
[compojure "1.6.1"]
; Our Http library for client/server
[http-kit "2.3.0"]
Ring defaults - for query params etc
[ring/ring-defaults "0.3.2"]
Clojure data . JSON library
[org.clojure/data.json "0.2.6"]]
:main ^:skip-aot rest-demo.core
:target-path "target/%s"
:profiles {:uberjar {:aot :all}})
| null | https://raw.githubusercontent.com/chris-emerson/rest_demo/e28d0e94d544afd049a98563b0df2736513c67ad/project.clj | clojure | Our Http library for client/server | (defproject rest-demo "0.1.0-SNAPSHOT"
:description "An example Clojure REST API Implementation"
:url "/@functionalhuman/building-a-rest-api-in-clojure-3a1e1ae096e"
:license {:name "EPL-2.0 OR GPL-2.0-or-later WITH Classpath-exception-2.0"
:url "-2.0/"}
:dependencies [[org.clojure/clojure "1.10.0"]
Compojure - A basic routing library
[compojure "1.6.1"]
[http-kit "2.3.0"]
Ring defaults - for query params etc
[ring/ring-defaults "0.3.2"]
Clojure data . JSON library
[org.clojure/data.json "0.2.6"]]
:main ^:skip-aot rest-demo.core
:target-path "target/%s"
:profiles {:uberjar {:aot :all}})
|
cad64e7487f193eb15c99ad5b64e9f67131ab5a4d3a72bc227b4e2d4fc627ee2 | craigfe/progress | readme.ml | open Progress
let bar color message =
let total = 1_000_000_000L in
let open Line.Using_int64 in
list
[ rpad 16 (constf " %s" message)
; bytes
; bytes_per_sec
; bar ~color ~style:`UTF8 total
; percentage_of total ++ const " "
]
|> Multi.line
let main () =
let layout =
let open Multi in
bar (Color.hex "#90e0ef") "index.html"
++ bar (Color.hex "#48cae4") "sitemap.xml"
++ bar (Color.hex "#00b4d8") "img/kittens.jpg"
++ bar (Color.hex "#0096c7") "img/puppies.jpg"
in
with_reporters layout @@ fun a b c d ->
let pick_random () =
match Random.int 100 with
| n when n < 19 -> a
| n when n < 58 -> b
| n when n < 74 -> c
| _ -> d
in
let random_progress () = Random.int64 1_000_000L in
for i = 1 to 13_000 do
if i mod 100 = 0 then Logs.info (fun f -> f "Iterations reached: %d" i);
(pick_random ()) (random_progress ());
Unix.sleepf 0.001
done
let run () =
let () =
Run with [ VERBOSE = true ] to see log entries being interleaved with
progress bar rendering .
progress bar rendering. *)
match Sys.getenv_opt "VERBOSE" with
| None | Some "false" -> ()
| Some _ ->
(* Configure a [Logs] reporter that behaves properly with concurrent
progress bar rendering. *)
Logs.set_reporter (Progress.logs_reporter ());
Logs.set_level (Some Info)
in
main ()
| null | https://raw.githubusercontent.com/craigfe/progress/d7129b772d05c5589b8807630031155a6aeb27f0/examples/readme.ml | ocaml | Configure a [Logs] reporter that behaves properly with concurrent
progress bar rendering. | open Progress
let bar color message =
let total = 1_000_000_000L in
let open Line.Using_int64 in
list
[ rpad 16 (constf " %s" message)
; bytes
; bytes_per_sec
; bar ~color ~style:`UTF8 total
; percentage_of total ++ const " "
]
|> Multi.line
let main () =
let layout =
let open Multi in
bar (Color.hex "#90e0ef") "index.html"
++ bar (Color.hex "#48cae4") "sitemap.xml"
++ bar (Color.hex "#00b4d8") "img/kittens.jpg"
++ bar (Color.hex "#0096c7") "img/puppies.jpg"
in
with_reporters layout @@ fun a b c d ->
let pick_random () =
match Random.int 100 with
| n when n < 19 -> a
| n when n < 58 -> b
| n when n < 74 -> c
| _ -> d
in
let random_progress () = Random.int64 1_000_000L in
for i = 1 to 13_000 do
if i mod 100 = 0 then Logs.info (fun f -> f "Iterations reached: %d" i);
(pick_random ()) (random_progress ());
Unix.sleepf 0.001
done
let run () =
let () =
Run with [ VERBOSE = true ] to see log entries being interleaved with
progress bar rendering .
progress bar rendering. *)
match Sys.getenv_opt "VERBOSE" with
| None | Some "false" -> ()
| Some _ ->
Logs.set_reporter (Progress.logs_reporter ());
Logs.set_level (Some Info)
in
main ()
|
04ae242f3d279a4e9dc6049fb95e0227da53ca4e14e4c415b20522867f174def | dnikolovv/haskell-tic-tac-toe | Api.hs | # LANGUAGE ScopedTypeVariables #
module Api
( Api
, server
) where
import App
import Auth
import ClassyPrelude
import Commands
import Control.Monad.Catch (MonadThrow, throwM)
import Data.Has (Has)
import Data.Maybe
import qualified Data.UUID as U
import qualified Data.UUID.V4 as U
import Domain
import qualified Hubs as H
import Network.WebSockets (Connection, PendingConnection, forkPingThread, sendTextData)
import Servant hiding (Unauthorized)
import Servant.API.WebSocket
import Servant.Auth.Server
import Servant.Server hiding (Unauthorized)
import Views
import qualified Handlers
import Data.Aeson (ToJSON, encode)
import Control.Monad.Except (MonadError)
import Handlers (HandlerM)
import Error (AppError(..))
import Servant (ServerError(..))
import Data.CaseInsensitive (mk)
type Api = Protected :<|> Public :<|> Sockets
type AppServer api = ServerT api AppM
server :: AppServer Api
server = protectedServer :<|> publicServer :<|> socketsServer
type JwtAuth = Auth '[ JWT] AuthenticatedUser
type Public =
"users" :> "create" :> Capture "name" Text :> Post '[ JSON] TokenView
type Protected = JwtAuth :> (
"users" :> "current" :> Get '[ JSON] UserView :<|>
"users" :> "available" :> Get '[ JSON] [UserView] :<|>
"users" :> "invite" :> Capture "userId" U.UUID :> PostNoContent '[ JSON] NoContent :<|>
"invitation" :> "accept" :> Capture "invitationId" U.UUID :> PostNoContent '[ JSON] NoContent :<|>
"invitation" :> "decline" :> Capture "invitationId" U.UUID :> PostNoContent '[ JSON] NoContent :<|>
"game" :> "move" :> ReqBody '[ JSON] SubmitGameMove :> PutNoContent '[ JSON] NoContent)
type Sockets =
"notifications" :> "subscribe" :> WebSocketPending :<|>
"game" :> Capture "gameId" U.UUID :> WebSocketPending
publicServer :: AppServer Public
publicServer = createUser
where
createUser = runHandlerOp . Handlers.createUser
protectedServer :: AppServer Protected
protectedServer (Authenticated user) =
getCurrentUser :<|>
listAvailableUsers :<|>
inviteUser :<|>
acceptInvitation :<|>
declineInvitation :<|>
submitGameMove
where
getCurrentUser = return $ UserView (U.toText . aUserId $ user) (aUserName user)
listAvailableUsers = runHandlerOp Handlers.listAvailableUsers
inviteUser userToInviteId = runHandlerOp $ Handlers.inviteUser (aUserId user) userToInviteId >> return NoContent
-- TODO: Validate who is accepting/declining the invitation
acceptInvitation id = runHandlerOp $ Handlers.acceptInvitation id >> return NoContent
declineInvitation id = runHandlerOp $ Handlers.declineInvitation id >> return NoContent
submitGameMove submitMoveCmd = runHandlerOp $ Handlers.submitGameMove user submitMoveCmd >> return NoContent
No throwAll because of the MonadUnliftIO hack - -13-reader-io/
protectedServer _ = throwM err401 :<|> throwM err401 :<|> (\_ -> throwM err401) :<|> (\_ -> throwM err401) :<|> (\_ -> throwM err401) :<|> (\_ -> throwM err401)
socketsServer :: AppServer Sockets
socketsServer = subscribeForNotifications :<|> subscribeForGame
where
subscribeForNotifications pConn = void $ runHandlerOp $ Handlers.subscribeToHubAsUser H.NotificationsHub pConn
subscribeForGame gameId conn = runHandlerOp $ Handlers.subscribeForGameEvents gameId conn
newtype ApiError =
ApiError
{ message :: Text
}
deriving (Generic)
instance ToJSON ApiError
runHandlerOp :: (MonadIO m, MonadReader State m, MonadThrow m, MonadUnliftIO m) => HandlerM a -> m a
runHandlerOp handlerOp =
Handlers.liftHandler handlerOp `catch` (\(ex :: AppError) -> handleError ex)
where
handleError ex = throwM $ toServantError ex
toServantError :: AppError -> ServerError
toServantError (ValidationError msg) = servantErrorWithText err400 msg
toServantError (Unauthorized msg) = servantErrorWithText err401 msg
toServantError (NotFound msg) = servantErrorWithText err404 msg
toServantError (Conflict msg) = servantErrorWithText err409 msg
servantErrorWithText :: ServerError -> Text -> ServerError
servantErrorWithText sErr message = sErr {errBody = errorBody, errHeaders = [jsonHeaders]}
where
errorBody = encode $ ApiError message
jsonHeaders = (mk "Content-Type", "application/json;charset=utf-8") | null | https://raw.githubusercontent.com/dnikolovv/haskell-tic-tac-toe/d8282dfcd73a07d49a86312a1f7f7275dadabc3a/src/Api.hs | haskell | TODO: Validate who is accepting/declining the invitation | # LANGUAGE ScopedTypeVariables #
module Api
( Api
, server
) where
import App
import Auth
import ClassyPrelude
import Commands
import Control.Monad.Catch (MonadThrow, throwM)
import Data.Has (Has)
import Data.Maybe
import qualified Data.UUID as U
import qualified Data.UUID.V4 as U
import Domain
import qualified Hubs as H
import Network.WebSockets (Connection, PendingConnection, forkPingThread, sendTextData)
import Servant hiding (Unauthorized)
import Servant.API.WebSocket
import Servant.Auth.Server
import Servant.Server hiding (Unauthorized)
import Views
import qualified Handlers
import Data.Aeson (ToJSON, encode)
import Control.Monad.Except (MonadError)
import Handlers (HandlerM)
import Error (AppError(..))
import Servant (ServerError(..))
import Data.CaseInsensitive (mk)
type Api = Protected :<|> Public :<|> Sockets
type AppServer api = ServerT api AppM
server :: AppServer Api
server = protectedServer :<|> publicServer :<|> socketsServer
type JwtAuth = Auth '[ JWT] AuthenticatedUser
type Public =
"users" :> "create" :> Capture "name" Text :> Post '[ JSON] TokenView
type Protected = JwtAuth :> (
"users" :> "current" :> Get '[ JSON] UserView :<|>
"users" :> "available" :> Get '[ JSON] [UserView] :<|>
"users" :> "invite" :> Capture "userId" U.UUID :> PostNoContent '[ JSON] NoContent :<|>
"invitation" :> "accept" :> Capture "invitationId" U.UUID :> PostNoContent '[ JSON] NoContent :<|>
"invitation" :> "decline" :> Capture "invitationId" U.UUID :> PostNoContent '[ JSON] NoContent :<|>
"game" :> "move" :> ReqBody '[ JSON] SubmitGameMove :> PutNoContent '[ JSON] NoContent)
type Sockets =
"notifications" :> "subscribe" :> WebSocketPending :<|>
"game" :> Capture "gameId" U.UUID :> WebSocketPending
publicServer :: AppServer Public
publicServer = createUser
where
createUser = runHandlerOp . Handlers.createUser
protectedServer :: AppServer Protected
protectedServer (Authenticated user) =
getCurrentUser :<|>
listAvailableUsers :<|>
inviteUser :<|>
acceptInvitation :<|>
declineInvitation :<|>
submitGameMove
where
getCurrentUser = return $ UserView (U.toText . aUserId $ user) (aUserName user)
listAvailableUsers = runHandlerOp Handlers.listAvailableUsers
inviteUser userToInviteId = runHandlerOp $ Handlers.inviteUser (aUserId user) userToInviteId >> return NoContent
acceptInvitation id = runHandlerOp $ Handlers.acceptInvitation id >> return NoContent
declineInvitation id = runHandlerOp $ Handlers.declineInvitation id >> return NoContent
submitGameMove submitMoveCmd = runHandlerOp $ Handlers.submitGameMove user submitMoveCmd >> return NoContent
No throwAll because of the MonadUnliftIO hack - -13-reader-io/
protectedServer _ = throwM err401 :<|> throwM err401 :<|> (\_ -> throwM err401) :<|> (\_ -> throwM err401) :<|> (\_ -> throwM err401) :<|> (\_ -> throwM err401)
socketsServer :: AppServer Sockets
socketsServer = subscribeForNotifications :<|> subscribeForGame
where
subscribeForNotifications pConn = void $ runHandlerOp $ Handlers.subscribeToHubAsUser H.NotificationsHub pConn
subscribeForGame gameId conn = runHandlerOp $ Handlers.subscribeForGameEvents gameId conn
newtype ApiError =
ApiError
{ message :: Text
}
deriving (Generic)
instance ToJSON ApiError
runHandlerOp :: (MonadIO m, MonadReader State m, MonadThrow m, MonadUnliftIO m) => HandlerM a -> m a
runHandlerOp handlerOp =
Handlers.liftHandler handlerOp `catch` (\(ex :: AppError) -> handleError ex)
where
handleError ex = throwM $ toServantError ex
toServantError :: AppError -> ServerError
toServantError (ValidationError msg) = servantErrorWithText err400 msg
toServantError (Unauthorized msg) = servantErrorWithText err401 msg
toServantError (NotFound msg) = servantErrorWithText err404 msg
toServantError (Conflict msg) = servantErrorWithText err409 msg
servantErrorWithText :: ServerError -> Text -> ServerError
servantErrorWithText sErr message = sErr {errBody = errorBody, errHeaders = [jsonHeaders]}
where
errorBody = encode $ ApiError message
jsonHeaders = (mk "Content-Type", "application/json;charset=utf-8") |
28839932ab030e6c6eaef4f4ab33ef3a7eba648c0924755650e31e7c24ec2797 | Haskell-OpenAPI-Code-Generator/Stripe-Haskell-Library | SetupIntentNextActionVerifyWithMicrodeposits.hs | {-# LANGUAGE MultiWayIf #-}
CHANGE WITH CAUTION : This is a generated code file generated by -OpenAPI-Code-Generator/Haskell-OpenAPI-Client-Code-Generator .
{-# LANGUAGE OverloadedStrings #-}
-- | Contains the types generated from the schema SetupIntentNextActionVerifyWithMicrodeposits
module StripeAPI.Types.SetupIntentNextActionVerifyWithMicrodeposits where
import qualified Control.Monad.Fail
import qualified Data.Aeson
import qualified Data.Aeson as Data.Aeson.Encoding.Internal
import qualified Data.Aeson as Data.Aeson.Types
import qualified Data.Aeson as Data.Aeson.Types.FromJSON
import qualified Data.Aeson as Data.Aeson.Types.Internal
import qualified Data.Aeson as Data.Aeson.Types.ToJSON
import qualified Data.ByteString.Char8
import qualified Data.ByteString.Char8 as Data.ByteString.Internal
import qualified Data.Foldable
import qualified Data.Functor
import qualified Data.Maybe
import qualified Data.Scientific
import qualified Data.Text
import qualified Data.Text.Internal
import qualified Data.Time.Calendar as Data.Time.Calendar.Days
import qualified Data.Time.LocalTime as Data.Time.LocalTime.Internal.ZonedTime
import qualified GHC.Base
import qualified GHC.Classes
import qualified GHC.Int
import qualified GHC.Show
import qualified GHC.Types
import qualified StripeAPI.Common
import StripeAPI.TypeAlias
import qualified Prelude as GHC.Integer.Type
import qualified Prelude as GHC.Maybe
-- | Defines the object schema located at @components.schemas.setup_intent_next_action_verify_with_microdeposits@ in the specification.
data SetupIntentNextActionVerifyWithMicrodeposits = SetupIntentNextActionVerifyWithMicrodeposits
| arrival_date : The timestamp when the are expected to land .
setupIntentNextActionVerifyWithMicrodepositsArrivalDate :: GHC.Types.Int,
-- | hosted_verification_url: The URL for the hosted verification page, which allows customers to verify their bank account.
--
-- Constraints:
--
* Maximum length of 5000
setupIntentNextActionVerifyWithMicrodepositsHostedVerificationUrl :: Data.Text.Internal.Text,
| microdeposit_type : The type of the microdeposit sent to the customer . Used to distinguish between different verification methods .
setupIntentNextActionVerifyWithMicrodepositsMicrodepositType :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable SetupIntentNextActionVerifyWithMicrodepositsMicrodepositType'NonNullable))
}
deriving
( GHC.Show.Show,
GHC.Classes.Eq
)
instance Data.Aeson.Types.ToJSON.ToJSON SetupIntentNextActionVerifyWithMicrodeposits where
toJSON obj = Data.Aeson.Types.Internal.object (Data.Foldable.concat (["arrival_date" Data.Aeson.Types.ToJSON..= setupIntentNextActionVerifyWithMicrodepositsArrivalDate obj] : ["hosted_verification_url" Data.Aeson.Types.ToJSON..= setupIntentNextActionVerifyWithMicrodepositsHostedVerificationUrl obj] : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("microdeposit_type" Data.Aeson.Types.ToJSON..=)) (setupIntentNextActionVerifyWithMicrodepositsMicrodepositType obj) : GHC.Base.mempty))
toEncoding obj = Data.Aeson.Encoding.Internal.pairs (GHC.Base.mconcat (Data.Foldable.concat (["arrival_date" Data.Aeson.Types.ToJSON..= setupIntentNextActionVerifyWithMicrodepositsArrivalDate obj] : ["hosted_verification_url" Data.Aeson.Types.ToJSON..= setupIntentNextActionVerifyWithMicrodepositsHostedVerificationUrl obj] : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("microdeposit_type" Data.Aeson.Types.ToJSON..=)) (setupIntentNextActionVerifyWithMicrodepositsMicrodepositType obj) : GHC.Base.mempty)))
instance Data.Aeson.Types.FromJSON.FromJSON SetupIntentNextActionVerifyWithMicrodeposits where
parseJSON = Data.Aeson.Types.FromJSON.withObject "SetupIntentNextActionVerifyWithMicrodeposits" (\obj -> ((GHC.Base.pure SetupIntentNextActionVerifyWithMicrodeposits GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..: "arrival_date")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..: "hosted_verification_url")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "microdeposit_type"))
-- | Create a new 'SetupIntentNextActionVerifyWithMicrodeposits' with all required fields.
mkSetupIntentNextActionVerifyWithMicrodeposits ::
| ' '
GHC.Types.Int ->
-- | 'setupIntentNextActionVerifyWithMicrodepositsHostedVerificationUrl'
Data.Text.Internal.Text ->
SetupIntentNextActionVerifyWithMicrodeposits
mkSetupIntentNextActionVerifyWithMicrodeposits setupIntentNextActionVerifyWithMicrodepositsArrivalDate setupIntentNextActionVerifyWithMicrodepositsHostedVerificationUrl =
SetupIntentNextActionVerifyWithMicrodeposits
{ setupIntentNextActionVerifyWithMicrodepositsArrivalDate = setupIntentNextActionVerifyWithMicrodepositsArrivalDate,
setupIntentNextActionVerifyWithMicrodepositsHostedVerificationUrl = setupIntentNextActionVerifyWithMicrodepositsHostedVerificationUrl,
setupIntentNextActionVerifyWithMicrodepositsMicrodepositType = GHC.Maybe.Nothing
}
| Defines the enum schema located at in the specification .
--
The type of the microdeposit sent to the customer . Used to distinguish between different verification methods .
data SetupIntentNextActionVerifyWithMicrodepositsMicrodepositType'NonNullable
= -- | This case is used if the value encountered during decoding does not match any of the provided cases in the specification.
SetupIntentNextActionVerifyWithMicrodepositsMicrodepositType'NonNullableOther Data.Aeson.Types.Internal.Value
| -- | This constructor can be used to send values to the server which are not present in the specification yet.
SetupIntentNextActionVerifyWithMicrodepositsMicrodepositType'NonNullableTyped Data.Text.Internal.Text
| Represents the JSON value
SetupIntentNextActionVerifyWithMicrodepositsMicrodepositType'NonNullableEnumAmounts
| -- | Represents the JSON value @"descriptor_code"@
SetupIntentNextActionVerifyWithMicrodepositsMicrodepositType'NonNullableEnumDescriptorCode
deriving (GHC.Show.Show, GHC.Classes.Eq)
instance Data.Aeson.Types.ToJSON.ToJSON SetupIntentNextActionVerifyWithMicrodepositsMicrodepositType'NonNullable where
toJSON (SetupIntentNextActionVerifyWithMicrodepositsMicrodepositType'NonNullableOther val) = val
toJSON (SetupIntentNextActionVerifyWithMicrodepositsMicrodepositType'NonNullableTyped val) = Data.Aeson.Types.ToJSON.toJSON val
toJSON (SetupIntentNextActionVerifyWithMicrodepositsMicrodepositType'NonNullableEnumAmounts) = "amounts"
toJSON (SetupIntentNextActionVerifyWithMicrodepositsMicrodepositType'NonNullableEnumDescriptorCode) = "descriptor_code"
instance Data.Aeson.Types.FromJSON.FromJSON SetupIntentNextActionVerifyWithMicrodepositsMicrodepositType'NonNullable where
parseJSON val =
GHC.Base.pure
( if
| val GHC.Classes.== "amounts" -> SetupIntentNextActionVerifyWithMicrodepositsMicrodepositType'NonNullableEnumAmounts
| val GHC.Classes.== "descriptor_code" -> SetupIntentNextActionVerifyWithMicrodepositsMicrodepositType'NonNullableEnumDescriptorCode
| GHC.Base.otherwise -> SetupIntentNextActionVerifyWithMicrodepositsMicrodepositType'NonNullableOther val
)
| null | https://raw.githubusercontent.com/Haskell-OpenAPI-Code-Generator/Stripe-Haskell-Library/ba4401f083ff054f8da68c741f762407919de42f/src/StripeAPI/Types/SetupIntentNextActionVerifyWithMicrodeposits.hs | haskell | # LANGUAGE MultiWayIf #
# LANGUAGE OverloadedStrings #
| Contains the types generated from the schema SetupIntentNextActionVerifyWithMicrodeposits
| Defines the object schema located at @components.schemas.setup_intent_next_action_verify_with_microdeposits@ in the specification.
| hosted_verification_url: The URL for the hosted verification page, which allows customers to verify their bank account.
Constraints:
| Create a new 'SetupIntentNextActionVerifyWithMicrodeposits' with all required fields.
| 'setupIntentNextActionVerifyWithMicrodepositsHostedVerificationUrl'
| This case is used if the value encountered during decoding does not match any of the provided cases in the specification.
| This constructor can be used to send values to the server which are not present in the specification yet.
| Represents the JSON value @"descriptor_code"@ | CHANGE WITH CAUTION : This is a generated code file generated by -OpenAPI-Code-Generator/Haskell-OpenAPI-Client-Code-Generator .
module StripeAPI.Types.SetupIntentNextActionVerifyWithMicrodeposits where
import qualified Control.Monad.Fail
import qualified Data.Aeson
import qualified Data.Aeson as Data.Aeson.Encoding.Internal
import qualified Data.Aeson as Data.Aeson.Types
import qualified Data.Aeson as Data.Aeson.Types.FromJSON
import qualified Data.Aeson as Data.Aeson.Types.Internal
import qualified Data.Aeson as Data.Aeson.Types.ToJSON
import qualified Data.ByteString.Char8
import qualified Data.ByteString.Char8 as Data.ByteString.Internal
import qualified Data.Foldable
import qualified Data.Functor
import qualified Data.Maybe
import qualified Data.Scientific
import qualified Data.Text
import qualified Data.Text.Internal
import qualified Data.Time.Calendar as Data.Time.Calendar.Days
import qualified Data.Time.LocalTime as Data.Time.LocalTime.Internal.ZonedTime
import qualified GHC.Base
import qualified GHC.Classes
import qualified GHC.Int
import qualified GHC.Show
import qualified GHC.Types
import qualified StripeAPI.Common
import StripeAPI.TypeAlias
import qualified Prelude as GHC.Integer.Type
import qualified Prelude as GHC.Maybe
data SetupIntentNextActionVerifyWithMicrodeposits = SetupIntentNextActionVerifyWithMicrodeposits
| arrival_date : The timestamp when the are expected to land .
setupIntentNextActionVerifyWithMicrodepositsArrivalDate :: GHC.Types.Int,
* Maximum length of 5000
setupIntentNextActionVerifyWithMicrodepositsHostedVerificationUrl :: Data.Text.Internal.Text,
| microdeposit_type : The type of the microdeposit sent to the customer . Used to distinguish between different verification methods .
setupIntentNextActionVerifyWithMicrodepositsMicrodepositType :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable SetupIntentNextActionVerifyWithMicrodepositsMicrodepositType'NonNullable))
}
deriving
( GHC.Show.Show,
GHC.Classes.Eq
)
instance Data.Aeson.Types.ToJSON.ToJSON SetupIntentNextActionVerifyWithMicrodeposits where
toJSON obj = Data.Aeson.Types.Internal.object (Data.Foldable.concat (["arrival_date" Data.Aeson.Types.ToJSON..= setupIntentNextActionVerifyWithMicrodepositsArrivalDate obj] : ["hosted_verification_url" Data.Aeson.Types.ToJSON..= setupIntentNextActionVerifyWithMicrodepositsHostedVerificationUrl obj] : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("microdeposit_type" Data.Aeson.Types.ToJSON..=)) (setupIntentNextActionVerifyWithMicrodepositsMicrodepositType obj) : GHC.Base.mempty))
toEncoding obj = Data.Aeson.Encoding.Internal.pairs (GHC.Base.mconcat (Data.Foldable.concat (["arrival_date" Data.Aeson.Types.ToJSON..= setupIntentNextActionVerifyWithMicrodepositsArrivalDate obj] : ["hosted_verification_url" Data.Aeson.Types.ToJSON..= setupIntentNextActionVerifyWithMicrodepositsHostedVerificationUrl obj] : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("microdeposit_type" Data.Aeson.Types.ToJSON..=)) (setupIntentNextActionVerifyWithMicrodepositsMicrodepositType obj) : GHC.Base.mempty)))
instance Data.Aeson.Types.FromJSON.FromJSON SetupIntentNextActionVerifyWithMicrodeposits where
parseJSON = Data.Aeson.Types.FromJSON.withObject "SetupIntentNextActionVerifyWithMicrodeposits" (\obj -> ((GHC.Base.pure SetupIntentNextActionVerifyWithMicrodeposits GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..: "arrival_date")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..: "hosted_verification_url")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "microdeposit_type"))
mkSetupIntentNextActionVerifyWithMicrodeposits ::
| ' '
GHC.Types.Int ->
Data.Text.Internal.Text ->
SetupIntentNextActionVerifyWithMicrodeposits
mkSetupIntentNextActionVerifyWithMicrodeposits setupIntentNextActionVerifyWithMicrodepositsArrivalDate setupIntentNextActionVerifyWithMicrodepositsHostedVerificationUrl =
SetupIntentNextActionVerifyWithMicrodeposits
{ setupIntentNextActionVerifyWithMicrodepositsArrivalDate = setupIntentNextActionVerifyWithMicrodepositsArrivalDate,
setupIntentNextActionVerifyWithMicrodepositsHostedVerificationUrl = setupIntentNextActionVerifyWithMicrodepositsHostedVerificationUrl,
setupIntentNextActionVerifyWithMicrodepositsMicrodepositType = GHC.Maybe.Nothing
}
| Defines the enum schema located at in the specification .
The type of the microdeposit sent to the customer . Used to distinguish between different verification methods .
data SetupIntentNextActionVerifyWithMicrodepositsMicrodepositType'NonNullable
SetupIntentNextActionVerifyWithMicrodepositsMicrodepositType'NonNullableOther Data.Aeson.Types.Internal.Value
SetupIntentNextActionVerifyWithMicrodepositsMicrodepositType'NonNullableTyped Data.Text.Internal.Text
| Represents the JSON value
SetupIntentNextActionVerifyWithMicrodepositsMicrodepositType'NonNullableEnumAmounts
SetupIntentNextActionVerifyWithMicrodepositsMicrodepositType'NonNullableEnumDescriptorCode
deriving (GHC.Show.Show, GHC.Classes.Eq)
instance Data.Aeson.Types.ToJSON.ToJSON SetupIntentNextActionVerifyWithMicrodepositsMicrodepositType'NonNullable where
toJSON (SetupIntentNextActionVerifyWithMicrodepositsMicrodepositType'NonNullableOther val) = val
toJSON (SetupIntentNextActionVerifyWithMicrodepositsMicrodepositType'NonNullableTyped val) = Data.Aeson.Types.ToJSON.toJSON val
toJSON (SetupIntentNextActionVerifyWithMicrodepositsMicrodepositType'NonNullableEnumAmounts) = "amounts"
toJSON (SetupIntentNextActionVerifyWithMicrodepositsMicrodepositType'NonNullableEnumDescriptorCode) = "descriptor_code"
instance Data.Aeson.Types.FromJSON.FromJSON SetupIntentNextActionVerifyWithMicrodepositsMicrodepositType'NonNullable where
parseJSON val =
GHC.Base.pure
( if
| val GHC.Classes.== "amounts" -> SetupIntentNextActionVerifyWithMicrodepositsMicrodepositType'NonNullableEnumAmounts
| val GHC.Classes.== "descriptor_code" -> SetupIntentNextActionVerifyWithMicrodepositsMicrodepositType'NonNullableEnumDescriptorCode
| GHC.Base.otherwise -> SetupIntentNextActionVerifyWithMicrodepositsMicrodepositType'NonNullableOther val
)
|
66d024da8d0afa84207e0f8c8f7ffe8e2d1fd71803923cc404701bd09d9241dc | fakedata-haskell/fakedata | TextSpec.hs | # LANGUAGE ScopedTypeVariables #
module TextSpec where
import Data.Text (Text)
import qualified Data.Text as T
import Faker hiding (defaultFakerSettings)
import qualified Faker.Address as FA
import qualified Faker.Ancient as AN
import qualified Faker.App as AP
import qualified Faker.Appliance as AP
import qualified Faker.Artist as AR
import qualified Faker.Bank as BA
import qualified Faker.Barcode as BC
import qualified Faker.Beer as BE
import qualified Faker.Blood as BL
import qualified Faker.Book as BO
import qualified Faker.Book.CultureSeries as CE
import qualified Faker.Book.Dune as DU
import qualified Faker.Book.Lovecraft as LO
import qualified Faker.BossaNova as BO
import qualified Faker.Business as BU
import qualified Faker.Cannabis as CA
import qualified Faker.Chiquito as CI
import qualified Faker.ChuckNorris as CH
import qualified Faker.Code as CO
import qualified Faker.Coffee as CO
import qualified Faker.Coin as CO
import qualified Faker.Color as CO
import qualified Faker.Commerce as CO
import qualified Faker.Company as CM
import qualified Faker.Compass as CO
import qualified Faker.Computer as COM
import qualified Faker.Construction as CO
import qualified Faker.Cosmere as CO
import qualified Faker.Creature.Animal as AN
import qualified Faker.Creature.Cat as CA
import qualified Faker.Creature.Dog as DO
import qualified Faker.Creature.Horse as HO
import qualified Faker.CryptoCoin as CO
import qualified Faker.Currency as CU
import qualified Faker.DcComics as DC
import qualified Faker.Demographic as DE
import qualified Faker.Dessert as DE
import qualified Faker.Dnd as DN
import qualified Faker.DrivingLicense as DR
import qualified Faker.Drone as DX
import qualified Faker.Educator as ED
import qualified Faker.ElectricalComponents as EC
import qualified Faker.Esport as ES
import qualified Faker.File as FI
import qualified Faker.Finance as FI
import qualified Faker.Food as FO
import qualified Faker.FunnyName as FU
import qualified Faker.Game.Control as GC
import qualified Faker.Game.Dota as DO
import qualified Faker.Game.ElderScrolls as EL
import qualified Faker.Game.Fallout as FA
import qualified Faker.Game.HalfLife as HA
import qualified Faker.Game.Heroes as HE
import qualified Faker.Game.HeroesOfTheStorm as HS
import qualified Faker.Game.Minecraft as MC
import qualified Faker.Game.Myst as MY
import qualified Faker.Game.Overwatch as OV
import qualified Faker.Game.Pokemon as PO
import qualified Faker.Game.SonicTheHedgehog as SO
import qualified Faker.Game.StreetFighter as SF
import qualified Faker.Game.SuperSmashBros as SU
import qualified Faker.Game.WarhammerFantasy as WF
import qualified Faker.Game.Witcher as WI
import qualified Faker.Game.WorldOfWarcraft as WO
import qualified Faker.Game.Zelda as ZE
import qualified Faker.Gender as GE
import qualified Faker.GreekPhilosophers as GR
import qualified Faker.Hacker as HA
import qualified Faker.Hipster as HI
import qualified Faker.House as HO
import qualified Faker.IndustrySegments as IN
import qualified Faker.Internet as IN
import qualified Faker.JapaneseMedia.DragonBall as DR
import qualified Faker.JapaneseMedia.OnePiece as ON
import qualified Faker.JapaneseMedia.StudioGhibli as GI
import qualified Faker.JapaneseMedia.SwordArtOnline as SW
import qualified Faker.Job as JO
import qualified Faker.Kpop as KP
import qualified Faker.LeagueOfLegends as LE
import qualified Faker.Lorem as LM
import qualified Faker.Markdown as MA
import qualified Faker.Marketing as MA
import qualified Faker.Measurement as ME
import qualified Faker.Military as MI
import qualified Faker.Movie as MO
import qualified Faker.Movie.BackToTheFuture as BA
import qualified Faker.Movie.Departed as MD
import qualified Faker.Movie.Ghostbusters as GH
import qualified Faker.Movie.GratefulDead as GR
import qualified Faker.Movie.HarryPotter as HA
import qualified Faker.Movie.HitchhikersGuideToTheGalaxy as HI
import qualified Faker.Movie.Lebowski as LE
import qualified Faker.Movie.PrincessBride as PR
import qualified Faker.Movie.StarWars as ST
import qualified Faker.Movie.VForVendetta as VF
import qualified Faker.Music as MU
import qualified Faker.Music.Opera as OP
import qualified Faker.Music.PearlJam as PJ
import qualified Faker.Music.Phish as PH
import qualified Faker.Music.Prince as PC
import qualified Faker.Music.RockBand as RO
import qualified Faker.Music.Rush as RU
import qualified Faker.Music.UmphreysMcgee as UM
import qualified Faker.Name as NA
import qualified Faker.Nation as NA
import qualified Faker.NatoPhoneticAlphabet as NA
import qualified Faker.PhoneNumber as PH
import qualified Faker.ProgrammingLanguage as PR
import qualified Faker.Quote as QU
import qualified Faker.Quote.Shakespeare as SH
import qualified Faker.Rajnikanth as RK
import qualified Faker.Relationship as RE
import qualified Faker.Restaurant as RE
import qualified Faker.Science as SC
import qualified Faker.Show as WS
import qualified Faker.SlackEmoji as SL
import qualified Faker.Source as SO
import qualified Faker.Space as SP
import qualified Faker.Sport.Basketball as BA
import qualified Faker.Sport.Football as FO
import qualified Faker.Subscription as SU
import qualified Faker.Superhero as SU
import qualified Faker.Team as TE
import qualified Faker.TvShow.AquaTeenHungerForce as AQ
import qualified Faker.TvShow.BigBangTheory as BB
import qualified Faker.TvShow.BoJackHorseman as BO
import qualified Faker.TvShow.BreakingBad as BR
import qualified Faker.TvShow.Buffy as BU
import qualified Faker.TvShow.Community as CO
import qualified Faker.TvShow.DrWho as DR
import qualified Faker.TvShow.DumbAndDumber as DD
import qualified Faker.TvShow.FamilyGuy as FA
import qualified Faker.TvShow.FreshPrinceOfBelAir as FR
import qualified Faker.TvShow.Friends as FI
import qualified Faker.TvShow.Futurama as FT
import qualified Faker.TvShow.GameOfThrones as GA
import qualified Faker.TvShow.HeyArnold as HE
import qualified Faker.TvShow.HowIMetYourMother as HI
import qualified Faker.TvShow.MichaelScott as MI
import qualified Faker.TvShow.NewGirl as NE
import qualified Faker.TvShow.ParksAndRec as PA
import qualified Faker.TvShow.RickAndMorty as RI
import qualified Faker.TvShow.Rupaul as RU
import qualified Faker.TvShow.Seinfeld as SE
import qualified Faker.TvShow.SiliconValley as SI
import qualified Faker.TvShow.Simpsons as SS
import qualified Faker.TvShow.SouthPark as SO
import qualified Faker.TvShow.StarTrek as SR
import qualified Faker.TvShow.Stargate as SG
import qualified Faker.TvShow.StrangerThings as SH
import qualified Faker.TvShow.Suits as SU
import qualified Faker.TvShow.TheExpanse as TH
import qualified Faker.TvShow.TheItCrowd as TI
import qualified Faker.TvShow.TheThickOfIt as TO
import qualified Faker.TvShow.TwinPeaks as TW
import qualified Faker.TvShow.VentureBros as VE
import qualified Faker.University as UN
import qualified Faker.Vehicle as VE
import qualified Faker.Verbs as VE
import qualified Faker.WorldCup as WO
import qualified Faker.Yoda as YO
import System.IO.Unsafe (unsafePerformIO)
import qualified Faker
import Faker (Fake)
import System.Random (mkStdGen)
import Text.Regex.TDFA hiding (empty)
import Test.Hspec.QuickCheck(prop)
import qualified Test.QuickCheck as Q
import Test.Hspec
import TestImport
isText :: Text -> Bool
isText x = T.length x >= 1
fakerSettings :: FakerSettings
fakerSettings = defaultFakerSettings
verifyFakes :: [Fake Text] -> IO [Bool]
verifyFakes funs = do
let fs :: [IO Text] = map (generateWithSettings fakerSettings) funs
gs :: [IO Bool] = map (\f -> isText <$> f) fs
sequence gs
verifyFakeInt :: [Fake Int] -> IO [Bool]
verifyFakeInt funs = do
let fs :: [IO Int] = map (generateWithSettings fakerSettings) funs
gs :: [IO Bool] = map (\f -> (\x -> x >= 0) <$> f) fs
sequence gs
-- copied from -fakedata/blob/d342c6eb5aeb9990bb36ede1d1f08becc7d71e16/src/Hedgehog/Gen/Faker.hs
I need it for but it 's a cyclic dependency
-- made it work for quickeck instead of hedgehog.
-- who needs side affects anyway?
--
-- Select a value 'Fake' program in 'Gen'.
fakeQuickcheck :: Fake a -> Q.Gen a
fakeQuickcheck f = do
randomGen <- mkStdGen <$> Q.choose (minBound, maxBound)
pure $!
unsafePerformIO $
Faker.generateWithSettings
(Faker.setRandomGen
randomGen
fakerSettings
)
f
isDomain :: Text -> Bool
isDomain = (=~ "^[A-Za-z_]+\\.[a-z]{1,4}$") . T.unpack
isName :: Text -> Bool
isName = (=~ "^[A-Za-z_]+$") . T.unpack
isNum :: Text -> Bool
isNum = (=~ "^[0-9]+$") . T.unpack
isEmail :: Text -> Bool
isEmail input =
if (length splitAt /= 2) || (length splitDash /= 2) then False
else
isDomain domain && isName name && isNum num
where
splitAt = T.splitOn at input
[nameNum, domain] = splitAt
splitDash = T.splitOn dash nameNum
[name, num] = splitDash
dash :: Text
dash = T.pack "-"
at :: Text
at = T.pack "@"
spec :: Spec
spec = do
describe "TextSpec" $ do
it "Address" $ do
let functions :: [Fake Text] =
[ FA.country,
FA.cityPrefix,
FA.citySuffix,
FA.countryCode,
FA.countryCodeLong,
FA.buildingNumber,
FA.communityPrefix,
FA.communitySuffix,
FA.community,
FA.streetSuffix,
FA.secondaryAddress,
FA.postcode,
FA.state,
FA.stateAbbr,
FA.timeZone,
FA.city,
FA.streetName,
FA.streetAddress,
FA.fullAddress,
FA.mailBox,
FA.cityWithState
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Ancient" $ do
let functions :: [Fake Text] = [AN.god, AN.primordial, AN.hero, AN.titan]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "App" $ do
let functions :: [Fake Text] = [AP.name, AP.version]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Appliance" $ do
let functions :: [Fake Text] = [AP.brand, AP.equipment]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Artist" $ do
let functions :: [Fake Text] = [AR.names]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Bank" $ do
let functions :: [Fake Text] = [BA.name, BA.swiftBic]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Barcode" $ do
let functions :: [Fake Text] =
[ BC.ean8,
BC.ean13,
BC.upcA,
BC.upcE,
BC.compositeSymbol,
BC.isbn,
BC.ismn,
BC.issn
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Beer" $ do
let functions :: [Fake Text] =
[BE.name, BE.brand, BE.hop, BE.yeast, BE.malt, BE.style]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Blood" $ do
let functions :: [Fake Text] = [BL.type', BL.rhFactor, BL.group]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Book.CultureSeries" $ do
let functions :: [Fake Text] =
[ CE.books,
CE.cultureShips,
CE.cultureShipClasses,
CE.cultureShipClassAbvs,
CE.civs,
CE.planets
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Book.Dune" $ do
let functions :: [Fake Text] =
[ DU.characters,
DU.titles,
DU.planets,
DU.quotesGuildNavigator,
DU.quotesEmperor,
DU.quotesPaul,
DU.quotesThufir,
DU.quotesJessica,
DU.quotesIrulan,
DU.quotesMohiam,
DU.quotesGurney,
DU.quotesLeto,
DU.quotesStilgar,
DU.quotesLietKynes,
DU.quotesPardotKynes,
DU.quotesBaronHarkonnen,
DU.quotesPiter,
DU.quotesAlia,
DU.quotesMapes,
DU.quotesDuncan,
DU.quotesYueh,
DU.sayingsBeneGesserit,
DU.sayingsFremen,
DU.sayingsMentat,
DU.sayingsMuaddib,
DU.sayingsOrangeCatholicBible,
DU.cities
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Book.LoveCraft" $ do
let functions :: [Fake Text] =
[LO.fhtagn, LO.deity, LO.location, LO.tome, LO.words]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Book" $ do
let functions :: [Fake Text] =
[BO.author, BO.title, BO.publisher, BO.genre]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "BossaNova" $ do
let functions :: [Fake Text] = [BO.artists, BO.songs]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Business" $ do
let functions :: [Fake Text] = [BU.creditCardNumbers, BU.creditCardTypes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Cannabis" $ do
let functions :: [Fake Text] =
[ CA.strains,
CA.cannabinoidAbbreviations,
CA.cannabinoids,
CA.terpenes,
CA.medicalUses,
CA.healthBenefits,
CA.categories,
CA.types,
CA.buzzwords,
CA.brands
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "ChuckNorris" $ do
let functions :: [Fake Text] = [CH.fact]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "RajniKanth" $ do
let functions :: [Fake Text] = [RK.joke]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Show" $ do
let functions :: [Fake Text] = [WS.adultMusical]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Chiquito" $ do
let functions :: [Fake Text] =
[CI.expressions, CI.terms, CI.sentences, CI.jokes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Code" $ do
let functions :: [Fake Text] = [CO.asin]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "DnD" $ do
let functions :: [Fake Text] =
[ DN.klasses,
DN.alignments,
DN.cities,
DN.languages,
DN.meleeWeapons,
DN.monsters,
DN.races,
DN.rangedWeapons
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Coffee" $ do
let functions :: [Fake Text] =
[ CO.country,
CO.variety,
CO.intensifier,
CO.body,
CO.descriptor,
CO.name1,
CO.name2,
CO.notes,
CO.blendName,
CO.regionsColombia,
CO.regionsBrazil,
CO.regionsSumatra,
CO.regionsEthiopia,
CO.regionsHonduras,
CO.regionsKenya,
CO.regionsUganda,
CO.regionsMexico,
CO.regionsGuatemala,
CO.regionsNicaragua,
CO.regionsCostaRica,
CO.regionsTanzania,
CO.regionsElSalvador,
CO.regionsRwanda,
CO.regionsBurundi,
CO.regionsPanama,
CO.regionsYemen,
CO.regionsIndia
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Coin" $ do
let functions :: [Fake Text] = [CO.flip]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Color" $ do
let functions :: [Fake Text] = [CO.name]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Computer" $ do
let functions :: [Fake Text] =
[COM.type', COM.platform, COM.osLinux, COM.osMacos, COM.osWindows]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Commerce" $ do
let functions :: [Fake Text] =
[ CO.department,
CO.productNameAdjective,
CO.productNameMaterial,
CO.productNameProduct,
CO.promotionCodeAdjective,
CO.promotionCodeNoun
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Company" $ do
let functions :: [Fake Text] =
[ CM.suffix,
CM.buzzword,
CM.bs,
CM.name,
CM.industry,
CM.profession,
CM.type',
CM.sicCode,
CM.buzzword,
CM.bs
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
describe "Company" $
it "generated verify fake functions" $ do
let functions :: [Fake Text] =
[ CO.direction
, CO.abbreviation
, CO.azimuth
, CO.cardinalWord
, CO.cardinalAbbreviation
, CO.cardinalAzimuth
, CO.ordinalWord
, CO.ordinalAbbreviation
, CO.ordinalAzimuth
, CO.halfWindWord
, CO.halfWindAbbreviation
, CO.halfWindAzimuth
, CO.quarterWindWord
, CO.quarterWindAbbreviation
, CO.quarterWindAzimuth
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
describe "Company domain" $
it "forall domain fullfils is a domain name regex" $ Q.property $ Q.forAll (fakeQuickcheck CM.domain) isDomain
describe "Company email" $
it "forall email fullfils is an email regex" $ Q.property $ Q.forAll (fakeQuickcheck CM.email) isEmail
it "Construction" $ do
let functions :: [Fake Text] =
[ CO.materials,
CO.subcontractCategories,
CO.heavyEquipment,
CO.roles,
CO.trades,
CO.standardCostCodes
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Cosmere" $ do
let functions :: [Fake Text] =
[ CO.aons,
CO.shardWorlds,
CO.shards,
CO.surges,
CO.knightsRadiant,
CO.metals,
CO.allomancers,
CO.feruchemists,
CO.heralds,
CO.sprens
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Creature.Animal" $ do
let functions :: [Fake Text] = [AN.name]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Creature.Cat" $ do
let functions :: [Fake Text] = [CA.name, CA.breed, CA.registry]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Game.Control" $ do
let functions :: [Fake Text] =
[ GC.character,
GC.location,
GC.objectOfPower,
GC.alteredItem,
GC.alteredWorldEvent,
GC.hiss,
GC.theBoard,
GC.quote
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Creature.Dog" $ do
let functions :: [Fake Text] =
[ DO.name,
DO.breed,
DO.sound,
DO.memePhrase,
DO.age,
DO.coatLength,
DO.size
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Creature.Horuse" $ do
let functions :: [Fake Text] = [HO.name, HO.breed]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Cryptocoin" $ do
let functions :: [Fake Text] = [CO.coin]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Currency" $ do
let functions :: [Fake Text] = [CU.name, CU.code, CU.symbol]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "DcComics" $ do
let functions :: [Fake Text] =
[DC.hero, DC.heroine, DC.villain, DC.name, DC.title]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Drone" $ do
let functions :: [Fake Text] =
[ DX.name,
DX.batteryType,
DX.iso,
DX.photoFormat,
DX.videoFormat,
DX.maxShutterSpeed,
DX.minShutterSpeed,
DX.shutterSpeedUnits,
DX.weight,
DX.maxAscentSpeed,
DX.maxDescentSpeed,
DX.flightTime,
DX.maxAltitude,
DX.maxFlightDistance,
DX.maxSpeed,
DX.maxWindResistance,
DX.maxAngularVelocity,
DX.maxTiltAngle,
DX.operatingTemperature,
DX.batteryCapacity,
DX.batteryVoltage,
DX.batteryWeight,
DX.chargingTemperature,
DX.maxChargingPower,
DX.maxResolution
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "DrivingLicense" $ do
let functions :: [Fake Text] =
[ DR.usaAlabama,
DR.usaAlaska,
DR.usaArizona,
DR.usaArkansas,
DR.usaCalifornia,
DR.usaColorado,
DR.usaConnecticut,
DR.usaDelaware,
DR.usaDistrictOfColumbia,
DR.usaFlorida,
DR.usaGeorgia,
DR.usaHawaii,
DR.usaIdaho,
DR.usaIllinois,
DR.usaIndiana,
DR.usaIowa,
DR.usaKansas,
DR.usaKentucky,
DR.usaLouisiana,
DR.usaMaine,
DR.usaMaryland,
DR.usaMassachusetts,
DR.usaMichigan,
DR.usaMinnesota,
DR.usaMississippi,
DR.usaMissouri,
DR.usaMontana,
DR.usaNebraska,
DR.usaNevada,
DR.usaNewHampshire,
DR.usaNewJersey,
DR.usaNewMexico,
DR.usaNewYork,
DR.usaNorthCarolina,
DR.usaOhio,
DR.usaOklahoma,
DR.usaOregon,
DR.usaPennsylvania,
DR.usaRhodeIsland,
DR.usaSouthCarolina,
DR.usaSouthDakota,
DR.usaTennessee,
DR.usaTexas,
DR.usaUtah,
DR.usaVermont,
DR.usaVirginia,
DR.usaWashington,
DR.usaWestVirginia,
DR.usaWisconsin,
DR.usaWyoming,
DR.usaNorthDakota
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Demographic" $ do
let functions :: [Fake Text] =
[ DE.race,
DE.sex,
DE.demonym,
DE.educationalAttainment,
DE.maritalStatus
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Dessert" $ do
let functions :: [Fake Text] = [DE.variety, DE.topping, DE.flavor]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Educator" $ do
let functions :: [Fake Text] =
[ ED.schoolName,
ED.secondary,
ED.university,
ED.secondarySchool,
ED.campus,
ED.subject,
ED.degree,
ED.courseName,
ED.tertiaryUniversityType,
ED.tertiaryDegreeType,
ED.tertiaryDegreeCourseNumber,
ED.primary,
ED.primarySchool
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "ElectricalComponents" $ do
let functions :: [Fake Text] =
[EC.active, EC.passive, EC.electromechanical]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Esport" $ do
let functions :: [Fake Text] =
[ES.players, ES.teams, ES.events, ES.leagues, ES.games]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "File" $ do
let functions :: [Fake Text] = [FI.extension, FI.mimeType]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Finance" $ do
let functions :: [Fake Text] =
[ FI.visa,
FI.mastercard,
FI.discover,
FI.dinersClub,
FI.jcb,
FI.switch,
FI.solo,
FI.dankort,
FI.maestro,
FI.forbrugsforeningen,
FI.laser
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Food" $ do
let functions :: [Fake Text] =
[ FO.dish,
FO.descriptions,
FO.ingredients,
FO.fruits,
FO.vegetables,
FO.spices,
FO.measurements,
FO.measurementSizes,
FO.metricMeasurements,
FO.sushi
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "FunnyName" $ do
let functions :: [Fake Text] = [FU.name]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.Futurama" $ do
let functions :: [Fake Text] =
[ FT.characters,
FT.locations,
FT.quotes,
FT.hermesCatchphrases
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Game.Dota" $ do
let functions :: [Fake Text] =
[ DO.hero,
DO.item,
DO.team,
DO.player,
DO.abaddonQuote,
DO.alchemistQuote,
DO.axeQuote,
DO.beastmasterQuote,
DO.brewmasterQuote,
DO.bristlebackQuote,
DO.centaurQuote,
DO.chaosKnightQuote,
DO.clockwerkQuote,
DO.doomQuote,
DO.dragonKnightQuote,
DO.earthSpiritQuote,
DO.earthshakerQuote,
DO.elderTitanQuote,
DO.huskarQuote,
DO.ioQuote,
DO.kunkkaQuote,
DO.legionCommanderQuote,
DO.lifestealerQuote,
DO.lycanQuote,
DO.magnusQuote,
DO.nightStalkerQuote,
DO.omniknightQuote,
DO.phoenixQuote,
DO.pudgeQuote,
DO.sandKingQuote,
DO.slardarQuote,
DO.spiritBreakerQuote,
DO.svenQuote,
DO.tidehunterQuote,
DO.timbersawQuote,
DO.tinyQuote,
DO.tuskQuote,
DO.underlordQuote,
DO.undyingQuote,
DO.wraithKingQuote,
DO.meepoQuote
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Game.ElderScrolls" $ do
let functions :: [Fake Text] =
[ EL.race,
EL.creature,
EL.region,
EL.dragon,
EL.city,
EL.firstName,
EL.lastName
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Game.Fallout" $ do
let functions :: [Fake Text] =
[FA.characters, FA.factions, FA.locations, FA.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Game.HalfLife" $ do
let functions :: [Fake Text] = [HA.character, HA.enemy, HA.location]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Game.Heroes" $ do
let functions :: [Fake Text] = [HE.names, HE.specialties, HE.klasses]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Game.HeroesOfTheStorm" $ do
let functions :: [Fake Text] =
[ HS.battlegrounds,
HS.classNames,
HS.heroes,
HS.quotes
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Game.Myst" $ do
let functions :: [Fake Text] =
[MY.games, MY.creatures, MY.characters, MY.ages, MY.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Game.Overwatch" $ do
let functions :: [Fake Text] = [OV.heroes, OV.locations, OV.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Game.WarhammerFantasy" $ do
let functions :: [Fake Text] =
[ WF.creatures,
WF.factions,
WF.factions,
WF.locations,
WF.quotes,
WF.heros
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Game.Pokemon" $ do
let functions :: [Fake Text] = [PO.names, PO.locations, PO.moves]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Game.SonicTheHedgehog" $ do
let functions :: [Fake Text] = [SO.zone, SO.character, SO.game]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Game.SonicTheHedgehog" $ do
let functions :: [Fake Text] = [SO.zone, SO.character, SO.game]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Game.SuperSmashBros" $ do
let functions :: [Fake Text] = [SU.fighter, SU.stage]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Game.Witcher" $ do
let functions :: [Fake Text] =
[ WI.characters,
WI.witchers,
WI.schools,
WI.locations,
WI.quotes,
WI.monsters,
WI.signs,
WI.potions,
WI.books
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Game.WorldOfwarcraft" $ do
let functions :: [Fake Text] = [
WO.heros
, WO.quotes
, WO.classNames
, WO.races
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Game.Zelda" $ do
let functions :: [Fake Text] =
[ZE.games, ZE.characters, ZE.locations, ZE.items]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Game.Minecraft" $ do
let functions :: [Fake Text] =
[ MC.blocks,
MC.items,
MC.mobs
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Game.StreetFighter" $ do
let functions :: [Fake Text] =
[ SF.characters,
SF.stages,
SF.quotes,
SF.moves
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Gender" $ do
let functions :: [Fake Text] =
[GE.types, GE.binaryTypes, GE.shortBinaryTypes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "GreekPhilosophers" $ do
let functions :: [Fake Text] = [GR.names, GR.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Hacker" $ do
let functions :: [Fake Text] =
[HA.abbreviation, HA.adjective, HA.noun, HA.verb, HA.ingverb]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Hipster" $ do
let functions :: [Fake Text] = [HI.words]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "House" $ do
let functions :: [Fake Text] = [HO.furniture, HO.rooms]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Industry" $ do
let functions :: [Fake Text] =
[IN.industry, IN.superSector, IN.sector, IN.subSector]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Internet" $ do
let functions :: [Fake Text] =
[ IN.freeEmail,
IN.domainSuffix,
IN.userAgentAol,
IN.userAgentChrome,
IN.userAgentFirefox,
IN.userAgentInternetExplorer,
IN.userAgentNetscape,
IN.userAgentOpera,
IN.userAgentSafari
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "JapaneseMedia.DragonBall" $ do
let functions :: [Fake Text] = [DR.characters, DR.races, DR.planets]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "JapaneseMedia.OnePiece" $ do
let functions :: [Fake Text] =
[ ON.characters,
ON.seas,
ON.islands,
ON.locations,
ON.quotes,
ON.akumasNoMi
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "JapaneseMedia.SwordArtOnline" $ do
let functions :: [Fake Text] =
[SW.realName, SW.gameName, SW.location, SW.item]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "JapaneseMedia.StudioGhibli" $ do
let functions :: [Fake Text] =
[ GI.characters,
GI.quotes,
GI.movies
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Job" $ do
let functions :: [Fake Text] =
[ JO.field,
JO.seniority,
JO.position,
JO.keySkills,
JO.employmentType,
JO.educationLevel,
JO.title
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Kpop" $ do
let functions :: [Fake Text] =
[ KP.iGroups,
KP.iiGroups,
KP.iiiGroups,
KP.girlGroups,
KP.boyBands,
KP.solo
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "LeagueOfLegends" $ do
let functions :: [Fake Text] =
[ LE.champion,
LE.location,
LE.quote,
LE.summonerSpell,
LE.masteries,
LE.rank
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Lorem" $ do
let functions :: [Fake Text] = [LM.words, LM.supplemental]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Markdown" $ do
let functions :: [Fake Text] = [MA.headers, MA.emphasis]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Marketing" $ do
let functions :: [Fake Text] = [MA.buzzwords]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Measurement" $ do
let functions :: [Fake Text] =
[ ME.height,
ME.length,
ME.volume,
ME.weight,
ME.metricHeight,
ME.metricLength,
ME.metricVolume,
ME.metricWeight
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Military" $ do
let functions :: [Fake Text] =
[ MI.armyRank,
MI.marinesRank,
MI.navyRank,
MI.airForceRank,
MI.dodPaygrade,
MI.coastGuardRank,
MI.spaceForceRank
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Movie.Departed" $ do
let functions :: [Fake Text] = [MD.actors, MD.characters, MD.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Movie.BackToTheFuture" $ do
let functions :: [Fake Text] = [BA.dates, BA.characters, BA.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Movie.Ghostbusters" $ do
let functions :: [Fake Text] = [GH.actors, GH.characters, GH.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Movie.GratefulDead" $ do
let functions :: [Fake Text] = [GR.players, GR.songs]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Movie.HarryPotter" $ do
let functions :: [Fake Text] =
[ HA.characters,
HA.locations,
HA.quotes,
HA.books,
HA.houses,
HA.spells
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Movie.HitchhikersGuideToTheGalaxy" $ do
let functions :: [Fake Text] =
[ HI.characters,
HI.locations,
HI.marvinQuote,
HI.planets,
HI.quotes,
HI.species,
HI.starships
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Movie.Lebowski" $ do
let functions :: [Fake Text] = [LE.actors, LE.characters, LE.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Movie.PrincessBride" $ do
let functions :: [Fake Text] = [PR.characters, PR.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Movie.StarWars" $ do
let functions :: [Fake Text] =
[ ST.characters,
ST.callSquadrons,
ST.droids,
ST.planets,
ST.species,
ST.vehicles,
ST.wookieeWords,
ST.callNumbers,
ST.callSign,
ST.quotesAdmiralAckbar,
ST.quotesAhsokaTano,
ST.quotesAsajjVentress,
ST.quotesBendu,
ST.quotesBobaFett,
ST.quotesC3po,
ST.quotesCountDooku,
ST.quotesDarthCaedus,
ST.quotesDarthVader,
ST.quotesEmperorPalpatine,
ST.quotesFinn,
ST.quotesGrandAdmiralThrawn,
ST.quotesGrandMoffTarkin,
ST.quotesGreedo,
ST.quotesHanSolo,
ST.quotesJabbaTheHutt,
ST.quotesJarJarBinks,
ST.quotesK2so,
ST.quotesKyloRen,
ST.quotesLandoCalrissian,
ST.quotesLeiaOrgana,
ST.quotesLukeSkywalker,
ST.quotesMaceWindu,
ST.quotesMazKanata,
ST.quotesObiWanKenobi,
ST.quotesPadmeAmidala,
ST.quotesQuiGonJinn,
ST.quotesRey,
ST.quotesShmiSkywalker,
ST.quotesYoda,
ST.alternateCharacterSpellingsAdmiralAckbar,
ST.alternateCharacterSpellingsAhsokaTano,
ST.alternateCharacterSpellingsAnakinSkywalker,
ST.alternateCharacterSpellingsAsajjVentress,
ST.alternateCharacterSpellingsBendu,
ST.alternateCharacterSpellingsBobaFett,
ST.alternateCharacterSpellingsC3po,
ST.alternateCharacterSpellingsCountDooku,
ST.alternateCharacterSpellingsDarthCaedus,
ST.alternateCharacterSpellingsDarthVader,
ST.alternateCharacterSpellingsEmperorPalpatine,
ST.alternateCharacterSpellingsFinn,
ST.alternateCharacterSpellingsGeneralHux,
ST.alternateCharacterSpellingsGrandAdmiralThrawn,
ST.alternateCharacterSpellingsGrandMoffTarkin,
ST.alternateCharacterSpellingsGreedo,
ST.alternateCharacterSpellingsHanSolo,
ST.alternateCharacterSpellingsJabbaTheHutt,
ST.alternateCharacterSpellingsJarJarBinks,
ST.alternateCharacterSpellingsK2so,
ST.alternateCharacterSpellingsKyloRen,
ST.alternateCharacterSpellingsLandoCalrissian,
ST.alternateCharacterSpellingsLeiaOrgana,
ST.alternateCharacterSpellingsLukeSkywalker,
ST.alternateCharacterSpellingsMaceWindu,
ST.alternateCharacterSpellingsMazKanata,
ST.alternateCharacterSpellingsObiWanKenobi,
ST.alternateCharacterSpellingsPadmeAmidala,
ST.alternateCharacterSpellingsQuiGonJinn,
ST.alternateCharacterSpellingsRey,
ST.alternateCharacterSpellingsShmiSkywalker,
ST.alternateCharacterSpellingsYoda
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Movie.VForVendetta" $ do
let functions :: [Fake Text] = [VF.characters, VF.speeches, VF.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Movie" $ do
let functions :: [Fake Text] = [MO.quote, MO.title]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Music.Opera" $ do
let functions :: [Fake Text] =
[ OP.italianByGiuseppeVerdi,
OP.italianByGioacchinoRossini,
OP.italianByGaetanoDonizetti,
OP.italianByVincenzoBellini,
OP.italianByChristophWillibaldGluck,
OP.italianByWolfgangAmadeusMozart,
OP.germanByWolfgangAmadeusMozart,
OP.germanByLudwigVanBeethoven,
OP.germanByCarlMariaVonWeber,
OP.germanByRichardStrauss,
OP.germanByRichardWagner,
OP.germanByRobertSchumann,
OP.germanByFranzSchubert,
OP.germanByAlbanBerg,
OP.frenchByChristophWillibaldGluck,
OP.frenchByMauriceRavel,
OP.frenchByHectorBerlioz,
OP.frenchByGeorgesBizet,
OP.frenchByCharlesGounod,
OP.frenchByCamilleSaintSaëns
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Music.PearlJam" $ do
let functions :: [Fake Text] =
[ OP.italianByGiuseppeVerdi,
OP.italianByGioacchinoRossini,
OP.italianByGaetanoDonizetti,
OP.italianByVincenzoBellini
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Music.Phish" $ do
let functions :: [Fake Text] = [PH.songs, PH.musicians, PH.albums]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Music.RockBand" $ do
let functions :: [Fake Text] = [RO.name, RO.song]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Music.UmphreysMcgee" $ do
let functions :: [Fake Text] = [UM.song]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Music.Prince" $ do
let functions :: [Fake Text] =
[ PC.lyric,
PC.song,
PC.album,
PC.band
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Music.Rush" $ do
let functions :: [Fake Text] =
[ RU.players,
RU.albums
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Music" $ do
let functions :: [Fake Text] =
[MU.instruments, MU.bands, MU.albums, MU.genres, MU.mamboNo5, MU.hiphopSubgenres
, MU.hiphopGroups
, MU.hiphopArtist]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Name" $ do
let functions :: [Fake Text] =
[ NA.maleFirstName,
NA.femaleFirstName,
NA.prefix,
NA.suffix,
NA.lastName,
NA.name,
NA.nameWithMiddle,
NA.firstName
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Nation" $ do
let functions :: [Fake Text] =
[NA.nationality, NA.language, NA.capitalCity, NA.flagEmoji]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "NatoPhoneticAlphabet" $ do
let functions :: [Fake Text] = [NA.codeWord]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "PhoneNumber" $ do
let functions :: [Fake Text] =
[PH.formats, PH.countryCode, PH.cellPhoneFormat]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "ProgrammingLanguage" $ do
let functions :: [Fake Text] = [PR.name, PR.creator]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Quote.Shakespeare" $ do
let functions :: [Fake Text] =
[SH.hamlet, SH.asYouLikeIt, SH.kingRichardIii, SH.romeoAndJuliet]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Quote" $ do
let functions :: [Fake Text] =
[ QU.famousLastWords,
QU.matz,
QU.mostInterestingManInTheWorld,
QU.robin,
QU.singularSiegler,
QU.yoda,
QU.fortuneCookie
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Relationship" $ do
let functions :: [Fake Text] =
[ RE.inLaw,
RE.spouse,
RE.parent,
RE.sibling,
RE.familialDirect,
RE.familialExtended
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Restaurant" $ do
let functions :: [Fake Text] =
[ RE.nameSuffix,
RE.type',
RE.description,
RE.review,
RE.namePrefix,
RE.name
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Science" $ do
let functions :: [Fake Text] =
[SC.element, SC.elementSymbol, SC.scientist
, SC.elementState, SC.elementSubcategory]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "SlackEmoji" $ do
let functions :: [Fake Text] =
[ SL.people,
SL.nature,
SL.foodAndDrink,
SL.celebration,
SL.activity,
SL.travelAndPlaces,
SL.objectsAndSymbols,
SL.custom,
SL.emoji
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Source" $ do
let functions :: [Fake Text] =
[ SO.helloWorldRuby,
SO.helloWorldJavascript,
SO.printRuby,
SO.printJavascript,
SO.print1To10Ruby,
SO.print1To10Javascript
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Space" $ do
let functions :: [Fake Text] =
[ SP.planet,
SP.moon,
SP.galaxy,
SP.nebula,
SP.starCluster,
SP.constellation,
SP.star,
SP.agency,
SP.agencyAbv,
SP.nasaSpaceCraft,
SP.company,
SP.distanceMeasurement,
SP.meteorite,
SP.launchVehicle
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Sport.Basketball" $ do
let functions :: [Fake Text] =
[BA.teams, BA.players, BA.coaches, BA.positions]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Sport.Football" $ do
let functions :: [Fake Text] =
[FO.teams, FO.players, FO.coaches, FO.competitions, FO.positions]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Subscription" $ do
let functions :: [Fake Text] =
[ SU.plans,
SU.statuses,
SU.paymentMethods,
SU.subscriptionTerms,
SU.paymentTerms
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Superhero" $ do
let functions :: [Fake Text] =
[SU.power, SU.prefix, SU.suffix, SU.descriptor, SU.name]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Team" $ do
let functions :: [Fake Text] = [TE.creature, TE.sport, TE.mascot, TE.name]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "University" $ do
let functions :: [Fake Text] = [UN.prefix, UN.suffix, UN.name]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Vehicle" $ do
let functions :: [Fake Text] =
[ VE.manufacture,
VE.makes,
VE.colors,
VE.transmissions,
VE.driveTypes,
VE.fuelTypes,
VE.styles,
VE.carTypes,
VE.carOptions,
VE.standardSpecs,
VE.licensePlate,
VE.modelsByMakeBMW,
VE.modelsByMakeAudi,
VE.modelsByMakeToyota,
VE.modelsByMakeChevy,
VE.modelsByMakeFord,
VE.modelsByMakeDodge,
VE.modelsByMakeLincoln,
VE.modelsByMakeBuick,
VE.modelsByMakeHonda,
VE.modelsByMakeNissan
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
let ifunctions :: [Fake Int] = [VE.doors, VE.engineSizes]
bools <- verifyFakeInt ifunctions
(and bools) `shouldBe` True
it "Verbs" $ do
let functions :: [Fake Text] =
[VE.base, VE.past, VE.pastParticiple, VE.simplePresent, VE.ingForm]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "WorldCup" $ do
let functions :: [Fake Text] =
[ WO.teams,
WO.stadiums,
WO.cities,
WO.groupsGroupA,
WO.groupsGroupB,
WO.groupsGroupC,
WO.groupsGroupD,
WO.groupsGroupE,
WO.groupsGroupF,
WO.groupsGroupG,
WO.groupsGroupH,
WO.rostersEgyptCoach,
WO.rostersEgyptGoalkeepers,
WO.rostersEgyptDefenders,
WO.rostersEgyptMidfielders,
WO.rostersEgyptForwards,
WO.rostersRussiaCoach,
WO.rostersRussiaGoalkeepers,
WO.rostersRussiaDefenders,
WO.rostersRussiaMidfielders,
WO.rostersRussiaForwards,
WO.rostersSaudiArabiaCoach,
WO.rostersSaudiArabiaGoalkeepers,
WO.rostersSaudiArabiaDefenders,
WO.rostersSaudiArabiaMidfielders,
WO.rostersSaudiArabiaForwards,
WO.rostersUruguayCoach,
WO.rostersUruguayGoalkeepers,
WO.rostersUruguayDefenders,
WO.rostersUruguayMidfielders,
WO.rostersUruguayForwards,
WO.rostersIranCoach,
WO.rostersIranGoalkeepers,
WO.rostersIranDefenders,
WO.rostersIranMidfielders,
WO.rostersIranForwards,
WO.rostersMoroccoCoach,
WO.rostersMoroccoGoalkeepers,
WO.rostersMoroccoDefenders,
WO.rostersMoroccoMidfielders,
WO.rostersMoroccoForwards,
WO.rostersPortugalCoach,
WO.rostersPortugalGoalkeepers,
WO.rostersPortugalDefenders,
WO.rostersPortugalMidfielders,
WO.rostersPortugalForwards,
WO.rostersSpainCoach,
WO.rostersSpainGoalkeepers,
WO.rostersSpainDefenders,
WO.rostersSpainMidfielders,
WO.rostersSpainForwards,
WO.rostersAustraliaCoach,
WO.rostersAustraliaGoalkeepers,
WO.rostersAustraliaDefenders,
WO.rostersAustraliaMidfielders,
WO.rostersAustraliaForwards,
WO.rostersDenmarkCoach,
WO.rostersDenmarkGoalkeepers,
WO.rostersDenmarkDefenders,
WO.rostersDenmarkMidfielders,
WO.rostersDenmarkForwards,
WO.rostersFranceCoach,
WO.rostersFranceGoalkeepers,
WO.rostersFranceDefenders,
WO.rostersFranceMidfielders,
WO.rostersFranceForwards,
WO.rostersPeruCoach,
WO.rostersPeruGoalkeepers,
WO.rostersPeruDefenders,
WO.rostersPeruMidfielders,
WO.rostersPeruForwards,
WO.rostersArgentinaCoach,
WO.rostersArgentinaGoalkeepers,
WO.rostersArgentinaDefenders,
WO.rostersArgentinaMidfielders,
WO.rostersArgentinaForwards,
WO.rostersCroatiaCoach,
WO.rostersCroatiaGoalkeepers,
WO.rostersCroatiaDefenders,
WO.rostersCroatiaMidfielders,
WO.rostersCroatiaForwards,
WO.rostersIcelandCoach,
WO.rostersIcelandGoalkeepers,
WO.rostersIcelandDefenders,
WO.rostersIcelandMidfielders,
WO.rostersIcelandForwards,
WO.rostersNigeriaCoach,
WO.rostersNigeriaGoalkeepers,
WO.rostersNigeriaDefenders,
WO.rostersNigeriaMidfielders,
WO.rostersNigeriaForwards,
WO.rostersBrazilCoach,
WO.rostersBrazilGoalkeepers,
WO.rostersBrazilDefenders,
WO.rostersBrazilMidfielders,
WO.rostersBrazilForwards,
WO.rostersCostaRicaCoach,
WO.rostersCostaRicaGoalkeepers,
WO.rostersCostaRicaDefenders,
WO.rostersCostaRicaMidfielders,
WO.rostersCostaRicaForwards,
WO.rostersSerbiaCoach,
WO.rostersSerbiaGoalkeepers,
WO.rostersSerbiaDefenders,
WO.rostersSerbiaMidfielders,
WO.rostersSerbiaForwards,
WO.rostersSwitzerlandCoach,
WO.rostersSwitzerlandGoalkeepers,
WO.rostersSwitzerlandDefenders,
WO.rostersSwitzerlandMidfielders,
WO.rostersSwitzerlandForwards,
WO.rostersGermanyCoach,
WO.rostersGermanyGoalkeepers,
WO.rostersGermanyDefenders,
WO.rostersGermanyMidfielders,
WO.rostersGermanyForwards,
WO.rostersMexicoCoach,
WO.rostersMexicoGoalkeepers,
WO.rostersMexicoDefenders,
WO.rostersMexicoMidfielders,
WO.rostersMexicoForwards,
WO.rostersSouthKoreaCoach,
WO.rostersSouthKoreaGoalkeepers,
WO.rostersSouthKoreaDefenders,
WO.rostersSouthKoreaMidfielders,
WO.rostersSouthKoreaForwards,
WO.rostersSwedenCoach,
WO.rostersSwedenGoalkeepers,
WO.rostersSwedenDefenders,
WO.rostersSwedenMidfielders,
WO.rostersSwedenForwards,
WO.rostersBelgiumCoach,
WO.rostersBelgiumGoalkeepers,
WO.rostersBelgiumDefenders,
WO.rostersBelgiumMidfielders,
WO.rostersBelgiumForwards,
WO.rostersEnglandCoach,
WO.rostersEnglandGoalkeepers,
WO.rostersEnglandDefenders,
WO.rostersEnglandMidfielders,
WO.rostersEnglandForwards,
WO.rostersPanamaCoach,
WO.rostersPanamaGoalkeepers,
WO.rostersPanamaDefenders,
WO.rostersPanamaMidfielders,
WO.rostersPanamaForwards,
WO.rostersTunisiaCoach,
WO.rostersTunisiaGoalkeepers,
WO.rostersTunisiaDefenders,
WO.rostersTunisiaMidfielders,
WO.rostersTunisiaForwards,
WO.rostersColumbiaCoach,
WO.rostersColumbiaGoalkeepers,
WO.rostersColumbiaDefenders,
WO.rostersColumbiaMidfielders,
WO.rostersColumbiaForwards,
WO.rostersJapanCoach,
WO.rostersJapanGoalkeepers,
WO.rostersJapanDefenders,
WO.rostersJapanMidfielders,
WO.rostersJapanForwards,
WO.rostersPolandCoach,
WO.rostersPolandGoalkeepers,
WO.rostersPolandDefenders,
WO.rostersPolandMidfielders,
WO.rostersPolandForwards,
WO.rostersSenegalCoach,
WO.rostersSenegalGoalkeepers,
WO.rostersSenegalDefenders,
WO.rostersSenegalMidfielders,
WO.rostersSenegalForwards
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Yoda" $ do
let functions :: [Fake Text] = [YO.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.AquaTeenHungerForce" $ do
let functions :: [Fake Text] = [AQ.character, AQ.quote]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.BigBangTheory" $ do
let functions :: [Fake Text] = [BB.characters, BB.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.Suits" $ do
let functions :: [Fake Text] = [SU.characters, SU.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.BoJackHorseman" $ do
let functions :: [Fake Text] = [BO.character, BO.quote, BO.tongueTwister]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.BreakingBad" $ do
let functions :: [Fake Text] = [BR.character, BR.episode]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.Buffy" $ do
let functions :: [Fake Text] =
[BU.characters, BU.quotes, BU.actors, BU.bigBads, BU.episodes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.Community" $ do
let functions :: [Fake Text] = [CO.characters, CO.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.DrWho" $ do
let functions :: [Fake Text] =
[ DR.character,
DR.theDoctors,
DR.actors,
DR.catchPhrases,
DR.quotes,
DR.villains,
DR.species
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.DumbAndDumber" $ do
let functions :: [Fake Text] = [DD.actors, DD.characters, DD.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.FamilyGuy" $ do
let functions :: [Fake Text] = [FA.character, FA.location, FA.quote]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.FreshPrinceOfBelAir" $ do
let functions :: [Fake Text] = [FR.characters, FR.actors, FR.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.Friends" $ do
let functions :: [Fake Text] = [FI.characters, FI.locations, FI.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.Friends" $ do
let functions :: [Fake Text] = [FI.characters, FI.locations, FI.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.GameOfThrones" $ do
let functions :: [Fake Text] =
[GA.characters, GA.houses, GA.cities, GA.quotes, GA.dragons]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.HeyArnold" $ do
let functions :: [Fake Text] = [HE.characters, HE.locations, HE.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.HowIMetYourMother" $ do
let functions :: [Fake Text] =
[HI.character, HI.catchPhrase, HI.highFive, HI.quote]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.MichaelScott" $ do
let functions :: [Fake Text] = [MI.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.NewGirl" $ do
let functions :: [Fake Text] = [NE.characters, NE.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.ParksAndRec" $ do
let functions :: [Fake Text] = [PA.characters, PA.cities]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.RickAndMorty" $ do
let functions :: [Fake Text] = [RI.characters, RI.locations, RI.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.Rupaul" $ do
let functions :: [Fake Text] = [RU.queens, RU.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.Seinfeld" $ do
let functions :: [Fake Text] = [SE.character, SE.quote, SE.business]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.Seinfeld" $ do
let functions :: [Fake Text] = [SE.character, SE.quote, SE.business]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.SiliconValley" $ do
let functions :: [Fake Text] =
[ SI.characters,
SI.companies,
SI.quotes,
SI.apps,
SI.inventions,
SI.mottos,
SI.urls,
SI.email
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.Simpsons" $ do
let functions :: [Fake Text] = [SS.characters, SS.locations, SS.quotes, SS.episodeTitles]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.SouthPark" $ do
let functions :: [Fake Text] = [SO.characters, SO.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.StarTrek" $ do
let functions :: [Fake Text] =
[SR.character, SR.location, SR.specie, SR.villain]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.StarGate" $ do
let functions :: [Fake Text] = [SG.characters, SG.planets, SG.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.StrangerThings" $ do
let functions :: [Fake Text] = [SH.character, SH.quote]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.TheExpanse" $ do
let functions :: [Fake Text] =
[TH.characters, TH.locations, TH.ships, TH.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.TheItCrowd" $ do
let functions :: [Fake Text] =
[TI.actors, TI.characters, TI.emails, TI.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.TheThickOfIt" $ do
let functions :: [Fake Text] =
[TO.characters, TO.positions, TO.departments]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.TwinPeaks" $ do
let functions :: [Fake Text] = [TW.characters, TW.locations, TW.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.VentureBros" $ do
let functions :: [Fake Text] =
[VE.character, VE.organization, VE.vehicle, VE.quote]
bools <- verifyFakes functions
(and bools) `shouldBe` True
| null | https://raw.githubusercontent.com/fakedata-haskell/fakedata/ea938c38845b274e28abe7f4e8e342f491e83c89/test/TextSpec.hs | haskell | copied from -fakedata/blob/d342c6eb5aeb9990bb36ede1d1f08becc7d71e16/src/Hedgehog/Gen/Faker.hs
made it work for quickeck instead of hedgehog.
who needs side affects anyway?
Select a value 'Fake' program in 'Gen'. | # LANGUAGE ScopedTypeVariables #
module TextSpec where
import Data.Text (Text)
import qualified Data.Text as T
import Faker hiding (defaultFakerSettings)
import qualified Faker.Address as FA
import qualified Faker.Ancient as AN
import qualified Faker.App as AP
import qualified Faker.Appliance as AP
import qualified Faker.Artist as AR
import qualified Faker.Bank as BA
import qualified Faker.Barcode as BC
import qualified Faker.Beer as BE
import qualified Faker.Blood as BL
import qualified Faker.Book as BO
import qualified Faker.Book.CultureSeries as CE
import qualified Faker.Book.Dune as DU
import qualified Faker.Book.Lovecraft as LO
import qualified Faker.BossaNova as BO
import qualified Faker.Business as BU
import qualified Faker.Cannabis as CA
import qualified Faker.Chiquito as CI
import qualified Faker.ChuckNorris as CH
import qualified Faker.Code as CO
import qualified Faker.Coffee as CO
import qualified Faker.Coin as CO
import qualified Faker.Color as CO
import qualified Faker.Commerce as CO
import qualified Faker.Company as CM
import qualified Faker.Compass as CO
import qualified Faker.Computer as COM
import qualified Faker.Construction as CO
import qualified Faker.Cosmere as CO
import qualified Faker.Creature.Animal as AN
import qualified Faker.Creature.Cat as CA
import qualified Faker.Creature.Dog as DO
import qualified Faker.Creature.Horse as HO
import qualified Faker.CryptoCoin as CO
import qualified Faker.Currency as CU
import qualified Faker.DcComics as DC
import qualified Faker.Demographic as DE
import qualified Faker.Dessert as DE
import qualified Faker.Dnd as DN
import qualified Faker.DrivingLicense as DR
import qualified Faker.Drone as DX
import qualified Faker.Educator as ED
import qualified Faker.ElectricalComponents as EC
import qualified Faker.Esport as ES
import qualified Faker.File as FI
import qualified Faker.Finance as FI
import qualified Faker.Food as FO
import qualified Faker.FunnyName as FU
import qualified Faker.Game.Control as GC
import qualified Faker.Game.Dota as DO
import qualified Faker.Game.ElderScrolls as EL
import qualified Faker.Game.Fallout as FA
import qualified Faker.Game.HalfLife as HA
import qualified Faker.Game.Heroes as HE
import qualified Faker.Game.HeroesOfTheStorm as HS
import qualified Faker.Game.Minecraft as MC
import qualified Faker.Game.Myst as MY
import qualified Faker.Game.Overwatch as OV
import qualified Faker.Game.Pokemon as PO
import qualified Faker.Game.SonicTheHedgehog as SO
import qualified Faker.Game.StreetFighter as SF
import qualified Faker.Game.SuperSmashBros as SU
import qualified Faker.Game.WarhammerFantasy as WF
import qualified Faker.Game.Witcher as WI
import qualified Faker.Game.WorldOfWarcraft as WO
import qualified Faker.Game.Zelda as ZE
import qualified Faker.Gender as GE
import qualified Faker.GreekPhilosophers as GR
import qualified Faker.Hacker as HA
import qualified Faker.Hipster as HI
import qualified Faker.House as HO
import qualified Faker.IndustrySegments as IN
import qualified Faker.Internet as IN
import qualified Faker.JapaneseMedia.DragonBall as DR
import qualified Faker.JapaneseMedia.OnePiece as ON
import qualified Faker.JapaneseMedia.StudioGhibli as GI
import qualified Faker.JapaneseMedia.SwordArtOnline as SW
import qualified Faker.Job as JO
import qualified Faker.Kpop as KP
import qualified Faker.LeagueOfLegends as LE
import qualified Faker.Lorem as LM
import qualified Faker.Markdown as MA
import qualified Faker.Marketing as MA
import qualified Faker.Measurement as ME
import qualified Faker.Military as MI
import qualified Faker.Movie as MO
import qualified Faker.Movie.BackToTheFuture as BA
import qualified Faker.Movie.Departed as MD
import qualified Faker.Movie.Ghostbusters as GH
import qualified Faker.Movie.GratefulDead as GR
import qualified Faker.Movie.HarryPotter as HA
import qualified Faker.Movie.HitchhikersGuideToTheGalaxy as HI
import qualified Faker.Movie.Lebowski as LE
import qualified Faker.Movie.PrincessBride as PR
import qualified Faker.Movie.StarWars as ST
import qualified Faker.Movie.VForVendetta as VF
import qualified Faker.Music as MU
import qualified Faker.Music.Opera as OP
import qualified Faker.Music.PearlJam as PJ
import qualified Faker.Music.Phish as PH
import qualified Faker.Music.Prince as PC
import qualified Faker.Music.RockBand as RO
import qualified Faker.Music.Rush as RU
import qualified Faker.Music.UmphreysMcgee as UM
import qualified Faker.Name as NA
import qualified Faker.Nation as NA
import qualified Faker.NatoPhoneticAlphabet as NA
import qualified Faker.PhoneNumber as PH
import qualified Faker.ProgrammingLanguage as PR
import qualified Faker.Quote as QU
import qualified Faker.Quote.Shakespeare as SH
import qualified Faker.Rajnikanth as RK
import qualified Faker.Relationship as RE
import qualified Faker.Restaurant as RE
import qualified Faker.Science as SC
import qualified Faker.Show as WS
import qualified Faker.SlackEmoji as SL
import qualified Faker.Source as SO
import qualified Faker.Space as SP
import qualified Faker.Sport.Basketball as BA
import qualified Faker.Sport.Football as FO
import qualified Faker.Subscription as SU
import qualified Faker.Superhero as SU
import qualified Faker.Team as TE
import qualified Faker.TvShow.AquaTeenHungerForce as AQ
import qualified Faker.TvShow.BigBangTheory as BB
import qualified Faker.TvShow.BoJackHorseman as BO
import qualified Faker.TvShow.BreakingBad as BR
import qualified Faker.TvShow.Buffy as BU
import qualified Faker.TvShow.Community as CO
import qualified Faker.TvShow.DrWho as DR
import qualified Faker.TvShow.DumbAndDumber as DD
import qualified Faker.TvShow.FamilyGuy as FA
import qualified Faker.TvShow.FreshPrinceOfBelAir as FR
import qualified Faker.TvShow.Friends as FI
import qualified Faker.TvShow.Futurama as FT
import qualified Faker.TvShow.GameOfThrones as GA
import qualified Faker.TvShow.HeyArnold as HE
import qualified Faker.TvShow.HowIMetYourMother as HI
import qualified Faker.TvShow.MichaelScott as MI
import qualified Faker.TvShow.NewGirl as NE
import qualified Faker.TvShow.ParksAndRec as PA
import qualified Faker.TvShow.RickAndMorty as RI
import qualified Faker.TvShow.Rupaul as RU
import qualified Faker.TvShow.Seinfeld as SE
import qualified Faker.TvShow.SiliconValley as SI
import qualified Faker.TvShow.Simpsons as SS
import qualified Faker.TvShow.SouthPark as SO
import qualified Faker.TvShow.StarTrek as SR
import qualified Faker.TvShow.Stargate as SG
import qualified Faker.TvShow.StrangerThings as SH
import qualified Faker.TvShow.Suits as SU
import qualified Faker.TvShow.TheExpanse as TH
import qualified Faker.TvShow.TheItCrowd as TI
import qualified Faker.TvShow.TheThickOfIt as TO
import qualified Faker.TvShow.TwinPeaks as TW
import qualified Faker.TvShow.VentureBros as VE
import qualified Faker.University as UN
import qualified Faker.Vehicle as VE
import qualified Faker.Verbs as VE
import qualified Faker.WorldCup as WO
import qualified Faker.Yoda as YO
import System.IO.Unsafe (unsafePerformIO)
import qualified Faker
import Faker (Fake)
import System.Random (mkStdGen)
import Text.Regex.TDFA hiding (empty)
import Test.Hspec.QuickCheck(prop)
import qualified Test.QuickCheck as Q
import Test.Hspec
import TestImport
isText :: Text -> Bool
isText x = T.length x >= 1
fakerSettings :: FakerSettings
fakerSettings = defaultFakerSettings
verifyFakes :: [Fake Text] -> IO [Bool]
verifyFakes funs = do
let fs :: [IO Text] = map (generateWithSettings fakerSettings) funs
gs :: [IO Bool] = map (\f -> isText <$> f) fs
sequence gs
verifyFakeInt :: [Fake Int] -> IO [Bool]
verifyFakeInt funs = do
let fs :: [IO Int] = map (generateWithSettings fakerSettings) funs
gs :: [IO Bool] = map (\f -> (\x -> x >= 0) <$> f) fs
sequence gs
I need it for but it 's a cyclic dependency
fakeQuickcheck :: Fake a -> Q.Gen a
fakeQuickcheck f = do
randomGen <- mkStdGen <$> Q.choose (minBound, maxBound)
pure $!
unsafePerformIO $
Faker.generateWithSettings
(Faker.setRandomGen
randomGen
fakerSettings
)
f
isDomain :: Text -> Bool
isDomain = (=~ "^[A-Za-z_]+\\.[a-z]{1,4}$") . T.unpack
isName :: Text -> Bool
isName = (=~ "^[A-Za-z_]+$") . T.unpack
isNum :: Text -> Bool
isNum = (=~ "^[0-9]+$") . T.unpack
isEmail :: Text -> Bool
isEmail input =
if (length splitAt /= 2) || (length splitDash /= 2) then False
else
isDomain domain && isName name && isNum num
where
splitAt = T.splitOn at input
[nameNum, domain] = splitAt
splitDash = T.splitOn dash nameNum
[name, num] = splitDash
dash :: Text
dash = T.pack "-"
at :: Text
at = T.pack "@"
spec :: Spec
spec = do
describe "TextSpec" $ do
it "Address" $ do
let functions :: [Fake Text] =
[ FA.country,
FA.cityPrefix,
FA.citySuffix,
FA.countryCode,
FA.countryCodeLong,
FA.buildingNumber,
FA.communityPrefix,
FA.communitySuffix,
FA.community,
FA.streetSuffix,
FA.secondaryAddress,
FA.postcode,
FA.state,
FA.stateAbbr,
FA.timeZone,
FA.city,
FA.streetName,
FA.streetAddress,
FA.fullAddress,
FA.mailBox,
FA.cityWithState
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Ancient" $ do
let functions :: [Fake Text] = [AN.god, AN.primordial, AN.hero, AN.titan]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "App" $ do
let functions :: [Fake Text] = [AP.name, AP.version]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Appliance" $ do
let functions :: [Fake Text] = [AP.brand, AP.equipment]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Artist" $ do
let functions :: [Fake Text] = [AR.names]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Bank" $ do
let functions :: [Fake Text] = [BA.name, BA.swiftBic]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Barcode" $ do
let functions :: [Fake Text] =
[ BC.ean8,
BC.ean13,
BC.upcA,
BC.upcE,
BC.compositeSymbol,
BC.isbn,
BC.ismn,
BC.issn
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Beer" $ do
let functions :: [Fake Text] =
[BE.name, BE.brand, BE.hop, BE.yeast, BE.malt, BE.style]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Blood" $ do
let functions :: [Fake Text] = [BL.type', BL.rhFactor, BL.group]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Book.CultureSeries" $ do
let functions :: [Fake Text] =
[ CE.books,
CE.cultureShips,
CE.cultureShipClasses,
CE.cultureShipClassAbvs,
CE.civs,
CE.planets
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Book.Dune" $ do
let functions :: [Fake Text] =
[ DU.characters,
DU.titles,
DU.planets,
DU.quotesGuildNavigator,
DU.quotesEmperor,
DU.quotesPaul,
DU.quotesThufir,
DU.quotesJessica,
DU.quotesIrulan,
DU.quotesMohiam,
DU.quotesGurney,
DU.quotesLeto,
DU.quotesStilgar,
DU.quotesLietKynes,
DU.quotesPardotKynes,
DU.quotesBaronHarkonnen,
DU.quotesPiter,
DU.quotesAlia,
DU.quotesMapes,
DU.quotesDuncan,
DU.quotesYueh,
DU.sayingsBeneGesserit,
DU.sayingsFremen,
DU.sayingsMentat,
DU.sayingsMuaddib,
DU.sayingsOrangeCatholicBible,
DU.cities
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Book.LoveCraft" $ do
let functions :: [Fake Text] =
[LO.fhtagn, LO.deity, LO.location, LO.tome, LO.words]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Book" $ do
let functions :: [Fake Text] =
[BO.author, BO.title, BO.publisher, BO.genre]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "BossaNova" $ do
let functions :: [Fake Text] = [BO.artists, BO.songs]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Business" $ do
let functions :: [Fake Text] = [BU.creditCardNumbers, BU.creditCardTypes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Cannabis" $ do
let functions :: [Fake Text] =
[ CA.strains,
CA.cannabinoidAbbreviations,
CA.cannabinoids,
CA.terpenes,
CA.medicalUses,
CA.healthBenefits,
CA.categories,
CA.types,
CA.buzzwords,
CA.brands
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "ChuckNorris" $ do
let functions :: [Fake Text] = [CH.fact]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "RajniKanth" $ do
let functions :: [Fake Text] = [RK.joke]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Show" $ do
let functions :: [Fake Text] = [WS.adultMusical]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Chiquito" $ do
let functions :: [Fake Text] =
[CI.expressions, CI.terms, CI.sentences, CI.jokes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Code" $ do
let functions :: [Fake Text] = [CO.asin]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "DnD" $ do
let functions :: [Fake Text] =
[ DN.klasses,
DN.alignments,
DN.cities,
DN.languages,
DN.meleeWeapons,
DN.monsters,
DN.races,
DN.rangedWeapons
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Coffee" $ do
let functions :: [Fake Text] =
[ CO.country,
CO.variety,
CO.intensifier,
CO.body,
CO.descriptor,
CO.name1,
CO.name2,
CO.notes,
CO.blendName,
CO.regionsColombia,
CO.regionsBrazil,
CO.regionsSumatra,
CO.regionsEthiopia,
CO.regionsHonduras,
CO.regionsKenya,
CO.regionsUganda,
CO.regionsMexico,
CO.regionsGuatemala,
CO.regionsNicaragua,
CO.regionsCostaRica,
CO.regionsTanzania,
CO.regionsElSalvador,
CO.regionsRwanda,
CO.regionsBurundi,
CO.regionsPanama,
CO.regionsYemen,
CO.regionsIndia
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Coin" $ do
let functions :: [Fake Text] = [CO.flip]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Color" $ do
let functions :: [Fake Text] = [CO.name]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Computer" $ do
let functions :: [Fake Text] =
[COM.type', COM.platform, COM.osLinux, COM.osMacos, COM.osWindows]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Commerce" $ do
let functions :: [Fake Text] =
[ CO.department,
CO.productNameAdjective,
CO.productNameMaterial,
CO.productNameProduct,
CO.promotionCodeAdjective,
CO.promotionCodeNoun
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Company" $ do
let functions :: [Fake Text] =
[ CM.suffix,
CM.buzzword,
CM.bs,
CM.name,
CM.industry,
CM.profession,
CM.type',
CM.sicCode,
CM.buzzword,
CM.bs
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
describe "Company" $
it "generated verify fake functions" $ do
let functions :: [Fake Text] =
[ CO.direction
, CO.abbreviation
, CO.azimuth
, CO.cardinalWord
, CO.cardinalAbbreviation
, CO.cardinalAzimuth
, CO.ordinalWord
, CO.ordinalAbbreviation
, CO.ordinalAzimuth
, CO.halfWindWord
, CO.halfWindAbbreviation
, CO.halfWindAzimuth
, CO.quarterWindWord
, CO.quarterWindAbbreviation
, CO.quarterWindAzimuth
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
describe "Company domain" $
it "forall domain fullfils is a domain name regex" $ Q.property $ Q.forAll (fakeQuickcheck CM.domain) isDomain
describe "Company email" $
it "forall email fullfils is an email regex" $ Q.property $ Q.forAll (fakeQuickcheck CM.email) isEmail
it "Construction" $ do
let functions :: [Fake Text] =
[ CO.materials,
CO.subcontractCategories,
CO.heavyEquipment,
CO.roles,
CO.trades,
CO.standardCostCodes
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Cosmere" $ do
let functions :: [Fake Text] =
[ CO.aons,
CO.shardWorlds,
CO.shards,
CO.surges,
CO.knightsRadiant,
CO.metals,
CO.allomancers,
CO.feruchemists,
CO.heralds,
CO.sprens
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Creature.Animal" $ do
let functions :: [Fake Text] = [AN.name]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Creature.Cat" $ do
let functions :: [Fake Text] = [CA.name, CA.breed, CA.registry]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Game.Control" $ do
let functions :: [Fake Text] =
[ GC.character,
GC.location,
GC.objectOfPower,
GC.alteredItem,
GC.alteredWorldEvent,
GC.hiss,
GC.theBoard,
GC.quote
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Creature.Dog" $ do
let functions :: [Fake Text] =
[ DO.name,
DO.breed,
DO.sound,
DO.memePhrase,
DO.age,
DO.coatLength,
DO.size
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Creature.Horuse" $ do
let functions :: [Fake Text] = [HO.name, HO.breed]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Cryptocoin" $ do
let functions :: [Fake Text] = [CO.coin]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Currency" $ do
let functions :: [Fake Text] = [CU.name, CU.code, CU.symbol]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "DcComics" $ do
let functions :: [Fake Text] =
[DC.hero, DC.heroine, DC.villain, DC.name, DC.title]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Drone" $ do
let functions :: [Fake Text] =
[ DX.name,
DX.batteryType,
DX.iso,
DX.photoFormat,
DX.videoFormat,
DX.maxShutterSpeed,
DX.minShutterSpeed,
DX.shutterSpeedUnits,
DX.weight,
DX.maxAscentSpeed,
DX.maxDescentSpeed,
DX.flightTime,
DX.maxAltitude,
DX.maxFlightDistance,
DX.maxSpeed,
DX.maxWindResistance,
DX.maxAngularVelocity,
DX.maxTiltAngle,
DX.operatingTemperature,
DX.batteryCapacity,
DX.batteryVoltage,
DX.batteryWeight,
DX.chargingTemperature,
DX.maxChargingPower,
DX.maxResolution
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "DrivingLicense" $ do
let functions :: [Fake Text] =
[ DR.usaAlabama,
DR.usaAlaska,
DR.usaArizona,
DR.usaArkansas,
DR.usaCalifornia,
DR.usaColorado,
DR.usaConnecticut,
DR.usaDelaware,
DR.usaDistrictOfColumbia,
DR.usaFlorida,
DR.usaGeorgia,
DR.usaHawaii,
DR.usaIdaho,
DR.usaIllinois,
DR.usaIndiana,
DR.usaIowa,
DR.usaKansas,
DR.usaKentucky,
DR.usaLouisiana,
DR.usaMaine,
DR.usaMaryland,
DR.usaMassachusetts,
DR.usaMichigan,
DR.usaMinnesota,
DR.usaMississippi,
DR.usaMissouri,
DR.usaMontana,
DR.usaNebraska,
DR.usaNevada,
DR.usaNewHampshire,
DR.usaNewJersey,
DR.usaNewMexico,
DR.usaNewYork,
DR.usaNorthCarolina,
DR.usaOhio,
DR.usaOklahoma,
DR.usaOregon,
DR.usaPennsylvania,
DR.usaRhodeIsland,
DR.usaSouthCarolina,
DR.usaSouthDakota,
DR.usaTennessee,
DR.usaTexas,
DR.usaUtah,
DR.usaVermont,
DR.usaVirginia,
DR.usaWashington,
DR.usaWestVirginia,
DR.usaWisconsin,
DR.usaWyoming,
DR.usaNorthDakota
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Demographic" $ do
let functions :: [Fake Text] =
[ DE.race,
DE.sex,
DE.demonym,
DE.educationalAttainment,
DE.maritalStatus
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Dessert" $ do
let functions :: [Fake Text] = [DE.variety, DE.topping, DE.flavor]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Educator" $ do
let functions :: [Fake Text] =
[ ED.schoolName,
ED.secondary,
ED.university,
ED.secondarySchool,
ED.campus,
ED.subject,
ED.degree,
ED.courseName,
ED.tertiaryUniversityType,
ED.tertiaryDegreeType,
ED.tertiaryDegreeCourseNumber,
ED.primary,
ED.primarySchool
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "ElectricalComponents" $ do
let functions :: [Fake Text] =
[EC.active, EC.passive, EC.electromechanical]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Esport" $ do
let functions :: [Fake Text] =
[ES.players, ES.teams, ES.events, ES.leagues, ES.games]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "File" $ do
let functions :: [Fake Text] = [FI.extension, FI.mimeType]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Finance" $ do
let functions :: [Fake Text] =
[ FI.visa,
FI.mastercard,
FI.discover,
FI.dinersClub,
FI.jcb,
FI.switch,
FI.solo,
FI.dankort,
FI.maestro,
FI.forbrugsforeningen,
FI.laser
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Food" $ do
let functions :: [Fake Text] =
[ FO.dish,
FO.descriptions,
FO.ingredients,
FO.fruits,
FO.vegetables,
FO.spices,
FO.measurements,
FO.measurementSizes,
FO.metricMeasurements,
FO.sushi
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "FunnyName" $ do
let functions :: [Fake Text] = [FU.name]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.Futurama" $ do
let functions :: [Fake Text] =
[ FT.characters,
FT.locations,
FT.quotes,
FT.hermesCatchphrases
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Game.Dota" $ do
let functions :: [Fake Text] =
[ DO.hero,
DO.item,
DO.team,
DO.player,
DO.abaddonQuote,
DO.alchemistQuote,
DO.axeQuote,
DO.beastmasterQuote,
DO.brewmasterQuote,
DO.bristlebackQuote,
DO.centaurQuote,
DO.chaosKnightQuote,
DO.clockwerkQuote,
DO.doomQuote,
DO.dragonKnightQuote,
DO.earthSpiritQuote,
DO.earthshakerQuote,
DO.elderTitanQuote,
DO.huskarQuote,
DO.ioQuote,
DO.kunkkaQuote,
DO.legionCommanderQuote,
DO.lifestealerQuote,
DO.lycanQuote,
DO.magnusQuote,
DO.nightStalkerQuote,
DO.omniknightQuote,
DO.phoenixQuote,
DO.pudgeQuote,
DO.sandKingQuote,
DO.slardarQuote,
DO.spiritBreakerQuote,
DO.svenQuote,
DO.tidehunterQuote,
DO.timbersawQuote,
DO.tinyQuote,
DO.tuskQuote,
DO.underlordQuote,
DO.undyingQuote,
DO.wraithKingQuote,
DO.meepoQuote
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Game.ElderScrolls" $ do
let functions :: [Fake Text] =
[ EL.race,
EL.creature,
EL.region,
EL.dragon,
EL.city,
EL.firstName,
EL.lastName
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Game.Fallout" $ do
let functions :: [Fake Text] =
[FA.characters, FA.factions, FA.locations, FA.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Game.HalfLife" $ do
let functions :: [Fake Text] = [HA.character, HA.enemy, HA.location]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Game.Heroes" $ do
let functions :: [Fake Text] = [HE.names, HE.specialties, HE.klasses]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Game.HeroesOfTheStorm" $ do
let functions :: [Fake Text] =
[ HS.battlegrounds,
HS.classNames,
HS.heroes,
HS.quotes
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Game.Myst" $ do
let functions :: [Fake Text] =
[MY.games, MY.creatures, MY.characters, MY.ages, MY.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Game.Overwatch" $ do
let functions :: [Fake Text] = [OV.heroes, OV.locations, OV.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Game.WarhammerFantasy" $ do
let functions :: [Fake Text] =
[ WF.creatures,
WF.factions,
WF.factions,
WF.locations,
WF.quotes,
WF.heros
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Game.Pokemon" $ do
let functions :: [Fake Text] = [PO.names, PO.locations, PO.moves]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Game.SonicTheHedgehog" $ do
let functions :: [Fake Text] = [SO.zone, SO.character, SO.game]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Game.SonicTheHedgehog" $ do
let functions :: [Fake Text] = [SO.zone, SO.character, SO.game]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Game.SuperSmashBros" $ do
let functions :: [Fake Text] = [SU.fighter, SU.stage]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Game.Witcher" $ do
let functions :: [Fake Text] =
[ WI.characters,
WI.witchers,
WI.schools,
WI.locations,
WI.quotes,
WI.monsters,
WI.signs,
WI.potions,
WI.books
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Game.WorldOfwarcraft" $ do
let functions :: [Fake Text] = [
WO.heros
, WO.quotes
, WO.classNames
, WO.races
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Game.Zelda" $ do
let functions :: [Fake Text] =
[ZE.games, ZE.characters, ZE.locations, ZE.items]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Game.Minecraft" $ do
let functions :: [Fake Text] =
[ MC.blocks,
MC.items,
MC.mobs
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Game.StreetFighter" $ do
let functions :: [Fake Text] =
[ SF.characters,
SF.stages,
SF.quotes,
SF.moves
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Gender" $ do
let functions :: [Fake Text] =
[GE.types, GE.binaryTypes, GE.shortBinaryTypes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "GreekPhilosophers" $ do
let functions :: [Fake Text] = [GR.names, GR.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Hacker" $ do
let functions :: [Fake Text] =
[HA.abbreviation, HA.adjective, HA.noun, HA.verb, HA.ingverb]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Hipster" $ do
let functions :: [Fake Text] = [HI.words]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "House" $ do
let functions :: [Fake Text] = [HO.furniture, HO.rooms]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Industry" $ do
let functions :: [Fake Text] =
[IN.industry, IN.superSector, IN.sector, IN.subSector]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Internet" $ do
let functions :: [Fake Text] =
[ IN.freeEmail,
IN.domainSuffix,
IN.userAgentAol,
IN.userAgentChrome,
IN.userAgentFirefox,
IN.userAgentInternetExplorer,
IN.userAgentNetscape,
IN.userAgentOpera,
IN.userAgentSafari
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "JapaneseMedia.DragonBall" $ do
let functions :: [Fake Text] = [DR.characters, DR.races, DR.planets]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "JapaneseMedia.OnePiece" $ do
let functions :: [Fake Text] =
[ ON.characters,
ON.seas,
ON.islands,
ON.locations,
ON.quotes,
ON.akumasNoMi
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "JapaneseMedia.SwordArtOnline" $ do
let functions :: [Fake Text] =
[SW.realName, SW.gameName, SW.location, SW.item]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "JapaneseMedia.StudioGhibli" $ do
let functions :: [Fake Text] =
[ GI.characters,
GI.quotes,
GI.movies
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Job" $ do
let functions :: [Fake Text] =
[ JO.field,
JO.seniority,
JO.position,
JO.keySkills,
JO.employmentType,
JO.educationLevel,
JO.title
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Kpop" $ do
let functions :: [Fake Text] =
[ KP.iGroups,
KP.iiGroups,
KP.iiiGroups,
KP.girlGroups,
KP.boyBands,
KP.solo
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "LeagueOfLegends" $ do
let functions :: [Fake Text] =
[ LE.champion,
LE.location,
LE.quote,
LE.summonerSpell,
LE.masteries,
LE.rank
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Lorem" $ do
let functions :: [Fake Text] = [LM.words, LM.supplemental]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Markdown" $ do
let functions :: [Fake Text] = [MA.headers, MA.emphasis]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Marketing" $ do
let functions :: [Fake Text] = [MA.buzzwords]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Measurement" $ do
let functions :: [Fake Text] =
[ ME.height,
ME.length,
ME.volume,
ME.weight,
ME.metricHeight,
ME.metricLength,
ME.metricVolume,
ME.metricWeight
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Military" $ do
let functions :: [Fake Text] =
[ MI.armyRank,
MI.marinesRank,
MI.navyRank,
MI.airForceRank,
MI.dodPaygrade,
MI.coastGuardRank,
MI.spaceForceRank
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Movie.Departed" $ do
let functions :: [Fake Text] = [MD.actors, MD.characters, MD.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Movie.BackToTheFuture" $ do
let functions :: [Fake Text] = [BA.dates, BA.characters, BA.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Movie.Ghostbusters" $ do
let functions :: [Fake Text] = [GH.actors, GH.characters, GH.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Movie.GratefulDead" $ do
let functions :: [Fake Text] = [GR.players, GR.songs]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Movie.HarryPotter" $ do
let functions :: [Fake Text] =
[ HA.characters,
HA.locations,
HA.quotes,
HA.books,
HA.houses,
HA.spells
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Movie.HitchhikersGuideToTheGalaxy" $ do
let functions :: [Fake Text] =
[ HI.characters,
HI.locations,
HI.marvinQuote,
HI.planets,
HI.quotes,
HI.species,
HI.starships
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Movie.Lebowski" $ do
let functions :: [Fake Text] = [LE.actors, LE.characters, LE.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Movie.PrincessBride" $ do
let functions :: [Fake Text] = [PR.characters, PR.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Movie.StarWars" $ do
let functions :: [Fake Text] =
[ ST.characters,
ST.callSquadrons,
ST.droids,
ST.planets,
ST.species,
ST.vehicles,
ST.wookieeWords,
ST.callNumbers,
ST.callSign,
ST.quotesAdmiralAckbar,
ST.quotesAhsokaTano,
ST.quotesAsajjVentress,
ST.quotesBendu,
ST.quotesBobaFett,
ST.quotesC3po,
ST.quotesCountDooku,
ST.quotesDarthCaedus,
ST.quotesDarthVader,
ST.quotesEmperorPalpatine,
ST.quotesFinn,
ST.quotesGrandAdmiralThrawn,
ST.quotesGrandMoffTarkin,
ST.quotesGreedo,
ST.quotesHanSolo,
ST.quotesJabbaTheHutt,
ST.quotesJarJarBinks,
ST.quotesK2so,
ST.quotesKyloRen,
ST.quotesLandoCalrissian,
ST.quotesLeiaOrgana,
ST.quotesLukeSkywalker,
ST.quotesMaceWindu,
ST.quotesMazKanata,
ST.quotesObiWanKenobi,
ST.quotesPadmeAmidala,
ST.quotesQuiGonJinn,
ST.quotesRey,
ST.quotesShmiSkywalker,
ST.quotesYoda,
ST.alternateCharacterSpellingsAdmiralAckbar,
ST.alternateCharacterSpellingsAhsokaTano,
ST.alternateCharacterSpellingsAnakinSkywalker,
ST.alternateCharacterSpellingsAsajjVentress,
ST.alternateCharacterSpellingsBendu,
ST.alternateCharacterSpellingsBobaFett,
ST.alternateCharacterSpellingsC3po,
ST.alternateCharacterSpellingsCountDooku,
ST.alternateCharacterSpellingsDarthCaedus,
ST.alternateCharacterSpellingsDarthVader,
ST.alternateCharacterSpellingsEmperorPalpatine,
ST.alternateCharacterSpellingsFinn,
ST.alternateCharacterSpellingsGeneralHux,
ST.alternateCharacterSpellingsGrandAdmiralThrawn,
ST.alternateCharacterSpellingsGrandMoffTarkin,
ST.alternateCharacterSpellingsGreedo,
ST.alternateCharacterSpellingsHanSolo,
ST.alternateCharacterSpellingsJabbaTheHutt,
ST.alternateCharacterSpellingsJarJarBinks,
ST.alternateCharacterSpellingsK2so,
ST.alternateCharacterSpellingsKyloRen,
ST.alternateCharacterSpellingsLandoCalrissian,
ST.alternateCharacterSpellingsLeiaOrgana,
ST.alternateCharacterSpellingsLukeSkywalker,
ST.alternateCharacterSpellingsMaceWindu,
ST.alternateCharacterSpellingsMazKanata,
ST.alternateCharacterSpellingsObiWanKenobi,
ST.alternateCharacterSpellingsPadmeAmidala,
ST.alternateCharacterSpellingsQuiGonJinn,
ST.alternateCharacterSpellingsRey,
ST.alternateCharacterSpellingsShmiSkywalker,
ST.alternateCharacterSpellingsYoda
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Movie.VForVendetta" $ do
let functions :: [Fake Text] = [VF.characters, VF.speeches, VF.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Movie" $ do
let functions :: [Fake Text] = [MO.quote, MO.title]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Music.Opera" $ do
let functions :: [Fake Text] =
[ OP.italianByGiuseppeVerdi,
OP.italianByGioacchinoRossini,
OP.italianByGaetanoDonizetti,
OP.italianByVincenzoBellini,
OP.italianByChristophWillibaldGluck,
OP.italianByWolfgangAmadeusMozart,
OP.germanByWolfgangAmadeusMozart,
OP.germanByLudwigVanBeethoven,
OP.germanByCarlMariaVonWeber,
OP.germanByRichardStrauss,
OP.germanByRichardWagner,
OP.germanByRobertSchumann,
OP.germanByFranzSchubert,
OP.germanByAlbanBerg,
OP.frenchByChristophWillibaldGluck,
OP.frenchByMauriceRavel,
OP.frenchByHectorBerlioz,
OP.frenchByGeorgesBizet,
OP.frenchByCharlesGounod,
OP.frenchByCamilleSaintSaëns
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Music.PearlJam" $ do
let functions :: [Fake Text] =
[ OP.italianByGiuseppeVerdi,
OP.italianByGioacchinoRossini,
OP.italianByGaetanoDonizetti,
OP.italianByVincenzoBellini
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Music.Phish" $ do
let functions :: [Fake Text] = [PH.songs, PH.musicians, PH.albums]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Music.RockBand" $ do
let functions :: [Fake Text] = [RO.name, RO.song]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Music.UmphreysMcgee" $ do
let functions :: [Fake Text] = [UM.song]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Music.Prince" $ do
let functions :: [Fake Text] =
[ PC.lyric,
PC.song,
PC.album,
PC.band
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Music.Rush" $ do
let functions :: [Fake Text] =
[ RU.players,
RU.albums
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Music" $ do
let functions :: [Fake Text] =
[MU.instruments, MU.bands, MU.albums, MU.genres, MU.mamboNo5, MU.hiphopSubgenres
, MU.hiphopGroups
, MU.hiphopArtist]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Name" $ do
let functions :: [Fake Text] =
[ NA.maleFirstName,
NA.femaleFirstName,
NA.prefix,
NA.suffix,
NA.lastName,
NA.name,
NA.nameWithMiddle,
NA.firstName
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Nation" $ do
let functions :: [Fake Text] =
[NA.nationality, NA.language, NA.capitalCity, NA.flagEmoji]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "NatoPhoneticAlphabet" $ do
let functions :: [Fake Text] = [NA.codeWord]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "PhoneNumber" $ do
let functions :: [Fake Text] =
[PH.formats, PH.countryCode, PH.cellPhoneFormat]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "ProgrammingLanguage" $ do
let functions :: [Fake Text] = [PR.name, PR.creator]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Quote.Shakespeare" $ do
let functions :: [Fake Text] =
[SH.hamlet, SH.asYouLikeIt, SH.kingRichardIii, SH.romeoAndJuliet]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Quote" $ do
let functions :: [Fake Text] =
[ QU.famousLastWords,
QU.matz,
QU.mostInterestingManInTheWorld,
QU.robin,
QU.singularSiegler,
QU.yoda,
QU.fortuneCookie
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Relationship" $ do
let functions :: [Fake Text] =
[ RE.inLaw,
RE.spouse,
RE.parent,
RE.sibling,
RE.familialDirect,
RE.familialExtended
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Restaurant" $ do
let functions :: [Fake Text] =
[ RE.nameSuffix,
RE.type',
RE.description,
RE.review,
RE.namePrefix,
RE.name
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Science" $ do
let functions :: [Fake Text] =
[SC.element, SC.elementSymbol, SC.scientist
, SC.elementState, SC.elementSubcategory]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "SlackEmoji" $ do
let functions :: [Fake Text] =
[ SL.people,
SL.nature,
SL.foodAndDrink,
SL.celebration,
SL.activity,
SL.travelAndPlaces,
SL.objectsAndSymbols,
SL.custom,
SL.emoji
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Source" $ do
let functions :: [Fake Text] =
[ SO.helloWorldRuby,
SO.helloWorldJavascript,
SO.printRuby,
SO.printJavascript,
SO.print1To10Ruby,
SO.print1To10Javascript
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Space" $ do
let functions :: [Fake Text] =
[ SP.planet,
SP.moon,
SP.galaxy,
SP.nebula,
SP.starCluster,
SP.constellation,
SP.star,
SP.agency,
SP.agencyAbv,
SP.nasaSpaceCraft,
SP.company,
SP.distanceMeasurement,
SP.meteorite,
SP.launchVehicle
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Sport.Basketball" $ do
let functions :: [Fake Text] =
[BA.teams, BA.players, BA.coaches, BA.positions]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Sport.Football" $ do
let functions :: [Fake Text] =
[FO.teams, FO.players, FO.coaches, FO.competitions, FO.positions]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Subscription" $ do
let functions :: [Fake Text] =
[ SU.plans,
SU.statuses,
SU.paymentMethods,
SU.subscriptionTerms,
SU.paymentTerms
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Superhero" $ do
let functions :: [Fake Text] =
[SU.power, SU.prefix, SU.suffix, SU.descriptor, SU.name]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Team" $ do
let functions :: [Fake Text] = [TE.creature, TE.sport, TE.mascot, TE.name]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "University" $ do
let functions :: [Fake Text] = [UN.prefix, UN.suffix, UN.name]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Vehicle" $ do
let functions :: [Fake Text] =
[ VE.manufacture,
VE.makes,
VE.colors,
VE.transmissions,
VE.driveTypes,
VE.fuelTypes,
VE.styles,
VE.carTypes,
VE.carOptions,
VE.standardSpecs,
VE.licensePlate,
VE.modelsByMakeBMW,
VE.modelsByMakeAudi,
VE.modelsByMakeToyota,
VE.modelsByMakeChevy,
VE.modelsByMakeFord,
VE.modelsByMakeDodge,
VE.modelsByMakeLincoln,
VE.modelsByMakeBuick,
VE.modelsByMakeHonda,
VE.modelsByMakeNissan
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
let ifunctions :: [Fake Int] = [VE.doors, VE.engineSizes]
bools <- verifyFakeInt ifunctions
(and bools) `shouldBe` True
it "Verbs" $ do
let functions :: [Fake Text] =
[VE.base, VE.past, VE.pastParticiple, VE.simplePresent, VE.ingForm]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "WorldCup" $ do
let functions :: [Fake Text] =
[ WO.teams,
WO.stadiums,
WO.cities,
WO.groupsGroupA,
WO.groupsGroupB,
WO.groupsGroupC,
WO.groupsGroupD,
WO.groupsGroupE,
WO.groupsGroupF,
WO.groupsGroupG,
WO.groupsGroupH,
WO.rostersEgyptCoach,
WO.rostersEgyptGoalkeepers,
WO.rostersEgyptDefenders,
WO.rostersEgyptMidfielders,
WO.rostersEgyptForwards,
WO.rostersRussiaCoach,
WO.rostersRussiaGoalkeepers,
WO.rostersRussiaDefenders,
WO.rostersRussiaMidfielders,
WO.rostersRussiaForwards,
WO.rostersSaudiArabiaCoach,
WO.rostersSaudiArabiaGoalkeepers,
WO.rostersSaudiArabiaDefenders,
WO.rostersSaudiArabiaMidfielders,
WO.rostersSaudiArabiaForwards,
WO.rostersUruguayCoach,
WO.rostersUruguayGoalkeepers,
WO.rostersUruguayDefenders,
WO.rostersUruguayMidfielders,
WO.rostersUruguayForwards,
WO.rostersIranCoach,
WO.rostersIranGoalkeepers,
WO.rostersIranDefenders,
WO.rostersIranMidfielders,
WO.rostersIranForwards,
WO.rostersMoroccoCoach,
WO.rostersMoroccoGoalkeepers,
WO.rostersMoroccoDefenders,
WO.rostersMoroccoMidfielders,
WO.rostersMoroccoForwards,
WO.rostersPortugalCoach,
WO.rostersPortugalGoalkeepers,
WO.rostersPortugalDefenders,
WO.rostersPortugalMidfielders,
WO.rostersPortugalForwards,
WO.rostersSpainCoach,
WO.rostersSpainGoalkeepers,
WO.rostersSpainDefenders,
WO.rostersSpainMidfielders,
WO.rostersSpainForwards,
WO.rostersAustraliaCoach,
WO.rostersAustraliaGoalkeepers,
WO.rostersAustraliaDefenders,
WO.rostersAustraliaMidfielders,
WO.rostersAustraliaForwards,
WO.rostersDenmarkCoach,
WO.rostersDenmarkGoalkeepers,
WO.rostersDenmarkDefenders,
WO.rostersDenmarkMidfielders,
WO.rostersDenmarkForwards,
WO.rostersFranceCoach,
WO.rostersFranceGoalkeepers,
WO.rostersFranceDefenders,
WO.rostersFranceMidfielders,
WO.rostersFranceForwards,
WO.rostersPeruCoach,
WO.rostersPeruGoalkeepers,
WO.rostersPeruDefenders,
WO.rostersPeruMidfielders,
WO.rostersPeruForwards,
WO.rostersArgentinaCoach,
WO.rostersArgentinaGoalkeepers,
WO.rostersArgentinaDefenders,
WO.rostersArgentinaMidfielders,
WO.rostersArgentinaForwards,
WO.rostersCroatiaCoach,
WO.rostersCroatiaGoalkeepers,
WO.rostersCroatiaDefenders,
WO.rostersCroatiaMidfielders,
WO.rostersCroatiaForwards,
WO.rostersIcelandCoach,
WO.rostersIcelandGoalkeepers,
WO.rostersIcelandDefenders,
WO.rostersIcelandMidfielders,
WO.rostersIcelandForwards,
WO.rostersNigeriaCoach,
WO.rostersNigeriaGoalkeepers,
WO.rostersNigeriaDefenders,
WO.rostersNigeriaMidfielders,
WO.rostersNigeriaForwards,
WO.rostersBrazilCoach,
WO.rostersBrazilGoalkeepers,
WO.rostersBrazilDefenders,
WO.rostersBrazilMidfielders,
WO.rostersBrazilForwards,
WO.rostersCostaRicaCoach,
WO.rostersCostaRicaGoalkeepers,
WO.rostersCostaRicaDefenders,
WO.rostersCostaRicaMidfielders,
WO.rostersCostaRicaForwards,
WO.rostersSerbiaCoach,
WO.rostersSerbiaGoalkeepers,
WO.rostersSerbiaDefenders,
WO.rostersSerbiaMidfielders,
WO.rostersSerbiaForwards,
WO.rostersSwitzerlandCoach,
WO.rostersSwitzerlandGoalkeepers,
WO.rostersSwitzerlandDefenders,
WO.rostersSwitzerlandMidfielders,
WO.rostersSwitzerlandForwards,
WO.rostersGermanyCoach,
WO.rostersGermanyGoalkeepers,
WO.rostersGermanyDefenders,
WO.rostersGermanyMidfielders,
WO.rostersGermanyForwards,
WO.rostersMexicoCoach,
WO.rostersMexicoGoalkeepers,
WO.rostersMexicoDefenders,
WO.rostersMexicoMidfielders,
WO.rostersMexicoForwards,
WO.rostersSouthKoreaCoach,
WO.rostersSouthKoreaGoalkeepers,
WO.rostersSouthKoreaDefenders,
WO.rostersSouthKoreaMidfielders,
WO.rostersSouthKoreaForwards,
WO.rostersSwedenCoach,
WO.rostersSwedenGoalkeepers,
WO.rostersSwedenDefenders,
WO.rostersSwedenMidfielders,
WO.rostersSwedenForwards,
WO.rostersBelgiumCoach,
WO.rostersBelgiumGoalkeepers,
WO.rostersBelgiumDefenders,
WO.rostersBelgiumMidfielders,
WO.rostersBelgiumForwards,
WO.rostersEnglandCoach,
WO.rostersEnglandGoalkeepers,
WO.rostersEnglandDefenders,
WO.rostersEnglandMidfielders,
WO.rostersEnglandForwards,
WO.rostersPanamaCoach,
WO.rostersPanamaGoalkeepers,
WO.rostersPanamaDefenders,
WO.rostersPanamaMidfielders,
WO.rostersPanamaForwards,
WO.rostersTunisiaCoach,
WO.rostersTunisiaGoalkeepers,
WO.rostersTunisiaDefenders,
WO.rostersTunisiaMidfielders,
WO.rostersTunisiaForwards,
WO.rostersColumbiaCoach,
WO.rostersColumbiaGoalkeepers,
WO.rostersColumbiaDefenders,
WO.rostersColumbiaMidfielders,
WO.rostersColumbiaForwards,
WO.rostersJapanCoach,
WO.rostersJapanGoalkeepers,
WO.rostersJapanDefenders,
WO.rostersJapanMidfielders,
WO.rostersJapanForwards,
WO.rostersPolandCoach,
WO.rostersPolandGoalkeepers,
WO.rostersPolandDefenders,
WO.rostersPolandMidfielders,
WO.rostersPolandForwards,
WO.rostersSenegalCoach,
WO.rostersSenegalGoalkeepers,
WO.rostersSenegalDefenders,
WO.rostersSenegalMidfielders,
WO.rostersSenegalForwards
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "Yoda" $ do
let functions :: [Fake Text] = [YO.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.AquaTeenHungerForce" $ do
let functions :: [Fake Text] = [AQ.character, AQ.quote]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.BigBangTheory" $ do
let functions :: [Fake Text] = [BB.characters, BB.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.Suits" $ do
let functions :: [Fake Text] = [SU.characters, SU.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.BoJackHorseman" $ do
let functions :: [Fake Text] = [BO.character, BO.quote, BO.tongueTwister]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.BreakingBad" $ do
let functions :: [Fake Text] = [BR.character, BR.episode]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.Buffy" $ do
let functions :: [Fake Text] =
[BU.characters, BU.quotes, BU.actors, BU.bigBads, BU.episodes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.Community" $ do
let functions :: [Fake Text] = [CO.characters, CO.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.DrWho" $ do
let functions :: [Fake Text] =
[ DR.character,
DR.theDoctors,
DR.actors,
DR.catchPhrases,
DR.quotes,
DR.villains,
DR.species
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.DumbAndDumber" $ do
let functions :: [Fake Text] = [DD.actors, DD.characters, DD.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.FamilyGuy" $ do
let functions :: [Fake Text] = [FA.character, FA.location, FA.quote]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.FreshPrinceOfBelAir" $ do
let functions :: [Fake Text] = [FR.characters, FR.actors, FR.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.Friends" $ do
let functions :: [Fake Text] = [FI.characters, FI.locations, FI.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.Friends" $ do
let functions :: [Fake Text] = [FI.characters, FI.locations, FI.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.GameOfThrones" $ do
let functions :: [Fake Text] =
[GA.characters, GA.houses, GA.cities, GA.quotes, GA.dragons]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.HeyArnold" $ do
let functions :: [Fake Text] = [HE.characters, HE.locations, HE.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.HowIMetYourMother" $ do
let functions :: [Fake Text] =
[HI.character, HI.catchPhrase, HI.highFive, HI.quote]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.MichaelScott" $ do
let functions :: [Fake Text] = [MI.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.NewGirl" $ do
let functions :: [Fake Text] = [NE.characters, NE.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.ParksAndRec" $ do
let functions :: [Fake Text] = [PA.characters, PA.cities]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.RickAndMorty" $ do
let functions :: [Fake Text] = [RI.characters, RI.locations, RI.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.Rupaul" $ do
let functions :: [Fake Text] = [RU.queens, RU.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.Seinfeld" $ do
let functions :: [Fake Text] = [SE.character, SE.quote, SE.business]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.Seinfeld" $ do
let functions :: [Fake Text] = [SE.character, SE.quote, SE.business]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.SiliconValley" $ do
let functions :: [Fake Text] =
[ SI.characters,
SI.companies,
SI.quotes,
SI.apps,
SI.inventions,
SI.mottos,
SI.urls,
SI.email
]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.Simpsons" $ do
let functions :: [Fake Text] = [SS.characters, SS.locations, SS.quotes, SS.episodeTitles]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.SouthPark" $ do
let functions :: [Fake Text] = [SO.characters, SO.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.StarTrek" $ do
let functions :: [Fake Text] =
[SR.character, SR.location, SR.specie, SR.villain]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.StarGate" $ do
let functions :: [Fake Text] = [SG.characters, SG.planets, SG.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.StrangerThings" $ do
let functions :: [Fake Text] = [SH.character, SH.quote]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.TheExpanse" $ do
let functions :: [Fake Text] =
[TH.characters, TH.locations, TH.ships, TH.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.TheItCrowd" $ do
let functions :: [Fake Text] =
[TI.actors, TI.characters, TI.emails, TI.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.TheThickOfIt" $ do
let functions :: [Fake Text] =
[TO.characters, TO.positions, TO.departments]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.TwinPeaks" $ do
let functions :: [Fake Text] = [TW.characters, TW.locations, TW.quotes]
bools <- verifyFakes functions
(and bools) `shouldBe` True
it "TvShow.VentureBros" $ do
let functions :: [Fake Text] =
[VE.character, VE.organization, VE.vehicle, VE.quote]
bools <- verifyFakes functions
(and bools) `shouldBe` True
|
ab3005155c69234c445b5a195e1a369fb27d0334a4a0e391a3d1787d6e237ff9 | WorksHub/client | core.cljs | (ns wh.pages.core
(:require [bidi.bidi :as bidi]
[cljs.loader :as loader]
[clojure.string :as str]
[pushy.core :as pushy]
[re-frame.core :refer [reg-fx reg-sub reg-event-db reg-event-fx dispatch dispatch-sync]]
[re-frame.db :refer [app-db]]
[wh.common.url :as common-url]
[wh.common.user :as user-common]
[wh.db :as db]
[wh.pages.modules :as modules]
[wh.routes :as routes]
[wh.util :as util]
[wh.verticals :as verticals]))
(def default-route {:handler :not-found})
(def default-page-size 24)
;; If you came here looking for 'scroll-to-top' functionality,
;; be aware that although we're setting `scrollTop` of `documentElement`,
;; it's the `onscroll` event of `js/window` that is triggered when a scroll happens
(defn force-scroll-to-x! [x]
(set! (.-scrollTop (.getElementById js/document "app")) x)
(set! (.-scrollTop (.-documentElement js/document)) x)
(set! (.-scrollTop (.-body js/document)) x))
(defn set-page-title! [page-name vertical]
(set!
(.-title js/document)
(str page-name " | " (get-in verticals/vertical-config [vertical :platform-name]))))
(defn force-scroll-to-top! []
(force-scroll-to-x! 0))
(defmulti on-page-load
"Returns a vector of events to dispatch when a page is shown."
::db/page)
NB : Other ` on - page - load ` methods are installed from their events ns ,
;; e.g `wh.blogs.learn.events/on-page-load`.
(defmethod on-page-load :default [_db] [])
(defmulti on-page-browser-nav
"Returns an event to dispatch upon the on-page browser navigation."
::db/page)
NB : Other ` on - page - browser - nav ` methods are installed from their events ns ,
;; e.g `wh.search.events/on-page-browser-nav`.
(defmethod on-page-browser-nav :default [_db] nil)
(defn- module-for [handler]
(modules/module-for handler (get-in @app-db [:wh.user.db/sub-db :wh.user.db/type])))
(defn resolve-handler [db handler]
(let [mapping (get-in db [::db/page-mapping handler])]
(if (map? mapping)
(if-let [redirect-fn (:redirect-fn mapping)]
(recur db (redirect-fn db))
handler)
handler)))
(defn redirect-when-not-permitted
"Return the page to redirect to when user is not allowed to
access the requested page."
[db handler]
(let [mapping (get-in db [::db/page-mapping handler])
can-access? (if (map? mapping)
(:can-access? mapping)
(constantly true))]
(cond
(can-access? db) nil
(= can-access? db/logged-in?) :login
(and (not (db/logged-in? db))
(= can-access? user-common/company?)) :login
:else :not-found)))
;; Set current page and page params, if any.
;; NOTE: this is an internal event, meant to be dispatched by
;; pushy only. To programmatically navigate through the app,
;; use the :navigate fx defined below.
(reg-event-fx ::set-page
db/default-interceptors
(fn [{db :db} [{:keys [handler params route-params query-params uri] :as _route} history-state]]
(let [handler (resolve-handler db handler)
page-info {:page-name (routes/handler->name handler)
:vertical (:wh.db/vertical db)}]
(case (redirect-when-not-permitted db handler)
:not-found
{:db (assoc db
::db/page :not-found
::db/loading? false) ; it might've been set in pre-rendered app-db
:page-title page-info}
:login
(let [current-path (bidi/url-encode (routes/path handler :params params :query-params query-params))
login-step (if (= :company (module-for handler)) :email :root)] ;; if company, show email login
{:navigate [:login :params {:step login-step} :query-params {:redirect current-path}]
:page-title page-info})
;; otherwise
(let [new-page? (not= (::db/page db) handler)
initial-load? (::db/initial-load? db)
scroll (if history-state (aget history-state "scroll-position") 0)
;; TODO: Come up with a universal way of replacing '+'s in route params' values with `bidi`?
route-params' (util/update* route-params :query #(str/replace % "+" " "))
query-params' (or (common-url/concat-vector-values query-params) {})
new-db (-> db
(assoc ::db/page handler
::db/page-params (merge params route-params' {})
::db/query-params query-params'
::db/uri uri
::db/scroll scroll)
(update ::db/page-moves inc))
on-page-load? (nil? history-state)
on-page-nav (when-not (or initial-load?
NB : This should not normally be a part of the condition ,
but our custom Pushy history state tx implementation
;; will cause `on-page-load` event on the latest entry
;; in the chain of forward-button events. So I decided
;; to pretend this is a new page load just in order to
;; avoid duplicate events triggering (`on-page-load` +
;; `on-page-browser-nav`).
on-page-load?)
(on-page-browser-nav new-db))]
(cond-> {:db new-db
:analytics/pageview true
:analytics/track [(str (routes/handler->name handler) " Viewed")
(merge params query-params route-params)
true]
:dispatch-n [[:error/close-global]
on-page-nav
[::disable-no-scroll]
[:wh.events/show-chat? true]]}
(not initial-load?)
(assoc :page-title page-info)
;; This forces scrolling to top when moving forward to a new page,
;; but does nothing when moving backwards. We leverage a built-in
;; `scrollRestoration` to keep & restore the scroll position.
(and new-page? (zero? scroll))
(assoc :scroll-to-top true)
;; We only fire `on-page-load` events when we didn't receive a back-button
;; navigation (i.e. `history-state` is `nil`). See `pushy/core.cljs`.
on-page-load?
(update :dispatch-n
#(let [events (cond-> (on-page-load new-db)
initial-load? (conj [:wh.events/set-initial-load false]))]
(concat % events)))))))))
Internal event meant to be triggered by : navigate only .
(reg-sub ::page
(fn [db _]
(::db/page db)))
(defn- parse-url [url]
(let [query-params (common-url/uri->query-params url)]
(assoc
(or (bidi/match-route routes/routes url)
default-route)
;; TODO: Shouldn't it also check `url` URI 'path' for a `query`?
;; If true, it makes sense to re-write this via delegating
to the shared ` wh.common.search/->search-term ` fn .
:params (when (contains? query-params "search")
{:query (get query-params "search")})
:query-params query-params
:uri url)))
(defn load-and-dispatch [[module event]]
(let [db @re-frame.db/app-db
this is to avoid loader flickering when logging in via GitHub
(= (:wh.db/page db) :github-callback) ;; hacky, but we're not in an event
(= (:wh.db/page db) :stackoverflow-callback)
(= (:wh.db/page db) :twitter-callback)
(and (zero? (:wh.db/page-moves db))
(:wh.db/server-side-rendered? db)))]
(when (and (not skip-loader?)
(not (loader/loaded? module)))
(dispatch [::set-loader]))
;; If we don't wrap the loader/load call in setTimeout and happen to
;; invoke this from an /admin/... URL, cljs-base is not yet fully loaded
;; by the time we're here.
See comment in -2264 .
(js/window.setTimeout
(fn [] (loader/load module
#(do
(when event
(dispatch-sync event))
(when-not skip-loader?
(dispatch [::unset-loader]))))))))
(reg-fx :load-and-dispatch load-and-dispatch)
(defn get-app-ssr-scroll-value []
(if-let [app-ssr (js/document.getElementById "app-ssr")]
(max (.-scrollY js/window) (.-scrollTop app-ssr))
(max (.-scrollY js/window) 0)))
(defn show-app! []
(when-let [app-ssr (js/document.getElementById "app-ssr")]
(let [scroll-value (get-app-ssr-scroll-value)
app (js/document.getElementById "app")]
(.remove (.-classList app) "app--hidden")
(force-scroll-to-x! scroll-value)
(js/document.body.removeChild app-ssr))))
(reg-fx :show-app? show-app!)
(defn- set-page [route history-state]
(let [set-page-event [::set-page route history-state]]
(if-let [module (module-for (:handler route))]
(load-and-dispatch [module set-page-event])
(dispatch set-page-event))))
(reg-fx :load-module-and-set-page #(set-page % nil))
(reg-event-fx
::load-module-and-set-page
db/default-interceptors
(fn [_ [route]]
{:load-module-and-set-page route}))
(reg-event-db
::disable-no-scroll
db/default-interceptors
(fn [db _]
(js/disableNoScroll)
db))
(reg-fx
:page-title
(fn [{:keys [page-name vertical]}]
(set-page-title! page-name vertical)))
(reg-event-db
::enable-no-scroll
db/default-interceptors
(fn [db _]
(js/setNoScroll "app" true)
db))
(defn processable-url? [uri]
(and (not (contains? routes/server-side-only-paths (.getPath uri))) ;; we tell pushy to leave alone server side rendered pages
;; while preserving the default behavior
(pushy/processable-url? uri)))
(defn dispatch-for-route-data? [{:keys [handler] :as route-data}]
(and route-data (not (contains? routes/nextjs-pages handler))))
(def pushy-instance (pushy/pushy set-page parse-url
:processable-url? processable-url?
:state-fn (fn []
(clj->js {:scroll-position (.-scrollTop (.-documentElement js/document))}))
:dispatch-for-route-data? dispatch-for-route-data?))
(defn navigate
"Construct a URI from `handler` & `opts` and set it as current via Pushy.
This will trigger setting ::db/page and ::db/page-params as appropriate."
[[handler & {:keys [params query-params anchor] :as _opts}]]
(when-let [token (routes/path handler
:params params
:query-params query-params
:anchor anchor)]
(pushy/set-token! pushy-instance token "")))
(reg-fx :navigate navigate)
(defn hook-browser-navigation! []
(pushy/start! pushy-instance))
(reg-event-db
::set-loader
db/default-interceptors
(fn [db _]
(assoc db ::db/loading? true)))
(reg-event-fx
::unset-loader
db/default-interceptors
(fn [{db :db} _]
{:db (assoc db ::db/loading? false)
:show-app? true}))
| null | https://raw.githubusercontent.com/WorksHub/client/4b704cbc825738a2faa05a382641b683d6e4ca37/client/src/wh/pages/core.cljs | clojure | If you came here looking for 'scroll-to-top' functionality,
be aware that although we're setting `scrollTop` of `documentElement`,
it's the `onscroll` event of `js/window` that is triggered when a scroll happens
e.g `wh.blogs.learn.events/on-page-load`.
e.g `wh.search.events/on-page-browser-nav`.
Set current page and page params, if any.
NOTE: this is an internal event, meant to be dispatched by
pushy only. To programmatically navigate through the app,
use the :navigate fx defined below.
it might've been set in pre-rendered app-db
if company, show email login
otherwise
TODO: Come up with a universal way of replacing '+'s in route params' values with `bidi`?
will cause `on-page-load` event on the latest entry
in the chain of forward-button events. So I decided
to pretend this is a new page load just in order to
avoid duplicate events triggering (`on-page-load` +
`on-page-browser-nav`).
This forces scrolling to top when moving forward to a new page,
but does nothing when moving backwards. We leverage a built-in
`scrollRestoration` to keep & restore the scroll position.
We only fire `on-page-load` events when we didn't receive a back-button
navigation (i.e. `history-state` is `nil`). See `pushy/core.cljs`.
TODO: Shouldn't it also check `url` URI 'path' for a `query`?
If true, it makes sense to re-write this via delegating
hacky, but we're not in an event
If we don't wrap the loader/load call in setTimeout and happen to
invoke this from an /admin/... URL, cljs-base is not yet fully loaded
by the time we're here.
we tell pushy to leave alone server side rendered pages
while preserving the default behavior | (ns wh.pages.core
(:require [bidi.bidi :as bidi]
[cljs.loader :as loader]
[clojure.string :as str]
[pushy.core :as pushy]
[re-frame.core :refer [reg-fx reg-sub reg-event-db reg-event-fx dispatch dispatch-sync]]
[re-frame.db :refer [app-db]]
[wh.common.url :as common-url]
[wh.common.user :as user-common]
[wh.db :as db]
[wh.pages.modules :as modules]
[wh.routes :as routes]
[wh.util :as util]
[wh.verticals :as verticals]))
(def default-route {:handler :not-found})
(def default-page-size 24)
(defn force-scroll-to-x! [x]
(set! (.-scrollTop (.getElementById js/document "app")) x)
(set! (.-scrollTop (.-documentElement js/document)) x)
(set! (.-scrollTop (.-body js/document)) x))
(defn set-page-title! [page-name vertical]
(set!
(.-title js/document)
(str page-name " | " (get-in verticals/vertical-config [vertical :platform-name]))))
(defn force-scroll-to-top! []
(force-scroll-to-x! 0))
(defmulti on-page-load
"Returns a vector of events to dispatch when a page is shown."
::db/page)
NB : Other ` on - page - load ` methods are installed from their events ns ,
(defmethod on-page-load :default [_db] [])
(defmulti on-page-browser-nav
"Returns an event to dispatch upon the on-page browser navigation."
::db/page)
NB : Other ` on - page - browser - nav ` methods are installed from their events ns ,
(defmethod on-page-browser-nav :default [_db] nil)
(defn- module-for [handler]
(modules/module-for handler (get-in @app-db [:wh.user.db/sub-db :wh.user.db/type])))
(defn resolve-handler [db handler]
(let [mapping (get-in db [::db/page-mapping handler])]
(if (map? mapping)
(if-let [redirect-fn (:redirect-fn mapping)]
(recur db (redirect-fn db))
handler)
handler)))
(defn redirect-when-not-permitted
"Return the page to redirect to when user is not allowed to
access the requested page."
[db handler]
(let [mapping (get-in db [::db/page-mapping handler])
can-access? (if (map? mapping)
(:can-access? mapping)
(constantly true))]
(cond
(can-access? db) nil
(= can-access? db/logged-in?) :login
(and (not (db/logged-in? db))
(= can-access? user-common/company?)) :login
:else :not-found)))
(reg-event-fx ::set-page
db/default-interceptors
(fn [{db :db} [{:keys [handler params route-params query-params uri] :as _route} history-state]]
(let [handler (resolve-handler db handler)
page-info {:page-name (routes/handler->name handler)
:vertical (:wh.db/vertical db)}]
(case (redirect-when-not-permitted db handler)
:not-found
{:db (assoc db
::db/page :not-found
:page-title page-info}
:login
(let [current-path (bidi/url-encode (routes/path handler :params params :query-params query-params))
{:navigate [:login :params {:step login-step} :query-params {:redirect current-path}]
:page-title page-info})
(let [new-page? (not= (::db/page db) handler)
initial-load? (::db/initial-load? db)
scroll (if history-state (aget history-state "scroll-position") 0)
route-params' (util/update* route-params :query #(str/replace % "+" " "))
query-params' (or (common-url/concat-vector-values query-params) {})
new-db (-> db
(assoc ::db/page handler
::db/page-params (merge params route-params' {})
::db/query-params query-params'
::db/uri uri
::db/scroll scroll)
(update ::db/page-moves inc))
on-page-load? (nil? history-state)
on-page-nav (when-not (or initial-load?
NB : This should not normally be a part of the condition ,
but our custom Pushy history state tx implementation
on-page-load?)
(on-page-browser-nav new-db))]
(cond-> {:db new-db
:analytics/pageview true
:analytics/track [(str (routes/handler->name handler) " Viewed")
(merge params query-params route-params)
true]
:dispatch-n [[:error/close-global]
on-page-nav
[::disable-no-scroll]
[:wh.events/show-chat? true]]}
(not initial-load?)
(assoc :page-title page-info)
(and new-page? (zero? scroll))
(assoc :scroll-to-top true)
on-page-load?
(update :dispatch-n
#(let [events (cond-> (on-page-load new-db)
initial-load? (conj [:wh.events/set-initial-load false]))]
(concat % events)))))))))
Internal event meant to be triggered by : navigate only .
(reg-sub ::page
(fn [db _]
(::db/page db)))
(defn- parse-url [url]
(let [query-params (common-url/uri->query-params url)]
(assoc
(or (bidi/match-route routes/routes url)
default-route)
to the shared ` wh.common.search/->search-term ` fn .
:params (when (contains? query-params "search")
{:query (get query-params "search")})
:query-params query-params
:uri url)))
(defn load-and-dispatch [[module event]]
(let [db @re-frame.db/app-db
this is to avoid loader flickering when logging in via GitHub
(= (:wh.db/page db) :stackoverflow-callback)
(= (:wh.db/page db) :twitter-callback)
(and (zero? (:wh.db/page-moves db))
(:wh.db/server-side-rendered? db)))]
(when (and (not skip-loader?)
(not (loader/loaded? module)))
(dispatch [::set-loader]))
See comment in -2264 .
(js/window.setTimeout
(fn [] (loader/load module
#(do
(when event
(dispatch-sync event))
(when-not skip-loader?
(dispatch [::unset-loader]))))))))
(reg-fx :load-and-dispatch load-and-dispatch)
(defn get-app-ssr-scroll-value []
(if-let [app-ssr (js/document.getElementById "app-ssr")]
(max (.-scrollY js/window) (.-scrollTop app-ssr))
(max (.-scrollY js/window) 0)))
(defn show-app! []
(when-let [app-ssr (js/document.getElementById "app-ssr")]
(let [scroll-value (get-app-ssr-scroll-value)
app (js/document.getElementById "app")]
(.remove (.-classList app) "app--hidden")
(force-scroll-to-x! scroll-value)
(js/document.body.removeChild app-ssr))))
(reg-fx :show-app? show-app!)
(defn- set-page [route history-state]
(let [set-page-event [::set-page route history-state]]
(if-let [module (module-for (:handler route))]
(load-and-dispatch [module set-page-event])
(dispatch set-page-event))))
(reg-fx :load-module-and-set-page #(set-page % nil))
(reg-event-fx
::load-module-and-set-page
db/default-interceptors
(fn [_ [route]]
{:load-module-and-set-page route}))
(reg-event-db
::disable-no-scroll
db/default-interceptors
(fn [db _]
(js/disableNoScroll)
db))
(reg-fx
:page-title
(fn [{:keys [page-name vertical]}]
(set-page-title! page-name vertical)))
(reg-event-db
::enable-no-scroll
db/default-interceptors
(fn [db _]
(js/setNoScroll "app" true)
db))
(defn processable-url? [uri]
(pushy/processable-url? uri)))
(defn dispatch-for-route-data? [{:keys [handler] :as route-data}]
(and route-data (not (contains? routes/nextjs-pages handler))))
(def pushy-instance (pushy/pushy set-page parse-url
:processable-url? processable-url?
:state-fn (fn []
(clj->js {:scroll-position (.-scrollTop (.-documentElement js/document))}))
:dispatch-for-route-data? dispatch-for-route-data?))
(defn navigate
"Construct a URI from `handler` & `opts` and set it as current via Pushy.
This will trigger setting ::db/page and ::db/page-params as appropriate."
[[handler & {:keys [params query-params anchor] :as _opts}]]
(when-let [token (routes/path handler
:params params
:query-params query-params
:anchor anchor)]
(pushy/set-token! pushy-instance token "")))
(reg-fx :navigate navigate)
(defn hook-browser-navigation! []
(pushy/start! pushy-instance))
(reg-event-db
::set-loader
db/default-interceptors
(fn [db _]
(assoc db ::db/loading? true)))
(reg-event-fx
::unset-loader
db/default-interceptors
(fn [{db :db} _]
{:db (assoc db ::db/loading? false)
:show-app? true}))
|
feae17db411636ad09f60511835aceb581cd89e8834e820d6bac0b481f22baff | NorfairKing/sydtest | Def.hs | # LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
{-# LANGUAGE GADTs #-}
{-# LANGUAGE RankNTypes #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeOperators #
module Test.Syd.Wai.Def where
import Network.HTTP.Client as HTTP
import Network.Socket (PortNumber)
import Network.Wai as Wai
import Network.Wai.Handler.Warp as Warp
import Test.Syd
import Test.Syd.Wai.Client
-- | Run a given 'Wai.Application' around every test.
--
-- This provides a 'WaiClient ()' which contains the port of the running application.
waiClientSpec :: Wai.Application -> TestDefM (HTTP.Manager ': outers) (WaiClient ()) result -> TestDefM outers oldInner result
waiClientSpec application = waiClientSpecWith $ pure application
-- | Run a given 'Wai.Application', as built by the given action, around every test.
waiClientSpecWith :: IO Application -> TestDefM (HTTP.Manager ': outers) (WaiClient ()) result -> TestDefM outers oldInner result
waiClientSpecWith application = waiClientSpecWithSetupFunc (\_ _ -> liftIO $ (,) <$> application <*> pure ())
| Run a given ' Wai . Application ' , as built by the given ' SetupFunc ' , around every test .
waiClientSpecWithSetupFunc ::
(HTTP.Manager -> oldInner -> SetupFunc (Application, env)) ->
TestDefM (HTTP.Manager ': outers) (WaiClient env) result ->
TestDefM outers oldInner result
waiClientSpecWithSetupFunc setupFunc = managerSpec . waiClientSpecWithSetupFunc' setupFunc
| Run a given ' Wai . Application ' , as built by the given ' SetupFunc ' , around every test .
--
-- This function doesn't set up the 'HTTP.Manager' like 'waiClientSpecWithSetupFunc' does.
waiClientSpecWithSetupFunc' ::
(HTTP.Manager -> oldInner -> SetupFunc (Application, env)) ->
TestDefM (HTTP.Manager ': outers) (WaiClient env) result ->
TestDefM (HTTP.Manager ': outers) oldInner result
waiClientSpecWithSetupFunc' setupFunc = setupAroundWith' $ \man oldInner -> do
(application, env) <- setupFunc man oldInner
waiClientSetupFunc man application env
| A ' SetupFunc ' for a ' WaiClient ' , given an ' Application ' and user - defined @env@.
waiClientSetupFunc :: HTTP.Manager -> Application -> env -> SetupFunc (WaiClient env)
waiClientSetupFunc man application env = do
p <- applicationSetupFunc application
let client =
WaiClient
{ waiClientManager = man,
waiClientEnv = env,
waiClientPort = p
}
pure client
-- | Run a given 'Wai.Application' around every test.
--
-- This provides the port on which the application is running.
waiSpec :: Wai.Application -> TestDef outers PortNumber -> TestDef outers ()
waiSpec application = waiSpecWithSetupFunc $ pure application
-- | Run a 'Wai.Application' around every test by setting it up with the given setup function.
--
-- This provides the port on which the application is running.
waiSpecWith :: (forall r. (Application -> IO r) -> IO r) -> TestDef outers PortNumber -> TestDef outers ()
waiSpecWith appFunc = waiSpecWithSetupFunc $ SetupFunc $ \takeApp -> appFunc takeApp
-- | Run a 'Wai.Application' around every test by setting it up with the given setup function that can take an argument.
-- a
-- This provides the port on which the application is running.
waiSpecWith' :: (forall r. (Application -> IO r) -> (inner -> IO r)) -> TestDef outers PortNumber -> TestDef outers inner
waiSpecWith' appFunc = waiSpecWithSetupFunc' $ \inner -> SetupFunc $ \takeApp -> appFunc takeApp inner
| Run a ' Wai . Application ' around every test by setting it up with the given ' SetupFunc ' .
-- a
-- This provides the port on which the application is running.
waiSpecWithSetupFunc :: SetupFunc Application -> TestDef outers PortNumber -> TestDef outers ()
waiSpecWithSetupFunc setupFunc = waiSpecWithSetupFunc' $ \() -> setupFunc
| Run a ' Wai . Application ' around every test by setting it up with the given ' SetupFunc ' and inner resource .
-- a
-- This provides the port on which the application is running.
waiSpecWithSetupFunc' :: (inner -> SetupFunc Application) -> TestDef outers PortNumber -> TestDef outers inner
waiSpecWithSetupFunc' setupFunc = setupAroundWith $ \inner -> do
application <- setupFunc inner
applicationSetupFunc application
| A ' SetupFunc ' to run an application and provide its port .
applicationSetupFunc :: Application -> SetupFunc PortNumber
applicationSetupFunc application = SetupFunc $ \func ->
Warp.testWithApplication (pure application) $ \p ->
func (fromIntegral p) -- Hopefully safe, because 'testWithApplication' should give us sensible port numbers
-- | Create a 'HTTP.Manager' before all tests in the given group.
managerSpec :: TestDefM (HTTP.Manager ': outers) inner result -> TestDefM outers inner result
managerSpec = beforeAll $ HTTP.newManager HTTP.defaultManagerSettings
| null | https://raw.githubusercontent.com/NorfairKing/sydtest/22a7421ba635a18b1bfa750e64c8db5ee8842e5a/sydtest-wai/src/Test/Syd/Wai/Def.hs | haskell | # LANGUAGE GADTs #
# LANGUAGE RankNTypes #
| Run a given 'Wai.Application' around every test.
This provides a 'WaiClient ()' which contains the port of the running application.
| Run a given 'Wai.Application', as built by the given action, around every test.
This function doesn't set up the 'HTTP.Manager' like 'waiClientSpecWithSetupFunc' does.
| Run a given 'Wai.Application' around every test.
This provides the port on which the application is running.
| Run a 'Wai.Application' around every test by setting it up with the given setup function.
This provides the port on which the application is running.
| Run a 'Wai.Application' around every test by setting it up with the given setup function that can take an argument.
a
This provides the port on which the application is running.
a
This provides the port on which the application is running.
a
This provides the port on which the application is running.
Hopefully safe, because 'testWithApplication' should give us sensible port numbers
| Create a 'HTTP.Manager' before all tests in the given group. | # LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeOperators #
module Test.Syd.Wai.Def where
import Network.HTTP.Client as HTTP
import Network.Socket (PortNumber)
import Network.Wai as Wai
import Network.Wai.Handler.Warp as Warp
import Test.Syd
import Test.Syd.Wai.Client
waiClientSpec :: Wai.Application -> TestDefM (HTTP.Manager ': outers) (WaiClient ()) result -> TestDefM outers oldInner result
waiClientSpec application = waiClientSpecWith $ pure application
waiClientSpecWith :: IO Application -> TestDefM (HTTP.Manager ': outers) (WaiClient ()) result -> TestDefM outers oldInner result
waiClientSpecWith application = waiClientSpecWithSetupFunc (\_ _ -> liftIO $ (,) <$> application <*> pure ())
| Run a given ' Wai . Application ' , as built by the given ' SetupFunc ' , around every test .
waiClientSpecWithSetupFunc ::
(HTTP.Manager -> oldInner -> SetupFunc (Application, env)) ->
TestDefM (HTTP.Manager ': outers) (WaiClient env) result ->
TestDefM outers oldInner result
waiClientSpecWithSetupFunc setupFunc = managerSpec . waiClientSpecWithSetupFunc' setupFunc
| Run a given ' Wai . Application ' , as built by the given ' SetupFunc ' , around every test .
waiClientSpecWithSetupFunc' ::
(HTTP.Manager -> oldInner -> SetupFunc (Application, env)) ->
TestDefM (HTTP.Manager ': outers) (WaiClient env) result ->
TestDefM (HTTP.Manager ': outers) oldInner result
waiClientSpecWithSetupFunc' setupFunc = setupAroundWith' $ \man oldInner -> do
(application, env) <- setupFunc man oldInner
waiClientSetupFunc man application env
| A ' SetupFunc ' for a ' WaiClient ' , given an ' Application ' and user - defined @env@.
waiClientSetupFunc :: HTTP.Manager -> Application -> env -> SetupFunc (WaiClient env)
waiClientSetupFunc man application env = do
p <- applicationSetupFunc application
let client =
WaiClient
{ waiClientManager = man,
waiClientEnv = env,
waiClientPort = p
}
pure client
waiSpec :: Wai.Application -> TestDef outers PortNumber -> TestDef outers ()
waiSpec application = waiSpecWithSetupFunc $ pure application
waiSpecWith :: (forall r. (Application -> IO r) -> IO r) -> TestDef outers PortNumber -> TestDef outers ()
waiSpecWith appFunc = waiSpecWithSetupFunc $ SetupFunc $ \takeApp -> appFunc takeApp
waiSpecWith' :: (forall r. (Application -> IO r) -> (inner -> IO r)) -> TestDef outers PortNumber -> TestDef outers inner
waiSpecWith' appFunc = waiSpecWithSetupFunc' $ \inner -> SetupFunc $ \takeApp -> appFunc takeApp inner
| Run a ' Wai . Application ' around every test by setting it up with the given ' SetupFunc ' .
waiSpecWithSetupFunc :: SetupFunc Application -> TestDef outers PortNumber -> TestDef outers ()
waiSpecWithSetupFunc setupFunc = waiSpecWithSetupFunc' $ \() -> setupFunc
| Run a ' Wai . Application ' around every test by setting it up with the given ' SetupFunc ' and inner resource .
waiSpecWithSetupFunc' :: (inner -> SetupFunc Application) -> TestDef outers PortNumber -> TestDef outers inner
waiSpecWithSetupFunc' setupFunc = setupAroundWith $ \inner -> do
application <- setupFunc inner
applicationSetupFunc application
| A ' SetupFunc ' to run an application and provide its port .
applicationSetupFunc :: Application -> SetupFunc PortNumber
applicationSetupFunc application = SetupFunc $ \func ->
Warp.testWithApplication (pure application) $ \p ->
managerSpec :: TestDefM (HTTP.Manager ': outers) inner result -> TestDefM outers inner result
managerSpec = beforeAll $ HTTP.newManager HTTP.defaultManagerSettings
|
3c0cee1a90787578c34fda76e3fc658218d23f17c6db834b6d3d422eb8be26bd | marigold-dev/deku | producer.mli | open Deku_concepts
open Deku_protocol
type producer
type t = producer
val encoding : producer Data_encoding.t
val empty : producer
val incoming_operation : operation:Operation.Signed.t -> producer -> producer
val incoming_tezos_operation :
tezos_operation:Tezos_operation.t -> producer -> producer
(* TODO: n log n *)
val clean :
receipts:Receipt.receipt list ->
tezos_operations:Tezos_operation.tezos_operation list ->
t ->
t
val produce :
identity:Identity.t ->
default_block_size:int ->
above:Block.block ->
withdrawal_handles_hash:Deku_crypto.BLAKE2b.BLAKE2b_256.hash ->
t ->
Block.block
| null | https://raw.githubusercontent.com/marigold-dev/deku/cdf82852196b55f755f40850515580be4fd9a3fa/deku-p/src/core/consensus/producer.mli | ocaml | TODO: n log n | open Deku_concepts
open Deku_protocol
type producer
type t = producer
val encoding : producer Data_encoding.t
val empty : producer
val incoming_operation : operation:Operation.Signed.t -> producer -> producer
val incoming_tezos_operation :
tezos_operation:Tezos_operation.t -> producer -> producer
val clean :
receipts:Receipt.receipt list ->
tezos_operations:Tezos_operation.tezos_operation list ->
t ->
t
val produce :
identity:Identity.t ->
default_block_size:int ->
above:Block.block ->
withdrawal_handles_hash:Deku_crypto.BLAKE2b.BLAKE2b_256.hash ->
t ->
Block.block
|
bb82419f02dac9c136c235dbe56a7dd17c57d17ccd56515c164576e3ce312aaa | zinid/conf | conf.erl | %%%-------------------------------------------------------------------
@author < >
%%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%%% you may not use this file except in compliance with the License.
%%% You may obtain a copy of the License at
%%%
%%% -2.0
%%%
%%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%%% See the License for the specific language governing permissions and
%%% limitations under the License.
%%%
%%%-------------------------------------------------------------------
-module(conf).
-behaviour(application).
%% API
-export([start/0]).
-export([stop/0]).
-export([load_file/1]).
-export([reload_file/0]).
-export([reload_file/1]).
-export([load/1]).
-export([reload/1]).
-export([get_path/0]).
-export([format_error/1]).
%% Application callbacks
-export([start/2, stop/1, config_change/3]).
-export_type([error_reason/0, apps_config/0]).
-type backend() :: conf_yaml_backend.
-type error_reason() :: {bad_env, conf_env:error_reason()} |
{bad_ref, conf_file:ref(), conf_file:error_reason()} |
{backend(), term()}.
-type apps_config() :: [{atom(), #{atom() => term()} | {atom(), term()}}].
-callback validator() -> yval:validator().
%%%===================================================================
%%% API
%%%===================================================================
-spec load_file(file:filename_all()) -> ok | {error, error_reason()}.
load_file(Path0) ->
case prep_path(Path0) of
{ok, Path} -> read_and_load_file(Path, false);
error -> erlang:error(badarg, [Path0])
end.
-spec reload_file() -> ok | {error, error_reason()}.
reload_file() ->
case conf_env:file() of
{ok, Path} ->
reload_file(Path);
{error, Reason} ->
{error, {bad_env, Reason}}
end.
-spec reload_file(file:filename_all()) -> ok | {error, error_reason()}.
reload_file(Path0) ->
case prep_path(Path0) of
{ok, Path} -> read_and_load_file(Path, true);
error -> erlang:error(badarg, [Path0])
end.
-spec load(term()) -> ok | {error, error_reason()}.
load(Y) ->
load(Y, false).
-spec reload(term()) -> ok | {error, error_reason()}.
reload(Y) ->
load(Y, true).
-spec get_path() -> {ok, binary()} | {error, error_reason()}.
get_path() ->
case conf_env:file() of
{ok, _} = OK -> OK;
{error, Reason} -> {error, {bad_env, Reason}}
end.
-spec format_error(error_reason()) -> string().
format_error({bad_env, Reason}) ->
conf_env:format_error(Reason);
format_error({bad_ref, _Ref, Reason}) ->
conf_file:format_error(Reason);
format_error({Module, Reason}) ->
Module:format_error(Reason).
-spec start() -> ok | {error, term()}.
start() ->
case application:ensure_all_started(?MODULE) of
{ok, _} -> ok;
{error, _} = Err -> Err
end.
-spec stop() -> ok | {error, term()}.
stop() ->
application:stop(?MODULE).
%%%===================================================================
%%% Application callbacks
%%%===================================================================
-spec start(normal | {takeover, node()} | {failover, node()}, term()) ->
{ok, pid()} | {error, term()}.
start(_StartType, _StartArgs) ->
case conf_env:file() of
{ok, Path} ->
case read_and_load_file(Path, false) of
ok ->
conf_sup:start_link();
{error, Reason} = Err ->
logger:critical(
"Failed to load configuration from ~ts: ~ts",
[conf_file:format_ref(Path), format_error(Reason)]),
do_stop(Err)
end;
{error, {undefined_env, _}} ->
conf_sup:start_link();
{error, Reason} = Err ->
logger:critical("~s", [conf_env:format_error(Reason)]),
do_stop(Err)
end.
-spec stop(term()) -> ok.
stop(_State) ->
ok.
-spec config_change(Changed :: [{atom(), term()}],
New :: [{atom(), term()}],
Removed :: [atom()]) -> ok.
config_change(_Changed, _New, _Removed) ->
ok.
%%%===================================================================
Internal functions
%%%===================================================================
-spec read_and_load_file(binary(), boolean()) -> ok | {error, error_reason()}.
read_and_load_file(Path, Reload) ->
case conf_file:path_to_ref(Path) of
{error, Reason} -> {error, {bad_ref, Path, Reason}};
{ok, Ref} ->
Mimes = conf_yaml_backend:mime_types(),
case conf_file:read(Ref, Mimes) of
{error, Reason} ->
{error, {bad_ref, Ref, Reason}};
{ok, Data} ->
case conf_yaml_backend:decode(Data) of
{ok, Y} ->
load(Y, Reload);
{error, Reason} ->
{error, {conf_yaml_backend, Reason}}
end
end
end.
-spec load(term(), boolean()) -> ok | {error, error_reason()}.
load(Y, Reload) ->
case conf_yaml_backend:validate(Y) of
{ok, Config} ->
case conf_env:load(Config, Reload) of
ok -> ok;
{error, Errors} ->
report_config_change_errors(Errors)
end;
{error, Reason} ->
{error, {conf_yaml_backend, Reason}}
end.
-spec report_config_change_errors(term()) -> ok.
report_config_change_errors(Errors) when is_list(Errors) ->
Errors1 = lists:filter(
fun({module_not_defined, _}) -> false;
({application_not_found, _}) -> false;
(_) -> true
end, Errors),
lists:foreach(
fun(Error) ->
logger:warning(
"Failed to change configuration of Erlang application: ~p",
[Error])
end, Errors1);
report_config_change_errors(Error) ->
logger:warning(
"Failed to change configuration of Erlang applications: ~p",
[Error]).
-spec do_stop({error, term()}) -> {error, term()}.
do_stop({error, Reason} = Err) ->
case conf_env:on_fail() of
stop ->
Err;
OnFail ->
flush_logger(),
Status = case OnFail of
crash -> format_error(Reason);
_Halt -> 1
end,
halt(Status)
end.
-spec flush_logger() -> ok.
flush_logger() ->
lists:foreach(
fun(#{id := Name, module := Mod}) ->
case conf_misc:try_load(Mod, filesync, 1) of
{ok, _} -> Mod:filesync(Name);
_ -> ok
end
end, logger:get_handler_config()).
-spec prep_path(file:filename_all()) -> {ok, binary()} | error.
prep_path(Path) when is_binary(Path), Path /= <<>> ->
{ok, Path};
prep_path(Path) when is_list(Path), Path /= [] ->
try unicode:characters_to_binary(Path) of
Bin when is_binary(Bin) -> {ok, Bin};
_ -> error
catch _:_ ->
error
end;
prep_path(_) ->
error.
| null | https://raw.githubusercontent.com/zinid/conf/8f6b94df3584f63fbc6b241ac4ea0740a2e658fb/src/conf.erl | erlang | -------------------------------------------------------------------
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-------------------------------------------------------------------
API
Application callbacks
===================================================================
API
===================================================================
===================================================================
Application callbacks
===================================================================
===================================================================
=================================================================== | @author < >
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(conf).
-behaviour(application).
-export([start/0]).
-export([stop/0]).
-export([load_file/1]).
-export([reload_file/0]).
-export([reload_file/1]).
-export([load/1]).
-export([reload/1]).
-export([get_path/0]).
-export([format_error/1]).
-export([start/2, stop/1, config_change/3]).
-export_type([error_reason/0, apps_config/0]).
-type backend() :: conf_yaml_backend.
-type error_reason() :: {bad_env, conf_env:error_reason()} |
{bad_ref, conf_file:ref(), conf_file:error_reason()} |
{backend(), term()}.
-type apps_config() :: [{atom(), #{atom() => term()} | {atom(), term()}}].
-callback validator() -> yval:validator().
-spec load_file(file:filename_all()) -> ok | {error, error_reason()}.
load_file(Path0) ->
case prep_path(Path0) of
{ok, Path} -> read_and_load_file(Path, false);
error -> erlang:error(badarg, [Path0])
end.
-spec reload_file() -> ok | {error, error_reason()}.
reload_file() ->
case conf_env:file() of
{ok, Path} ->
reload_file(Path);
{error, Reason} ->
{error, {bad_env, Reason}}
end.
-spec reload_file(file:filename_all()) -> ok | {error, error_reason()}.
reload_file(Path0) ->
case prep_path(Path0) of
{ok, Path} -> read_and_load_file(Path, true);
error -> erlang:error(badarg, [Path0])
end.
-spec load(term()) -> ok | {error, error_reason()}.
load(Y) ->
load(Y, false).
-spec reload(term()) -> ok | {error, error_reason()}.
reload(Y) ->
load(Y, true).
-spec get_path() -> {ok, binary()} | {error, error_reason()}.
get_path() ->
case conf_env:file() of
{ok, _} = OK -> OK;
{error, Reason} -> {error, {bad_env, Reason}}
end.
-spec format_error(error_reason()) -> string().
format_error({bad_env, Reason}) ->
conf_env:format_error(Reason);
format_error({bad_ref, _Ref, Reason}) ->
conf_file:format_error(Reason);
format_error({Module, Reason}) ->
Module:format_error(Reason).
-spec start() -> ok | {error, term()}.
start() ->
case application:ensure_all_started(?MODULE) of
{ok, _} -> ok;
{error, _} = Err -> Err
end.
-spec stop() -> ok | {error, term()}.
stop() ->
application:stop(?MODULE).
-spec start(normal | {takeover, node()} | {failover, node()}, term()) ->
{ok, pid()} | {error, term()}.
start(_StartType, _StartArgs) ->
case conf_env:file() of
{ok, Path} ->
case read_and_load_file(Path, false) of
ok ->
conf_sup:start_link();
{error, Reason} = Err ->
logger:critical(
"Failed to load configuration from ~ts: ~ts",
[conf_file:format_ref(Path), format_error(Reason)]),
do_stop(Err)
end;
{error, {undefined_env, _}} ->
conf_sup:start_link();
{error, Reason} = Err ->
logger:critical("~s", [conf_env:format_error(Reason)]),
do_stop(Err)
end.
-spec stop(term()) -> ok.
stop(_State) ->
ok.
-spec config_change(Changed :: [{atom(), term()}],
New :: [{atom(), term()}],
Removed :: [atom()]) -> ok.
config_change(_Changed, _New, _Removed) ->
ok.
Internal functions
-spec read_and_load_file(binary(), boolean()) -> ok | {error, error_reason()}.
read_and_load_file(Path, Reload) ->
case conf_file:path_to_ref(Path) of
{error, Reason} -> {error, {bad_ref, Path, Reason}};
{ok, Ref} ->
Mimes = conf_yaml_backend:mime_types(),
case conf_file:read(Ref, Mimes) of
{error, Reason} ->
{error, {bad_ref, Ref, Reason}};
{ok, Data} ->
case conf_yaml_backend:decode(Data) of
{ok, Y} ->
load(Y, Reload);
{error, Reason} ->
{error, {conf_yaml_backend, Reason}}
end
end
end.
-spec load(term(), boolean()) -> ok | {error, error_reason()}.
load(Y, Reload) ->
case conf_yaml_backend:validate(Y) of
{ok, Config} ->
case conf_env:load(Config, Reload) of
ok -> ok;
{error, Errors} ->
report_config_change_errors(Errors)
end;
{error, Reason} ->
{error, {conf_yaml_backend, Reason}}
end.
-spec report_config_change_errors(term()) -> ok.
report_config_change_errors(Errors) when is_list(Errors) ->
Errors1 = lists:filter(
fun({module_not_defined, _}) -> false;
({application_not_found, _}) -> false;
(_) -> true
end, Errors),
lists:foreach(
fun(Error) ->
logger:warning(
"Failed to change configuration of Erlang application: ~p",
[Error])
end, Errors1);
report_config_change_errors(Error) ->
logger:warning(
"Failed to change configuration of Erlang applications: ~p",
[Error]).
-spec do_stop({error, term()}) -> {error, term()}.
do_stop({error, Reason} = Err) ->
case conf_env:on_fail() of
stop ->
Err;
OnFail ->
flush_logger(),
Status = case OnFail of
crash -> format_error(Reason);
_Halt -> 1
end,
halt(Status)
end.
-spec flush_logger() -> ok.
flush_logger() ->
lists:foreach(
fun(#{id := Name, module := Mod}) ->
case conf_misc:try_load(Mod, filesync, 1) of
{ok, _} -> Mod:filesync(Name);
_ -> ok
end
end, logger:get_handler_config()).
-spec prep_path(file:filename_all()) -> {ok, binary()} | error.
prep_path(Path) when is_binary(Path), Path /= <<>> ->
{ok, Path};
prep_path(Path) when is_list(Path), Path /= [] ->
try unicode:characters_to_binary(Path) of
Bin when is_binary(Bin) -> {ok, Bin};
_ -> error
catch _:_ ->
error
end;
prep_path(_) ->
error.
|
82bda09c56532f1942ddec5df5067a8c82579edde9b7999a4655af430b950b30 | ninenines/ct_helper | ct_helper_error_h.erl | Copyright ( c ) 2014 , < >
%%
%% Permission to use, copy, modify, and/or distribute this software for any
%% purpose with or without fee is hereby granted, provided that the above
%% copyright notice and this permission notice appear in all copies.
%%
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-module(ct_helper_error_h).
-behaviour(gen_event).
%% Public interface.
-export([ignore/3]).
-export([ignore/4]).
%% gen_event.
-export([init/1]).
-export([handle_event/2]).
-export([handle_call/2]).
-export([handle_info/2]).
-export([terminate/2]).
-export([code_change/3]).
%% Public interface.
%% Ignore crashes from self() occuring in M:F/A.
ignore(M, F, A) ->
ignore(self(), M, F, A).
Ignore crashes from Pid occuring in M : F / A.
ignore(Pid, M, F, A) ->
error_logger ! {expect, {Pid, M, F, A}},
ok.
%% gen_event.
init(_) ->
spawn(fun() -> error_logger:tty(false) end),
{ok, []}.
%% Ignore supervisor and progress reports.
handle_event({info_report, _, {_, progress, _}}, State) ->
{ok, State};
handle_event({info_report, _, {_, std_info, _}}, State) ->
{ok, State};
handle_event({error_report, _, {_, supervisor_report, _}}, State) ->
{ok, State};
%% Ignore gun retry failures.
handle_event({error_report, _, {_, crash_report,
[[{initial_call, {gun, init, _}}, _, _,
{error_info, {error, gone, _}}|_]|_]}},
State) ->
{ok, State};
Ignore emulator reports that are a duplicate of what Ranch gives us .
%%
%% The emulator always sends strings for errors, which makes it very
%% difficult to extract the information we need, hence the regexps.
handle_event(Event = {error, GL, {emulator, _, Msg}}, State)
when node(GL) =:= node() ->
Result = re:run(Msg,
"Error in process ([^\s]+).+? with exit value: "
".+?{stacktrace,\\[{([^,]+),([^,]+),(.+)",
[{capture, all_but_first, list}]),
case Result of
nomatch ->
write_event(Event),
{ok, State};
{match, [PidStr, MStr, FStr, Rest]} ->
A = case Rest of
"[]" ++ _ ->
0;
"[" ++ Rest2 ->
count_args(Rest2, 1, 0);
_ ->
{match, [AStr]} = re:run(Rest, "([^,]+).+",
[{capture, all_but_first, list}]),
list_to_integer(AStr)
end,
Crash = {list_to_pid(PidStr), list_to_existing_atom(MStr),
list_to_existing_atom(FStr), A},
case lists:member(Crash, State) of
true ->
{ok, lists:delete(Crash, State)};
false ->
write_event(Event),
{ok, State}
end
end;
Cowboy 2.0 : error coming from Ranch .
handle_event(Event = {error, GL,
{_, "Ranch listener" ++ _, [_, _, Pid, {_, [{M, F, A, _}|_]}]}},
State) when node(GL) =:= node() ->
A2 = if is_list(A) -> length(A); true -> A end,
Crash = {Pid, M, F, A2},
case lists:member(Crash, State) of
true ->
{ok, lists:delete(Crash, State)};
false ->
write_event(Event),
{ok, State}
end;
Cowboy 2.0 : error coming from Cowboy .
handle_event(Event = {error, GL,
{_, "Ranch listener" ++ _, [_, _, _, Pid, _, [{M, F, A, _}|_]|_]}},
State) when node(GL) =:= node() ->
A2 = if is_list(A) -> length(A); true -> A end,
Crash = {Pid, M, F, A2},
case lists:member(Crash, State) of
true ->
{ok, lists:delete(Crash, State)};
false ->
write_event(Event),
{ok, State}
end;
%% Cowboy 1.0.
handle_event(Event = {error, GL,
{_, "Ranch listener" ++ _, [_, _, _, Pid, {cowboy_handler, [_, _, _,
{stacktrace, [{M, F, A, _}|_]}|_]}]}},
State) when node(GL) =:= node() ->
A2 = if is_list(A) -> length(A); true -> A end,
Crash = {Pid, M, F, A2},
case lists:member(Crash, State) of
true ->
{ok, lists:delete(Crash, State)};
false ->
write_event(Event),
{ok, State}
end;
handle_event(Event = {_, GL, _}, State) when node(GL) =:= node() ->
write_event(Event),
{ok, State};
handle_event(_, State) ->
{ok, State}.
handle_call(_, State) ->
{ok, {error, bad_query}, State}.
handle_info({expect, Crash}, State) ->
{ok, [Crash, Crash|State]};
handle_info(_, State) ->
{ok, State}.
terminate(_, _) ->
spawn(fun() -> error_logger:tty(true) end),
ok.
code_change(_, State, _) ->
{ok, State}.
Internal .
write_event(Event) ->
_ = error_logger_tty_h:write_event(
{erlang:universaltime(), Event},
io),
ok.
count_args("]" ++ _, N, 0) ->
N;
count_args("]" ++ Tail, N, Levels) ->
count_args(Tail, N, Levels - 1);
count_args("[" ++ Tail, N, Levels) ->
count_args(Tail, N, Levels + 1);
count_args("}" ++ Tail, N, Levels) ->
count_args(Tail, N, Levels - 1);
count_args("{" ++ Tail, N, Levels) ->
count_args(Tail, N, Levels + 1);
count_args("," ++ Tail, N, Levels = 0) ->
count_args(Tail, N + 1, Levels);
count_args("," ++ Tail, N, Levels) ->
count_args(Tail, N, Levels);
count_args([_|Tail], N, Levels) ->
count_args(Tail, N, Levels).
| null | https://raw.githubusercontent.com/ninenines/ct_helper/478aa272708ed4ad282ca02bed41a5320330e8af/src/ct_helper_error_h.erl | erlang |
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
Public interface.
gen_event.
Public interface.
Ignore crashes from self() occuring in M:F/A.
gen_event.
Ignore supervisor and progress reports.
Ignore gun retry failures.
The emulator always sends strings for errors, which makes it very
difficult to extract the information we need, hence the regexps.
Cowboy 1.0. | Copyright ( c ) 2014 , < >
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
-module(ct_helper_error_h).
-behaviour(gen_event).
-export([ignore/3]).
-export([ignore/4]).
-export([init/1]).
-export([handle_event/2]).
-export([handle_call/2]).
-export([handle_info/2]).
-export([terminate/2]).
-export([code_change/3]).
ignore(M, F, A) ->
ignore(self(), M, F, A).
Ignore crashes from Pid occuring in M : F / A.
ignore(Pid, M, F, A) ->
error_logger ! {expect, {Pid, M, F, A}},
ok.
init(_) ->
spawn(fun() -> error_logger:tty(false) end),
{ok, []}.
handle_event({info_report, _, {_, progress, _}}, State) ->
{ok, State};
handle_event({info_report, _, {_, std_info, _}}, State) ->
{ok, State};
handle_event({error_report, _, {_, supervisor_report, _}}, State) ->
{ok, State};
handle_event({error_report, _, {_, crash_report,
[[{initial_call, {gun, init, _}}, _, _,
{error_info, {error, gone, _}}|_]|_]}},
State) ->
{ok, State};
Ignore emulator reports that are a duplicate of what Ranch gives us .
handle_event(Event = {error, GL, {emulator, _, Msg}}, State)
when node(GL) =:= node() ->
Result = re:run(Msg,
"Error in process ([^\s]+).+? with exit value: "
".+?{stacktrace,\\[{([^,]+),([^,]+),(.+)",
[{capture, all_but_first, list}]),
case Result of
nomatch ->
write_event(Event),
{ok, State};
{match, [PidStr, MStr, FStr, Rest]} ->
A = case Rest of
"[]" ++ _ ->
0;
"[" ++ Rest2 ->
count_args(Rest2, 1, 0);
_ ->
{match, [AStr]} = re:run(Rest, "([^,]+).+",
[{capture, all_but_first, list}]),
list_to_integer(AStr)
end,
Crash = {list_to_pid(PidStr), list_to_existing_atom(MStr),
list_to_existing_atom(FStr), A},
case lists:member(Crash, State) of
true ->
{ok, lists:delete(Crash, State)};
false ->
write_event(Event),
{ok, State}
end
end;
Cowboy 2.0 : error coming from Ranch .
handle_event(Event = {error, GL,
{_, "Ranch listener" ++ _, [_, _, Pid, {_, [{M, F, A, _}|_]}]}},
State) when node(GL) =:= node() ->
A2 = if is_list(A) -> length(A); true -> A end,
Crash = {Pid, M, F, A2},
case lists:member(Crash, State) of
true ->
{ok, lists:delete(Crash, State)};
false ->
write_event(Event),
{ok, State}
end;
Cowboy 2.0 : error coming from Cowboy .
handle_event(Event = {error, GL,
{_, "Ranch listener" ++ _, [_, _, _, Pid, _, [{M, F, A, _}|_]|_]}},
State) when node(GL) =:= node() ->
A2 = if is_list(A) -> length(A); true -> A end,
Crash = {Pid, M, F, A2},
case lists:member(Crash, State) of
true ->
{ok, lists:delete(Crash, State)};
false ->
write_event(Event),
{ok, State}
end;
handle_event(Event = {error, GL,
{_, "Ranch listener" ++ _, [_, _, _, Pid, {cowboy_handler, [_, _, _,
{stacktrace, [{M, F, A, _}|_]}|_]}]}},
State) when node(GL) =:= node() ->
A2 = if is_list(A) -> length(A); true -> A end,
Crash = {Pid, M, F, A2},
case lists:member(Crash, State) of
true ->
{ok, lists:delete(Crash, State)};
false ->
write_event(Event),
{ok, State}
end;
handle_event(Event = {_, GL, _}, State) when node(GL) =:= node() ->
write_event(Event),
{ok, State};
handle_event(_, State) ->
{ok, State}.
handle_call(_, State) ->
{ok, {error, bad_query}, State}.
handle_info({expect, Crash}, State) ->
{ok, [Crash, Crash|State]};
handle_info(_, State) ->
{ok, State}.
terminate(_, _) ->
spawn(fun() -> error_logger:tty(true) end),
ok.
code_change(_, State, _) ->
{ok, State}.
Internal .
write_event(Event) ->
_ = error_logger_tty_h:write_event(
{erlang:universaltime(), Event},
io),
ok.
count_args("]" ++ _, N, 0) ->
N;
count_args("]" ++ Tail, N, Levels) ->
count_args(Tail, N, Levels - 1);
count_args("[" ++ Tail, N, Levels) ->
count_args(Tail, N, Levels + 1);
count_args("}" ++ Tail, N, Levels) ->
count_args(Tail, N, Levels - 1);
count_args("{" ++ Tail, N, Levels) ->
count_args(Tail, N, Levels + 1);
count_args("," ++ Tail, N, Levels = 0) ->
count_args(Tail, N + 1, Levels);
count_args("," ++ Tail, N, Levels) ->
count_args(Tail, N, Levels);
count_args([_|Tail], N, Levels) ->
count_args(Tail, N, Levels).
|
f93b37c3a1d914655b679b90a69845912483d6256cfb2f574732b3d00e024d1e | binaryage/chromex | echo_private.cljs | (ns chromex.app.echo-private (:require-macros [chromex.app.echo-private :refer [gen-wrap]])
(:require [chromex.core]))
-- functions --------------------------------------------------------------------------------------------------------------
(defn set-offer-info* [config id offer-info]
(gen-wrap :function ::set-offer-info config id offer-info))
(defn get-offer-info* [config id]
(gen-wrap :function ::get-offer-info config id))
(defn get-registration-code* [config type]
(gen-wrap :function ::get-registration-code config type))
(defn get-oobe-timestamp* [config]
(gen-wrap :function ::get-oobe-timestamp config))
(defn get-user-consent* [config consent-requester]
(gen-wrap :function ::get-user-consent config consent-requester))
| null | https://raw.githubusercontent.com/binaryage/chromex/33834ba5dd4f4238a3c51f99caa0416f30c308c5/src/apps_private/chromex/app/echo_private.cljs | clojure | (ns chromex.app.echo-private (:require-macros [chromex.app.echo-private :refer [gen-wrap]])
(:require [chromex.core]))
-- functions --------------------------------------------------------------------------------------------------------------
(defn set-offer-info* [config id offer-info]
(gen-wrap :function ::set-offer-info config id offer-info))
(defn get-offer-info* [config id]
(gen-wrap :function ::get-offer-info config id))
(defn get-registration-code* [config type]
(gen-wrap :function ::get-registration-code config type))
(defn get-oobe-timestamp* [config]
(gen-wrap :function ::get-oobe-timestamp config))
(defn get-user-consent* [config consent-requester]
(gen-wrap :function ::get-user-consent config consent-requester))
| |
62e9ae001621923099d49987705553ce21abedd0c26b82dae921d4a8d37a00f7 | vii/cl-irregsexp | cl-irregsexp.lisp | #.(macrolet ((r (x) x `,x))
(r
(let ((*debug-io* (make-string-output-stream)) (*standard-output* (make-string-output-stream)))
(asdf:operate 'asdf:load-op :cl-irregsexp))))
(defun slurp-file (name)
(with-open-file (s name :element-type '(unsigned-byte 8))
(let ((buf (cl-irregsexp.bytestrings:make-byte-vector (file-length s))))
(read-sequence buf s)
buf)))
(defun find-it (buf)
(declare (optimize speed))
(cl-irregsexp:match-bind (before (or "indecipherable" "undecipherable"))
buf
(length before)))
(compile 'find-it)
(gc)
(let ((buf (slurp-file "test-data")))
(let ((len (find-it buf)))
(let ((start (get-internal-real-time)))
(loop repeat 1000 do
(assert (= len (find-it buf))))
(let ((end (get-internal-real-time)))
(format t "~A ~$~&" len (/ (- end start) internal-time-units-per-second))))))
(quit)
| null | https://raw.githubusercontent.com/vii/cl-irregsexp/cc23512d3fe2880c5df47fa96d47b352c3d5b73a/bench/cl-irregsexp.lisp | lisp | #.(macrolet ((r (x) x `,x))
(r
(let ((*debug-io* (make-string-output-stream)) (*standard-output* (make-string-output-stream)))
(asdf:operate 'asdf:load-op :cl-irregsexp))))
(defun slurp-file (name)
(with-open-file (s name :element-type '(unsigned-byte 8))
(let ((buf (cl-irregsexp.bytestrings:make-byte-vector (file-length s))))
(read-sequence buf s)
buf)))
(defun find-it (buf)
(declare (optimize speed))
(cl-irregsexp:match-bind (before (or "indecipherable" "undecipherable"))
buf
(length before)))
(compile 'find-it)
(gc)
(let ((buf (slurp-file "test-data")))
(let ((len (find-it buf)))
(let ((start (get-internal-real-time)))
(loop repeat 1000 do
(assert (= len (find-it buf))))
(let ((end (get-internal-real-time)))
(format t "~A ~$~&" len (/ (- end start) internal-time-units-per-second))))))
(quit)
| |
cf64e7742496eacf0635d317fa4414f11f467cfa803fc3920c3b12adeafbb8fa | wilkerlucio/pathom-viz-connector | pathom2.clj | (ns com.wsscode.pathom-viz.connector.demos.pathom2
(:require [com.wsscode.pathom.viz.ws-connector.core :as p.connector]
[com.wsscode.pathom.core :as p]
[com.wsscode.pathom.connect :as pc]
[com.wsscode.pathom3.connect.indexes :as pci]
[clojure.set :as set])
(:import (java.time LocalDate)))
(pc/defresolver nested [_]
{:output {:nested {:value "true"}}})
(pc/defresolver item-by-id [{:keys [item/id]}]
{:item/id id
:item/text "bar"})
(def registry
[nested
(pc/constantly-resolver :pi Math/PI)
(pc/constantly-resolver :bad (LocalDate/now))
(pc/single-attr-resolver :pi :tau #(* 2 %))
item-by-id])
(def parser
(p/parser
{::p/env {::p/reader [p/map-reader
pc/reader3
pc/open-ident-reader
p/env-placeholder-reader]
::p/placeholder-prefixes #{">"}}
::p/mutate pc/mutate
::p/plugins [(pc/connect-plugin {::pc/register registry})
p/error-handler-plugin
p/trace-plugin]}))
(def tracked-parser
(p.connector/connect-parser
{::p.connector/parser-id ::my-parser}
(fn [env tx]
(parser (assoc env :extra-connector-stuff "bla") tx))))
(comment
(parser {} [{::pc/indexes [::pc/index-io]}])
(pci/reachable-paths
#:com.wsscode.pathom3.connect.indexes{:index-io {#{:item/id} #:item{:id {}, :text {}}}}
{:item/id {}})
(tracked-parser {} [:works-here?]))
| null | https://raw.githubusercontent.com/wilkerlucio/pathom-viz-connector/d95371ef5039849e031e3bad39748d8ac8bb1cf0/examples/com/wsscode/pathom_viz/connector/demos/pathom2.clj | clojure | (ns com.wsscode.pathom-viz.connector.demos.pathom2
(:require [com.wsscode.pathom.viz.ws-connector.core :as p.connector]
[com.wsscode.pathom.core :as p]
[com.wsscode.pathom.connect :as pc]
[com.wsscode.pathom3.connect.indexes :as pci]
[clojure.set :as set])
(:import (java.time LocalDate)))
(pc/defresolver nested [_]
{:output {:nested {:value "true"}}})
(pc/defresolver item-by-id [{:keys [item/id]}]
{:item/id id
:item/text "bar"})
(def registry
[nested
(pc/constantly-resolver :pi Math/PI)
(pc/constantly-resolver :bad (LocalDate/now))
(pc/single-attr-resolver :pi :tau #(* 2 %))
item-by-id])
(def parser
(p/parser
{::p/env {::p/reader [p/map-reader
pc/reader3
pc/open-ident-reader
p/env-placeholder-reader]
::p/placeholder-prefixes #{">"}}
::p/mutate pc/mutate
::p/plugins [(pc/connect-plugin {::pc/register registry})
p/error-handler-plugin
p/trace-plugin]}))
(def tracked-parser
(p.connector/connect-parser
{::p.connector/parser-id ::my-parser}
(fn [env tx]
(parser (assoc env :extra-connector-stuff "bla") tx))))
(comment
(parser {} [{::pc/indexes [::pc/index-io]}])
(pci/reachable-paths
#:com.wsscode.pathom3.connect.indexes{:index-io {#{:item/id} #:item{:id {}, :text {}}}}
{:item/id {}})
(tracked-parser {} [:works-here?]))
| |
e2bf096cae51929cdb14bbf3e01981c5cbaccbcbdb457236b0f9f94058c0ccd3 | faylang/fay | Benchmarks.hs | # LANGUAGE NoImplicitPrelude #
| The benchmarks suite . This code is written in . Which may skew
-- results, but probably not.
--
-- There's a set of benchmarks in main that are run, or you can choose
-- to run just one.
--
-- For a given benchmark it will run them a few times then calculate
the mean , min , and stddev of them , which should give an
-- accurate enough picture of the performance differences, for the
-- kind of speed differences that we care about at present.
--
-- Run me like this:
dist / build / fay / fay src / Benchmarks.hs --no - ghc & & node src /
module Benchmarks where
import FFI
import Prelude
--------------------------------------------------------------------------------
-- Main entry point
main :: Fay ()
main = do
sumBenchmark
lengthBenchmark
queensBenchmark
--------------------------------------------------------------------------------
-- Benchmarks
-- | Benchmark a simple tail-recursive function.
sumBenchmark :: Fay ()
sumBenchmark = runAndSummarize "sum 1000000 0" $ benchmark 5 (sum' 10000000 0)
-- A simple tail-recursive O(n) summing function.
sum' :: Double -> Double -> Double
sum' 0 acc = acc
sum' n acc = let i = (acc + n) in seq i (sum' (n - 1) i)
-- | Benchmark a simple tail-recursive function walking a list.
lengthBenchmark :: Fay ()
lengthBenchmark = do
let a = [1..1000000]
echo "Forcing the list ..."
length a `seq` return False
runAndSummarize "length [1..1000000]" $ benchmark 5 (length a)
-- | Benchmark the n-queens problem.
queensBenchmark :: Fay ()
queensBenchmark =
runAndSummarize "nqueens 11" $ benchmark 1 (nqueens 11)
-- | Solve the n-queens problem for nq.
nqueens :: Int -> Int
nqueens nq = length (gen nq) where
gen 0 = [[]]
gen n = concatMap (\bs -> map (: bs)
(filter (\q -> safe q 1 bs) nqs))
(gen (n-1))
nqs = [1..nq]
safe x d (q:l) = ((x /= q) && (x /= (q + d)) && (x /= (q - d))) && safe x (d + 1) l
safe _ _ _ = True
--------------------------------------------------------------------------------
Mini benchmarking library
-- | Run a benchmark and summarize the results.
runAndSummarize :: String -> Fay [Double] -> Fay ()
runAndSummarize label m = do
echo $ "Running benchmark “" ++ label ++ "” ..."
results <- m
echo $ "Results: " ++ unwords (map (\x -> show x ++ "ms") results)
echo $ "Mean " ++ show (mean results) ++ "ms, " ++
"Min " ++ show (minimum results) ++ "ms, " ++
"Max " ++ show (maximum results) ++ "ms, " ++
"Stddev " ++ show (stddev results) ++
"\n"
-- | Benchmark a double value.
benchmark :: Double -> a -> Fay [Double]
benchmark benchmarks a = do
echo "Recording ..."
go a 0 []
where
go a count results = do
start <- getSeconds
a `seq` return True
end <- getSeconds
if count == benchmarks
then return results
else go a (count+1) ((end-start) : results)
--------------------------------------------------------------------------------
-- Utility functions
-- unwords :: [String] -> String
-- unwords = intercalate " "
mean :: [Double] -> Double
mean xs = foldl' (+) 0 xs / fromIntegral (length xs)
stddev :: [Double] -> Double
stddev xs = let tmean = mean xs
in sqrt (mean (map (\x -> square (x - tmean)) xs))
-- sqrt :: Double -> Double
-- sqrt = ffi "Math.sqrt(%1)"
-- maximum :: [Double] -> Double
maximum ( x : xs ) = foldl max x xs
maximum _ = 0
-- minimum :: [Double] -> Double
minimum ( x : xs ) = foldl min x xs
minimum _ = 0
square :: Double -> Double
square x = x * x
echo :: String -> Fay ()
echo = ffi "console.log(%1)"
getSeconds :: Fay Double
getSeconds = ffi "new Date()"
| null | https://raw.githubusercontent.com/faylang/fay/8455d975f9f0db2ecc922410e43e484fbd134699/src/Benchmarks.hs | haskell | results, but probably not.
There's a set of benchmarks in main that are run, or you can choose
to run just one.
For a given benchmark it will run them a few times then calculate
accurate enough picture of the performance differences, for the
kind of speed differences that we care about at present.
Run me like this:
no - ghc & & node src /
------------------------------------------------------------------------------
Main entry point
------------------------------------------------------------------------------
Benchmarks
| Benchmark a simple tail-recursive function.
A simple tail-recursive O(n) summing function.
| Benchmark a simple tail-recursive function walking a list.
| Benchmark the n-queens problem.
| Solve the n-queens problem for nq.
------------------------------------------------------------------------------
| Run a benchmark and summarize the results.
| Benchmark a double value.
------------------------------------------------------------------------------
Utility functions
unwords :: [String] -> String
unwords = intercalate " "
sqrt :: Double -> Double
sqrt = ffi "Math.sqrt(%1)"
maximum :: [Double] -> Double
minimum :: [Double] -> Double | # LANGUAGE NoImplicitPrelude #
| The benchmarks suite . This code is written in . Which may skew
the mean , min , and stddev of them , which should give an
module Benchmarks where
import FFI
import Prelude
main :: Fay ()
main = do
sumBenchmark
lengthBenchmark
queensBenchmark
sumBenchmark :: Fay ()
sumBenchmark = runAndSummarize "sum 1000000 0" $ benchmark 5 (sum' 10000000 0)
sum' :: Double -> Double -> Double
sum' 0 acc = acc
sum' n acc = let i = (acc + n) in seq i (sum' (n - 1) i)
lengthBenchmark :: Fay ()
lengthBenchmark = do
let a = [1..1000000]
echo "Forcing the list ..."
length a `seq` return False
runAndSummarize "length [1..1000000]" $ benchmark 5 (length a)
queensBenchmark :: Fay ()
queensBenchmark =
runAndSummarize "nqueens 11" $ benchmark 1 (nqueens 11)
nqueens :: Int -> Int
nqueens nq = length (gen nq) where
gen 0 = [[]]
gen n = concatMap (\bs -> map (: bs)
(filter (\q -> safe q 1 bs) nqs))
(gen (n-1))
nqs = [1..nq]
safe x d (q:l) = ((x /= q) && (x /= (q + d)) && (x /= (q - d))) && safe x (d + 1) l
safe _ _ _ = True
Mini benchmarking library
runAndSummarize :: String -> Fay [Double] -> Fay ()
runAndSummarize label m = do
echo $ "Running benchmark “" ++ label ++ "” ..."
results <- m
echo $ "Results: " ++ unwords (map (\x -> show x ++ "ms") results)
echo $ "Mean " ++ show (mean results) ++ "ms, " ++
"Min " ++ show (minimum results) ++ "ms, " ++
"Max " ++ show (maximum results) ++ "ms, " ++
"Stddev " ++ show (stddev results) ++
"\n"
benchmark :: Double -> a -> Fay [Double]
benchmark benchmarks a = do
echo "Recording ..."
go a 0 []
where
go a count results = do
start <- getSeconds
a `seq` return True
end <- getSeconds
if count == benchmarks
then return results
else go a (count+1) ((end-start) : results)
mean :: [Double] -> Double
mean xs = foldl' (+) 0 xs / fromIntegral (length xs)
stddev :: [Double] -> Double
stddev xs = let tmean = mean xs
in sqrt (mean (map (\x -> square (x - tmean)) xs))
maximum ( x : xs ) = foldl max x xs
maximum _ = 0
minimum ( x : xs ) = foldl min x xs
minimum _ = 0
square :: Double -> Double
square x = x * x
echo :: String -> Fay ()
echo = ffi "console.log(%1)"
getSeconds :: Fay Double
getSeconds = ffi "new Date()"
|
5e653b0ae802f01ce02513d8128de0ec28901780c1ff893c9df0507efa6344f2 | huangz1990/SICP-answers | p214-exchange.scm | ;;; p214-exchange.scm
(define (exchange account1 account2)
(let ((difference (- (account1 'balance)
(account2 'balance))))
((account1 'withdraw) difference)
((account2 'deposit) difference)))
| null | https://raw.githubusercontent.com/huangz1990/SICP-answers/15e3475003ef10eb738cf93c1932277bc56bacbe/chp3/code/p214-exchange.scm | scheme | p214-exchange.scm |
(define (exchange account1 account2)
(let ((difference (- (account1 'balance)
(account2 'balance))))
((account1 'withdraw) difference)
((account2 'deposit) difference)))
|
5a9b232addb2a6a55f38f501b4ef3e5ae690c4de0568a4dd31e889ee7c0e7151 | jordanthayer/ocaml-search | scanalyzer_main.ml | * The main program for the scanalyzer domain .
@author eaburns
@since 2011 - 02 - 28
@author eaburns
@since 2011-02-28
*)
open Printf
let verb = ref Verb.always
let limit = ref []
let other_args = ref [ "pad... apparently" ]
let run_algorithm ?(limit=[]) alg inst =
let (sol_opt, e, g, p, q, d), t = Wrsys.with_time (alg inst limit) in
begin match sol_opt with
| None ->
Datafile.write_pairs stdout
[ "found solution", "no";
"final sol cost", "infinity";
"final sol length", "-1"; ]
| Some (goal_node, cost) ->
Datafile.write_pairs stdout
[ "found solution", "yes";
"final sol cost", string_of_float cost;
" final sol length " , string_of_int ( path ) ;
end;
let mem = Wrsys.get_proc_status [| "VmPeak:" |] (Unix.getpid ()) in
Datafile.write_pairs stdout
([ "total raw cpu time", string_of_float t;
"peak virtual mem usage kb", mem.(0);
"number of duplicates found", string_of_int d;
"total nodes expanded", string_of_int e;
"total nodes generated", string_of_int g; ]
@ (Limit.to_trailpairs limit))
let parse_args () =
(** [parse_args ()] parses the arguments. *)
let arg_spec =
[
"-v", Arg.Set_int verb, (sprintf "Verbosity level (default: %d)" !verb);
] @ (Limit.arg_specs limit)
in
let usage_str =
"sliding-tiles [-v <verb>] [-c <cost>] " ^ Limit.usage_string
in
Arg.parse arg_spec (fun s -> other_args := s :: !other_args) usage_str;
other_args := List.rev !other_args
let get_algorithm () =
(** [algorithm_by_name ()] gets the algorithm (arg count and
function) by its name. *)
let args = Array.of_list !other_args in
let alg_name = args.(1) in
let make_iface = Scanalyzer_interfaces.default_interface in
let sol_handler = Fn.identity in
let argc, alg_fun =
Wrlist.get_entry (Alg_table_dups.table @ Alg_table_dd.table)
"alg" alg_name in
let expt_nargs = argc - 1 and got_nargs = Array.length args - 2 in
if expt_nargs <> got_nargs then
failwith (sprintf "Expected %d arguments, got %d" expt_nargs got_nargs);
let alg_args = if argc > 1 then Array.sub args 1 argc else [| |] in
Alg_initializers.string_array_init alg_fun sol_handler make_iface
alg_args
let main () =
parse_args ();
Verb.with_level !verb
(fun () ->
let alg = get_algorithm () in
let inst = Scanalyzer_inst.read stdin in
run_algorithm ~limit:!limit alg inst)
let _ = main ()
| null | https://raw.githubusercontent.com/jordanthayer/ocaml-search/57cfc85417aa97ee5d8fbcdb84c333aae148175f/scanalyzer/scanalyzer_main.ml | ocaml | * [parse_args ()] parses the arguments.
* [algorithm_by_name ()] gets the algorithm (arg count and
function) by its name. | * The main program for the scanalyzer domain .
@author eaburns
@since 2011 - 02 - 28
@author eaburns
@since 2011-02-28
*)
open Printf
let verb = ref Verb.always
let limit = ref []
let other_args = ref [ "pad... apparently" ]
let run_algorithm ?(limit=[]) alg inst =
let (sol_opt, e, g, p, q, d), t = Wrsys.with_time (alg inst limit) in
begin match sol_opt with
| None ->
Datafile.write_pairs stdout
[ "found solution", "no";
"final sol cost", "infinity";
"final sol length", "-1"; ]
| Some (goal_node, cost) ->
Datafile.write_pairs stdout
[ "found solution", "yes";
"final sol cost", string_of_float cost;
" final sol length " , string_of_int ( path ) ;
end;
let mem = Wrsys.get_proc_status [| "VmPeak:" |] (Unix.getpid ()) in
Datafile.write_pairs stdout
([ "total raw cpu time", string_of_float t;
"peak virtual mem usage kb", mem.(0);
"number of duplicates found", string_of_int d;
"total nodes expanded", string_of_int e;
"total nodes generated", string_of_int g; ]
@ (Limit.to_trailpairs limit))
let parse_args () =
let arg_spec =
[
"-v", Arg.Set_int verb, (sprintf "Verbosity level (default: %d)" !verb);
] @ (Limit.arg_specs limit)
in
let usage_str =
"sliding-tiles [-v <verb>] [-c <cost>] " ^ Limit.usage_string
in
Arg.parse arg_spec (fun s -> other_args := s :: !other_args) usage_str;
other_args := List.rev !other_args
let get_algorithm () =
let args = Array.of_list !other_args in
let alg_name = args.(1) in
let make_iface = Scanalyzer_interfaces.default_interface in
let sol_handler = Fn.identity in
let argc, alg_fun =
Wrlist.get_entry (Alg_table_dups.table @ Alg_table_dd.table)
"alg" alg_name in
let expt_nargs = argc - 1 and got_nargs = Array.length args - 2 in
if expt_nargs <> got_nargs then
failwith (sprintf "Expected %d arguments, got %d" expt_nargs got_nargs);
let alg_args = if argc > 1 then Array.sub args 1 argc else [| |] in
Alg_initializers.string_array_init alg_fun sol_handler make_iface
alg_args
let main () =
parse_args ();
Verb.with_level !verb
(fun () ->
let alg = get_algorithm () in
let inst = Scanalyzer_inst.read stdin in
run_algorithm ~limit:!limit alg inst)
let _ = main ()
|
46cfa99f36a6cad7f9bc3a27443d744540daabe3f344688f675ecb5c4ad3515b | iloveponies/training-day | project.clj | (defproject training-day "1.0.0-SNAPSHOT"
:dependencies [[org.clojure/clojure "1.10.0"]
[iloveponies.tests/training-day "0.2.0-SNAPSHOT"]]
:profiles {:dev {:plugins [[lein-midje "3.2.1"]]}})
| null | https://raw.githubusercontent.com/iloveponies/training-day/fa692c550965ab9a3e6205a8a4a30071581bb6cc/project.clj | clojure | (defproject training-day "1.0.0-SNAPSHOT"
:dependencies [[org.clojure/clojure "1.10.0"]
[iloveponies.tests/training-day "0.2.0-SNAPSHOT"]]
:profiles {:dev {:plugins [[lein-midje "3.2.1"]]}})
| |
ba465342276683f02e47c85fa630282533b24226be52869b6b7509e4627275ff | links-lang/links | lens_map.mli | module type OrderedShow = sig
type t [@@deriving show]
include Map.OrderedType with type t := t
end
module type S = Lens_map_intf.S
module Make (Ord : OrderedShow) : S with type key = Ord.t
| null | https://raw.githubusercontent.com/links-lang/links/2923893c80677b67cacc6747a25b5bcd65c4c2b6/lens/lens_map.mli | ocaml | module type OrderedShow = sig
type t [@@deriving show]
include Map.OrderedType with type t := t
end
module type S = Lens_map_intf.S
module Make (Ord : OrderedShow) : S with type key = Ord.t
| |
b4af331e3de0c348e1a85d45672212105020f02b3f73fc022d531186da88098a | bhauman/advent-of-clojure | day14.clj | (ns advent-2015.day14
(:require
[clojure.java.io :as io]
[clojure.string :as string]))
(def prob14 (line-seq (io/reader (io/resource "2015/prob14"))))
(defn line-to-data [line]
(map read-string (re-seq #"\d+" line)))
(def reindeer (map line-to-data prob14))
(defn traveled [[speed travel restt] seconds]
(let [period (+ travel restt)]
(+ (* travel speed (int (/ seconds period)))
(let [finalp (rem seconds period)]
(if (> travel finalp)
(* speed finalp)
(* speed travel))))))
part 1
#_(reduce max (map #(traveled % 2503) reindeer))
(defn winners [reindeer seconds]
(let [res (apply merge-with concat
(map
#(hash-map (traveled % seconds) [%])
reindeer))]
(get res (apply max (keys res)))))
part 2
#_(reduce max
(vals
(frequencies
(mapcat (partial winners reindeer)
(range 1 (inc 2503))))))
| null | https://raw.githubusercontent.com/bhauman/advent-of-clojure/856763baf45bf7bf452ffd304dc1b89f9bc879a6/src/advent-2015/day14.clj | clojure | (ns advent-2015.day14
(:require
[clojure.java.io :as io]
[clojure.string :as string]))
(def prob14 (line-seq (io/reader (io/resource "2015/prob14"))))
(defn line-to-data [line]
(map read-string (re-seq #"\d+" line)))
(def reindeer (map line-to-data prob14))
(defn traveled [[speed travel restt] seconds]
(let [period (+ travel restt)]
(+ (* travel speed (int (/ seconds period)))
(let [finalp (rem seconds period)]
(if (> travel finalp)
(* speed finalp)
(* speed travel))))))
part 1
#_(reduce max (map #(traveled % 2503) reindeer))
(defn winners [reindeer seconds]
(let [res (apply merge-with concat
(map
#(hash-map (traveled % seconds) [%])
reindeer))]
(get res (apply max (keys res)))))
part 2
#_(reduce max
(vals
(frequencies
(mapcat (partial winners reindeer)
(range 1 (inc 2503))))))
| |
e9959c5218906523e7a1b45142006c60a0f1daa360c5677be140ab72abb98907 | janestreet/hardcaml | cyclesim.ml | open Base
include Cyclesim_intf
types defined in Cyclesim0 .
module Port_list = Cyclesim0.Port_list
module Private = Cyclesim0.Private
module Digest = Cyclesim0.Digest
type t_port_list = Cyclesim0.t_port_list
type ('i, 'o) t = ('i, 'o) Cyclesim0.t [@@deriving sexp_of]
let internal_ports = Cyclesim0.internal_ports
let in_ports = Cyclesim0.in_ports
let inputs = Cyclesim0.inputs
let digest t = Cyclesim0.digest t
let lookup_reg = Cyclesim0.lookup_reg
let lookup_mem = Cyclesim0.lookup_mem
module Violated_or_not = struct
type t =
| Violated of int list
| Not_violated
[@@deriving sexp_of]
end
let results_of_assertions (t : _ t) =
Map.mapi t.assertions ~f:(fun ~key ~data:_ ->
match Hashtbl.find t.violated_assertions key with
| Some cycles -> Violated_or_not.Violated (List.rev cycles)
| None -> Violated_or_not.Not_violated)
;;
module Config = Cyclesim0.Config
let circuit (sim : _ t) = sim.circuit
let cycle_check (sim : _ t) = sim.cycle_check ()
let cycle_before_clock_edge (sim : _ t) = sim.cycle_before_clock_edge ()
let cycle_at_clock_edge (sim : _ t) = sim.cycle_at_clock_edge ()
let cycle_after_clock_edge (sim : _ t) = sim.cycle_after_clock_edge ()
let reset (sim : _ t) = sim.reset ()
let cycle sim =
cycle_check sim;
cycle_before_clock_edge sim;
cycle_at_clock_edge sim;
cycle_after_clock_edge sim
;;
let in_port (sim : _ Cyclesim0.t) name =
try List.Assoc.find_exn sim.in_ports name ~equal:String.equal with
| _ -> raise_s [%message "Couldn't find input port" name]
;;
let internal_port (sim : _ Cyclesim0.t) name =
try List.Assoc.find_exn sim.internal_ports name ~equal:String.equal with
| _ -> raise_s [%message "Couldn't find internal port" name]
;;
let out_port_after_clock_edge (sim : _ Cyclesim0.t) name =
try List.Assoc.find_exn sim.out_ports_after_clock_edge name ~equal:String.equal with
| _ -> raise_s [%message "Couldn't find output port" name]
;;
let out_port_before_clock_edge (sim : _ Cyclesim0.t) name =
try List.Assoc.find_exn sim.out_ports_before_clock_edge name ~equal:String.equal with
| _ -> raise_s [%message "Couldn't find output port" name]
;;
let out_port ?(clock_edge = Side.After) t name =
match clock_edge with
| Before -> out_port_before_clock_edge t name
| After -> out_port_after_clock_edge t name
;;
let out_ports ?(clock_edge = Side.After) (t : _ t) =
match clock_edge with
| Before -> t.out_ports_before_clock_edge
| After -> t.out_ports_after_clock_edge
;;
let outputs ?(clock_edge = Side.After) (t : _ t) =
match clock_edge with
| Before -> t.outputs_before_clock_edge
| After -> t.outputs_after_clock_edge
;;
Cyclesim_combine
module Combine_error = Cyclesim_combine.Combine_error
let combine = Cyclesim_combine.combine
(* compilation *)
let create = Cyclesim_compile.create
(* interfaces *)
module With_interface (I : Interface.S) (O : Interface.S) = struct
type nonrec t = (Bits.t ref I.t, Bits.t ref O.t) t [@@deriving sexp_of]
module C = Circuit.With_interface (I) (O)
let coerce sim =
let find_port ports (name, width) =
match List.Assoc.find ports name ~equal:String.equal with
| Some x -> x
| None -> ref (Bits.zero width)
in
let to_input ports = I.map I.t ~f:(find_port ports) in
let to_output ports = O.map O.t ~f:(find_port ports) in
Private.coerce sim ~to_input ~to_output
;;
let create ?config ?circuit_config create_fn =
let circuit = C.create_exn ?config:circuit_config ~name:"simulator" create_fn in
let sim = create ?config circuit in
coerce sim
;;
end
| null | https://raw.githubusercontent.com/janestreet/hardcaml/a9b1880ca2fb1a566eac66d935cacf344ec76b13/src/cyclesim.ml | ocaml | compilation
interfaces | open Base
include Cyclesim_intf
types defined in Cyclesim0 .
module Port_list = Cyclesim0.Port_list
module Private = Cyclesim0.Private
module Digest = Cyclesim0.Digest
type t_port_list = Cyclesim0.t_port_list
type ('i, 'o) t = ('i, 'o) Cyclesim0.t [@@deriving sexp_of]
let internal_ports = Cyclesim0.internal_ports
let in_ports = Cyclesim0.in_ports
let inputs = Cyclesim0.inputs
let digest t = Cyclesim0.digest t
let lookup_reg = Cyclesim0.lookup_reg
let lookup_mem = Cyclesim0.lookup_mem
module Violated_or_not = struct
type t =
| Violated of int list
| Not_violated
[@@deriving sexp_of]
end
let results_of_assertions (t : _ t) =
Map.mapi t.assertions ~f:(fun ~key ~data:_ ->
match Hashtbl.find t.violated_assertions key with
| Some cycles -> Violated_or_not.Violated (List.rev cycles)
| None -> Violated_or_not.Not_violated)
;;
module Config = Cyclesim0.Config
let circuit (sim : _ t) = sim.circuit
let cycle_check (sim : _ t) = sim.cycle_check ()
let cycle_before_clock_edge (sim : _ t) = sim.cycle_before_clock_edge ()
let cycle_at_clock_edge (sim : _ t) = sim.cycle_at_clock_edge ()
let cycle_after_clock_edge (sim : _ t) = sim.cycle_after_clock_edge ()
let reset (sim : _ t) = sim.reset ()
let cycle sim =
cycle_check sim;
cycle_before_clock_edge sim;
cycle_at_clock_edge sim;
cycle_after_clock_edge sim
;;
let in_port (sim : _ Cyclesim0.t) name =
try List.Assoc.find_exn sim.in_ports name ~equal:String.equal with
| _ -> raise_s [%message "Couldn't find input port" name]
;;
let internal_port (sim : _ Cyclesim0.t) name =
try List.Assoc.find_exn sim.internal_ports name ~equal:String.equal with
| _ -> raise_s [%message "Couldn't find internal port" name]
;;
let out_port_after_clock_edge (sim : _ Cyclesim0.t) name =
try List.Assoc.find_exn sim.out_ports_after_clock_edge name ~equal:String.equal with
| _ -> raise_s [%message "Couldn't find output port" name]
;;
let out_port_before_clock_edge (sim : _ Cyclesim0.t) name =
try List.Assoc.find_exn sim.out_ports_before_clock_edge name ~equal:String.equal with
| _ -> raise_s [%message "Couldn't find output port" name]
;;
let out_port ?(clock_edge = Side.After) t name =
match clock_edge with
| Before -> out_port_before_clock_edge t name
| After -> out_port_after_clock_edge t name
;;
let out_ports ?(clock_edge = Side.After) (t : _ t) =
match clock_edge with
| Before -> t.out_ports_before_clock_edge
| After -> t.out_ports_after_clock_edge
;;
let outputs ?(clock_edge = Side.After) (t : _ t) =
match clock_edge with
| Before -> t.outputs_before_clock_edge
| After -> t.outputs_after_clock_edge
;;
Cyclesim_combine
module Combine_error = Cyclesim_combine.Combine_error
let combine = Cyclesim_combine.combine
let create = Cyclesim_compile.create
module With_interface (I : Interface.S) (O : Interface.S) = struct
type nonrec t = (Bits.t ref I.t, Bits.t ref O.t) t [@@deriving sexp_of]
module C = Circuit.With_interface (I) (O)
let coerce sim =
let find_port ports (name, width) =
match List.Assoc.find ports name ~equal:String.equal with
| Some x -> x
| None -> ref (Bits.zero width)
in
let to_input ports = I.map I.t ~f:(find_port ports) in
let to_output ports = O.map O.t ~f:(find_port ports) in
Private.coerce sim ~to_input ~to_output
;;
let create ?config ?circuit_config create_fn =
let circuit = C.create_exn ?config:circuit_config ~name:"simulator" create_fn in
let sim = create ?config circuit in
coerce sim
;;
end
|
e2f9c9de8e0d907bd29d3e2855204c7dd51d87186c89870eae539cbd1a53c924 | Enecuum/Node | IO.hs | # LANGUAGE NoImplicitPrelude #
{-# LANGUAGE GADTs #-}
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE FlexibleInstances #
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE DataKinds #-}
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ScopedTypeVariables #-}
# OPTIONS_GHC -fno - warn - orphans #
module Enecuum.Core.HGraph.Interpreters.IO
( interpretHGraphLIO
, runHGraphLIO
, runHGraphIO
) where
import Universum
import Data.Serialize
import Control.Monad.Free
import qualified Enecuum.Core.HGraph.Internal.Impl as Impl
import Data.HGraph.StringHashable (StringHashable)
import Enecuum.Core.HGraph.Language (HGraphF (..), HGraphL)
import Enecuum.Core.HGraph.Internal.Types (TNodeL)
import Enecuum.Core.HGraph.Types
-- | The interpreter of the language describing the action on graphs.
interpretHGraphLIO :: (Serialize c, StringHashable c) => TGraph c -> HGraphF (TNodeL c) a -> IO a
-- create a new node
interpretHGraphLIO graph (NewNode x next) = next <$> atomically (Impl.newNode graph x)
-- get node by hash, content or ref
interpretHGraphLIO graph (GetNode x next) = do
node <- atomically $ Impl.getNode graph x
pure $ next node
-- delete node by hash, content or ref
interpretHGraphLIO graph (DeleteNode x next) = do
ok <- atomically $ Impl.deleteNode graph x
pure $ next ok
-- create new link by contents, hashes or refs of the node
interpretHGraphLIO graph (NewLink x y next) = do
ok <- atomically $ Impl.newLink graph x y
pure $ next ok
-- delete link inter a nodes by contents, hashes or refs of the node
interpretHGraphLIO graph (DeleteLink x y next) = do
ok <- atomically $ Impl.deleteLink graph x y
pure $ next ok
interpretHGraphLIO graph (ClearGraph next) = do
atomically $ Impl.clearGraph graph
pure $ next ()
-- | Run H graph interpret.
runHGraphLIO, runHGraphIO :: (Serialize c, StringHashable c) => TGraph c -> HGraphL c w -> IO w
runHGraphLIO graph = foldFree (interpretHGraphLIO graph)
-- | Run H graph interpret in IO monad.
runHGraphIO = runHGraphLIO
| null | https://raw.githubusercontent.com/Enecuum/Node/3dfbc6a39c84bd45dd5f4b881e067044dde0153a/src/Enecuum/Core/HGraph/Interpreters/IO.hs | haskell | # LANGUAGE GADTs #
# LANGUAGE FlexibleContexts #
# LANGUAGE TypeOperators #
# LANGUAGE DataKinds #
# LANGUAGE TypeFamilies #
# LANGUAGE ScopedTypeVariables #
| The interpreter of the language describing the action on graphs.
create a new node
get node by hash, content or ref
delete node by hash, content or ref
create new link by contents, hashes or refs of the node
delete link inter a nodes by contents, hashes or refs of the node
| Run H graph interpret.
| Run H graph interpret in IO monad. | # LANGUAGE NoImplicitPrelude #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# OPTIONS_GHC -fno - warn - orphans #
module Enecuum.Core.HGraph.Interpreters.IO
( interpretHGraphLIO
, runHGraphLIO
, runHGraphIO
) where
import Universum
import Data.Serialize
import Control.Monad.Free
import qualified Enecuum.Core.HGraph.Internal.Impl as Impl
import Data.HGraph.StringHashable (StringHashable)
import Enecuum.Core.HGraph.Language (HGraphF (..), HGraphL)
import Enecuum.Core.HGraph.Internal.Types (TNodeL)
import Enecuum.Core.HGraph.Types
interpretHGraphLIO :: (Serialize c, StringHashable c) => TGraph c -> HGraphF (TNodeL c) a -> IO a
interpretHGraphLIO graph (NewNode x next) = next <$> atomically (Impl.newNode graph x)
interpretHGraphLIO graph (GetNode x next) = do
node <- atomically $ Impl.getNode graph x
pure $ next node
interpretHGraphLIO graph (DeleteNode x next) = do
ok <- atomically $ Impl.deleteNode graph x
pure $ next ok
interpretHGraphLIO graph (NewLink x y next) = do
ok <- atomically $ Impl.newLink graph x y
pure $ next ok
interpretHGraphLIO graph (DeleteLink x y next) = do
ok <- atomically $ Impl.deleteLink graph x y
pure $ next ok
interpretHGraphLIO graph (ClearGraph next) = do
atomically $ Impl.clearGraph graph
pure $ next ()
runHGraphLIO, runHGraphIO :: (Serialize c, StringHashable c) => TGraph c -> HGraphL c w -> IO w
runHGraphLIO graph = foldFree (interpretHGraphLIO graph)
runHGraphIO = runHGraphLIO
|
11f9e411923eb1e52f875147534fdde48ba4cf7107943ff0fce99f2fe8ef7ca1 | mirage/irmin | irmin_mirage_git.ml |
* Copyright ( c ) 2013 - 2022 < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (c) 2013-2022 Thomas Gazagnaire <>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
open Lwt.Infix
include Irmin_mirage_git_intf
let remote ?(ctx = Mimic.empty) ?headers uri =
let ( ! ) f a b = f b a in
match Smart_git.Endpoint.of_string uri with
| Ok edn ->
let edn =
Option.fold ~none:edn
~some:(!Smart_git.Endpoint.with_headers_if_http edn)
headers
in
(ctx, edn)
| Error (`Msg err) -> Fmt.invalid_arg "remote: %s" err
module Maker (G : Irmin_git.G) = struct
type endpoint = Mimic.ctx * Smart_git.Endpoint.t
module Maker = Irmin_git.Maker (G) (Git.Mem.Sync (G))
module Make
(S : Irmin_git.Schema.S
with type Hash.t = G.hash
and type Node.t = G.Value.Tree.t
and type Commit.t = G.Value.Commit.t) =
struct
include Maker.Make (S)
let remote ?ctx ?headers uri = E (remote ?ctx ?headers uri)
end
end
module Ref (G : Irmin_git.G) = struct
module Maker = Irmin_git.Ref (G) (Git.Mem.Sync (G))
module G = G
type branch = Maker.branch
type endpoint = Maker.endpoint
module Make (C : Irmin.Contents.S) = struct
include Maker.Make (C)
let remote ?ctx ?headers uri = E (remote ?ctx ?headers uri)
end
end
module KV (G : Irmin_git.G) = struct
module Maker = Irmin_git.KV (G) (Git.Mem.Sync (G))
module G = G
type endpoint = Maker.endpoint
type branch = Maker.branch
module Make (C : Irmin.Contents.S) = struct
include Maker.Make (C)
let remote ?ctx ?headers uri = E (remote ?ctx ?headers uri)
end
end
module KV_RO (G : Git.S) = struct
module Key = Mirage_kv.Key
type key = Key.t
module G = struct
include G
let v ?dotgit:_ _root = assert false
end
module Maker = KV (G)
module S = Maker.Make (Irmin.Contents.String)
module Sync = Irmin.Sync.Make (S)
let disconnect _ = Lwt.return_unit
type error = [ Mirage_kv.error | S.write_error ]
let pp_error ppf = function
| #Mirage_kv.error as e -> Mirage_kv.pp_error ppf e
| #S.write_error as e -> Irmin.Type.pp S.write_error_t ppf e
let err e : ('a, error) result = Error e
let err_not_found k = err (`Not_found k)
let path x =
XXX(samoht ): we should probably just push the Key module in
Irmin and remove the path abstraction completely ...
Irmin and remove the path abstraction completely ... *)
Key.segments x
module Tree = struct
type t = { repo : S.repo; tree : S.tree }
let digest t key =
S.Tree.find_tree t.tree (path key) >|= function
| None -> err_not_found key
| Some tree ->
let h = S.Tree.hash tree in
Ok (Irmin.Type.to_string S.Hash.t h)
let list t key =
S.Tree.list t.tree (path key) >|= fun l ->
let l =
List.map
(fun (s, k) ->
( s,
match S.Tree.destruct k with
| `Contents _ -> `Value
| `Node _ -> `Dictionary ))
l
in
Ok l
let exists t key =
S.Tree.kind t.tree (path key) >|= function
| Some `Contents -> Ok (Some `Value)
| Some `Node -> Ok (Some `Dictionary)
| None -> Ok None
let get t key =
S.Tree.find t.tree (path key) >|= function
| None -> err_not_found key
| Some v -> Ok v
end
type t = { root : S.path; t : S.t }
let head_message t =
S.Head.find t.t >|= function
| None -> "empty HEAD"
| Some h ->
let info = S.Commit.info h in
Fmt.str "commit: %a\nAuthor: %s\nDate: %Ld\n\n%s\n" S.Commit.pp_hash h
(S.Info.author info) (S.Info.date info) (S.Info.message info)
let last_modified t key =
let key' = path key in
S.last_modified t.t key' >|= function
| [] -> Error (`Not_found key)
| h :: _ -> Ok (0, S.Info.date (S.Commit.info h))
let connect ?depth ?(branch = "main") ?(root = Mirage_kv.Key.empty) ?ctx
?headers t uri =
let remote = S.remote ?ctx ?headers uri in
let head = Git.Reference.v ("refs/heads/" ^ branch) in
S.repo_of_git ~bare:true ~head t >>= fun repo ->
S.of_branch repo branch >>= fun t ->
Sync.pull_exn t ?depth remote `Set >|= fun _ ->
let root = path root in
{ t; root }
let tree t =
let repo = S.repo t.t in
(S.find_tree t.t t.root >|= function
| None -> S.Tree.empty ()
| Some tree -> tree)
>|= fun tree -> { Tree.repo; tree }
let exists t k = tree t >>= fun t -> Tree.exists t k
let get t k = tree t >>= fun t -> Tree.get t k
let list t k = tree t >>= fun t -> Tree.list t k
let digest t k = tree t >>= fun t -> Tree.digest t k
let get t k =
match Key.segments k with
| [ "HEAD" ] -> head_message t >|= fun v -> Ok v
| _ -> get t k
end
module KV_RW (G : Irmin_git.G) (C : Mirage_clock.PCLOCK) = struct
XXX(samoht ): batches are stored in memory . This could be bad if
large objects are stored for too long ... Might be worth having
a clever LRU , which pushes larges objects to the underlying
layer when needed .
large objects are stored for too long... Might be worth having
a clever LRU, which pushes larges objects to the underlying
layer when needed. *)
module RO = KV_RO (G)
module S = RO.S
module Tree = RO.Tree
module Info = Irmin_mirage.Info (S.Info) (C)
type batch = { repo : S.repo; mutable tree : S.tree; origin : S.commit }
type store = Batch of batch | Store of RO.t
and t = {
store : store;
author : unit -> string;
msg : [ `Set of RO.key | `Remove of RO.key | `Batch ] -> string;
remote : Irmin.remote;
}
type key = RO.key
type error = RO.error
let pp_error = RO.pp_error
let default_author () = "irmin <>"
let default_msg = function
| `Set k -> Fmt.str "Updating %a" Mirage_kv.Key.pp k
| `Remove k -> Fmt.str "Removing %a" Mirage_kv.Key.pp k
| `Batch -> "Commmiting batch operation"
let connect ?depth ?branch ?root ?ctx ?headers ?(author = default_author)
?(msg = default_msg) git uri =
RO.connect ?depth ?branch ?root ?ctx ?headers git uri >|= fun t ->
let remote = S.remote ?ctx ?headers uri in
{ store = Store t; author; msg; remote }
let disconnect t =
match t.store with Store t -> RO.disconnect t | Batch _ -> Lwt.return_unit
(* XXX(samoht): always return the 'last modified' on the
underlying storage layer, not for the current batch. *)
let last_modified t key =
match t.store with
| Store t -> RO.last_modified t key
| Batch b ->
RO.S.of_commit b.origin >>= fun t ->
RO.last_modified { root = S.Path.empty; t } key
let repo t = match t.store with Store t -> S.repo t.t | Batch b -> b.repo
let tree t =
match t.store with
| Store t -> RO.tree t
| Batch b -> Lwt.return { Tree.tree = b.tree; repo = repo t }
let digest t k = tree t >>= fun t -> Tree.digest t k
let exists t k = tree t >>= fun t -> Tree.exists t k
let get t k = tree t >>= fun t -> Tree.get t k
let list t k = tree t >>= fun t -> Tree.list t k
type write_error = [ RO.error | Mirage_kv.write_error | RO.Sync.push_error ]
let write_error = function
| Ok _ -> Ok ()
| Error e -> Error (e :> write_error)
let pp_write_error ppf = function
| #RO.error as e -> RO.pp_error ppf e
| #RO.Sync.push_error as e -> RO.Sync.pp_push_error ppf e
| #Mirage_kv.write_error as e -> Mirage_kv.pp_write_error ppf e
let info t op = Info.f ~author:(t.author ()) "%s" (t.msg op)
let path = RO.path
let set t k v =
let info = info t (`Set k) in
match t.store with
| Store s -> (
S.set ~info s.t (path k) v >>= function
| Ok _ -> RO.Sync.push s.t t.remote >|= write_error
| Error e -> Lwt.return (Error (e :> write_error)))
| Batch b ->
S.Tree.add b.tree (path k) v >|= fun tree ->
b.tree <- tree;
Ok ()
let remove t k =
let info = info t (`Remove k) in
match t.store with
| Store s -> (
S.remove ~info s.t (path k) >>= function
| Ok _ -> RO.Sync.push s.t t.remote >|= write_error
| Error e -> Lwt.return (Error (e :> write_error)))
| Batch b ->
S.Tree.remove b.tree (path k) >|= fun tree ->
b.tree <- tree;
Ok ()
let get_store_tree (t : RO.t) =
S.Head.find t.t >>= function
| None -> Lwt.return_none
| Some origin -> (
let tree = S.Commit.tree origin in
S.Tree.find_tree tree t.root >|= function
| Some t -> Some (origin, t)
| None -> Some (origin, S.Tree.empty ()))
let batch t ?(retries = 42) f =
let info = info t `Batch in
let one t =
match t.store with
| Batch _ -> Fmt.failwith "No recursive batches"
| Store s -> (
let repo = S.repo s.t in
(* get the tree origin *)
get_store_tree s >>= function
| None -> f t >|= fun x -> Ok x (* no transaction is needed *)
| Some (origin, old_tree) -> (
let batch = { repo; tree = old_tree; origin } in
let b = Batch batch in
f { t with store = b } >>= fun result ->
get_store_tree s >>= function
| None ->
(* Someting weird happened, retring *)
Lwt.return (Error `Retry)
| Some (_, main_tree) -> (
Irmin.Merge.f S.Tree.merge
~old:(Irmin.Merge.promise old_tree)
main_tree batch.tree
>>= function
| Error (`Conflict _) -> Lwt.return (Error `Retry)
| Ok new_tree -> (
S.set_tree s.t ~info s.root new_tree >|= function
| Ok () -> Ok result
| Error _ -> Error `Retry))))
in
let rec loop = function
| 0 -> Lwt.fail_with "Too many retries"
| n -> (
one t >>= function
| Error `Retry -> loop (n - 1)
| Ok r -> Lwt.return r)
in
loop retries >>= fun r ->
match t.store with
| Batch _ -> Fmt.failwith "No recursive batches"
| Store s -> (
RO.Sync.push s.t t.remote >>= function
| Ok _ -> Lwt.return r
| Error e -> Lwt.fail_with (Fmt.to_to_string RO.Sync.pp_push_error e))
end
module Mem = struct
module G = Irmin_git.Mem
include Maker (G)
module Maker = struct
module Ref = Ref (G)
module KV = KV (G)
end
module Ref = Maker.Ref
module KV = Maker.KV
module KV_RO = KV_RO (G)
module KV_RW = KV_RW (G)
end
| null | https://raw.githubusercontent.com/mirage/irmin/abeee121a6db7b085b3c68af50ef24a8d8f9ed05/src/irmin-mirage/git/irmin_mirage_git.ml | ocaml | XXX(samoht): always return the 'last modified' on the
underlying storage layer, not for the current batch.
get the tree origin
no transaction is needed
Someting weird happened, retring |
* Copyright ( c ) 2013 - 2022 < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (c) 2013-2022 Thomas Gazagnaire <>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
open Lwt.Infix
include Irmin_mirage_git_intf
let remote ?(ctx = Mimic.empty) ?headers uri =
let ( ! ) f a b = f b a in
match Smart_git.Endpoint.of_string uri with
| Ok edn ->
let edn =
Option.fold ~none:edn
~some:(!Smart_git.Endpoint.with_headers_if_http edn)
headers
in
(ctx, edn)
| Error (`Msg err) -> Fmt.invalid_arg "remote: %s" err
module Maker (G : Irmin_git.G) = struct
type endpoint = Mimic.ctx * Smart_git.Endpoint.t
module Maker = Irmin_git.Maker (G) (Git.Mem.Sync (G))
module Make
(S : Irmin_git.Schema.S
with type Hash.t = G.hash
and type Node.t = G.Value.Tree.t
and type Commit.t = G.Value.Commit.t) =
struct
include Maker.Make (S)
let remote ?ctx ?headers uri = E (remote ?ctx ?headers uri)
end
end
module Ref (G : Irmin_git.G) = struct
module Maker = Irmin_git.Ref (G) (Git.Mem.Sync (G))
module G = G
type branch = Maker.branch
type endpoint = Maker.endpoint
module Make (C : Irmin.Contents.S) = struct
include Maker.Make (C)
let remote ?ctx ?headers uri = E (remote ?ctx ?headers uri)
end
end
module KV (G : Irmin_git.G) = struct
module Maker = Irmin_git.KV (G) (Git.Mem.Sync (G))
module G = G
type endpoint = Maker.endpoint
type branch = Maker.branch
module Make (C : Irmin.Contents.S) = struct
include Maker.Make (C)
let remote ?ctx ?headers uri = E (remote ?ctx ?headers uri)
end
end
module KV_RO (G : Git.S) = struct
module Key = Mirage_kv.Key
type key = Key.t
module G = struct
include G
let v ?dotgit:_ _root = assert false
end
module Maker = KV (G)
module S = Maker.Make (Irmin.Contents.String)
module Sync = Irmin.Sync.Make (S)
let disconnect _ = Lwt.return_unit
type error = [ Mirage_kv.error | S.write_error ]
let pp_error ppf = function
| #Mirage_kv.error as e -> Mirage_kv.pp_error ppf e
| #S.write_error as e -> Irmin.Type.pp S.write_error_t ppf e
let err e : ('a, error) result = Error e
let err_not_found k = err (`Not_found k)
let path x =
XXX(samoht ): we should probably just push the Key module in
Irmin and remove the path abstraction completely ...
Irmin and remove the path abstraction completely ... *)
Key.segments x
module Tree = struct
type t = { repo : S.repo; tree : S.tree }
let digest t key =
S.Tree.find_tree t.tree (path key) >|= function
| None -> err_not_found key
| Some tree ->
let h = S.Tree.hash tree in
Ok (Irmin.Type.to_string S.Hash.t h)
let list t key =
S.Tree.list t.tree (path key) >|= fun l ->
let l =
List.map
(fun (s, k) ->
( s,
match S.Tree.destruct k with
| `Contents _ -> `Value
| `Node _ -> `Dictionary ))
l
in
Ok l
let exists t key =
S.Tree.kind t.tree (path key) >|= function
| Some `Contents -> Ok (Some `Value)
| Some `Node -> Ok (Some `Dictionary)
| None -> Ok None
let get t key =
S.Tree.find t.tree (path key) >|= function
| None -> err_not_found key
| Some v -> Ok v
end
type t = { root : S.path; t : S.t }
let head_message t =
S.Head.find t.t >|= function
| None -> "empty HEAD"
| Some h ->
let info = S.Commit.info h in
Fmt.str "commit: %a\nAuthor: %s\nDate: %Ld\n\n%s\n" S.Commit.pp_hash h
(S.Info.author info) (S.Info.date info) (S.Info.message info)
let last_modified t key =
let key' = path key in
S.last_modified t.t key' >|= function
| [] -> Error (`Not_found key)
| h :: _ -> Ok (0, S.Info.date (S.Commit.info h))
let connect ?depth ?(branch = "main") ?(root = Mirage_kv.Key.empty) ?ctx
?headers t uri =
let remote = S.remote ?ctx ?headers uri in
let head = Git.Reference.v ("refs/heads/" ^ branch) in
S.repo_of_git ~bare:true ~head t >>= fun repo ->
S.of_branch repo branch >>= fun t ->
Sync.pull_exn t ?depth remote `Set >|= fun _ ->
let root = path root in
{ t; root }
let tree t =
let repo = S.repo t.t in
(S.find_tree t.t t.root >|= function
| None -> S.Tree.empty ()
| Some tree -> tree)
>|= fun tree -> { Tree.repo; tree }
let exists t k = tree t >>= fun t -> Tree.exists t k
let get t k = tree t >>= fun t -> Tree.get t k
let list t k = tree t >>= fun t -> Tree.list t k
let digest t k = tree t >>= fun t -> Tree.digest t k
let get t k =
match Key.segments k with
| [ "HEAD" ] -> head_message t >|= fun v -> Ok v
| _ -> get t k
end
module KV_RW (G : Irmin_git.G) (C : Mirage_clock.PCLOCK) = struct
XXX(samoht ): batches are stored in memory . This could be bad if
large objects are stored for too long ... Might be worth having
a clever LRU , which pushes larges objects to the underlying
layer when needed .
large objects are stored for too long... Might be worth having
a clever LRU, which pushes larges objects to the underlying
layer when needed. *)
module RO = KV_RO (G)
module S = RO.S
module Tree = RO.Tree
module Info = Irmin_mirage.Info (S.Info) (C)
type batch = { repo : S.repo; mutable tree : S.tree; origin : S.commit }
type store = Batch of batch | Store of RO.t
and t = {
store : store;
author : unit -> string;
msg : [ `Set of RO.key | `Remove of RO.key | `Batch ] -> string;
remote : Irmin.remote;
}
type key = RO.key
type error = RO.error
let pp_error = RO.pp_error
let default_author () = "irmin <>"
let default_msg = function
| `Set k -> Fmt.str "Updating %a" Mirage_kv.Key.pp k
| `Remove k -> Fmt.str "Removing %a" Mirage_kv.Key.pp k
| `Batch -> "Commmiting batch operation"
let connect ?depth ?branch ?root ?ctx ?headers ?(author = default_author)
?(msg = default_msg) git uri =
RO.connect ?depth ?branch ?root ?ctx ?headers git uri >|= fun t ->
let remote = S.remote ?ctx ?headers uri in
{ store = Store t; author; msg; remote }
let disconnect t =
match t.store with Store t -> RO.disconnect t | Batch _ -> Lwt.return_unit
let last_modified t key =
match t.store with
| Store t -> RO.last_modified t key
| Batch b ->
RO.S.of_commit b.origin >>= fun t ->
RO.last_modified { root = S.Path.empty; t } key
let repo t = match t.store with Store t -> S.repo t.t | Batch b -> b.repo
let tree t =
match t.store with
| Store t -> RO.tree t
| Batch b -> Lwt.return { Tree.tree = b.tree; repo = repo t }
let digest t k = tree t >>= fun t -> Tree.digest t k
let exists t k = tree t >>= fun t -> Tree.exists t k
let get t k = tree t >>= fun t -> Tree.get t k
let list t k = tree t >>= fun t -> Tree.list t k
type write_error = [ RO.error | Mirage_kv.write_error | RO.Sync.push_error ]
let write_error = function
| Ok _ -> Ok ()
| Error e -> Error (e :> write_error)
let pp_write_error ppf = function
| #RO.error as e -> RO.pp_error ppf e
| #RO.Sync.push_error as e -> RO.Sync.pp_push_error ppf e
| #Mirage_kv.write_error as e -> Mirage_kv.pp_write_error ppf e
let info t op = Info.f ~author:(t.author ()) "%s" (t.msg op)
let path = RO.path
let set t k v =
let info = info t (`Set k) in
match t.store with
| Store s -> (
S.set ~info s.t (path k) v >>= function
| Ok _ -> RO.Sync.push s.t t.remote >|= write_error
| Error e -> Lwt.return (Error (e :> write_error)))
| Batch b ->
S.Tree.add b.tree (path k) v >|= fun tree ->
b.tree <- tree;
Ok ()
let remove t k =
let info = info t (`Remove k) in
match t.store with
| Store s -> (
S.remove ~info s.t (path k) >>= function
| Ok _ -> RO.Sync.push s.t t.remote >|= write_error
| Error e -> Lwt.return (Error (e :> write_error)))
| Batch b ->
S.Tree.remove b.tree (path k) >|= fun tree ->
b.tree <- tree;
Ok ()
let get_store_tree (t : RO.t) =
S.Head.find t.t >>= function
| None -> Lwt.return_none
| Some origin -> (
let tree = S.Commit.tree origin in
S.Tree.find_tree tree t.root >|= function
| Some t -> Some (origin, t)
| None -> Some (origin, S.Tree.empty ()))
let batch t ?(retries = 42) f =
let info = info t `Batch in
let one t =
match t.store with
| Batch _ -> Fmt.failwith "No recursive batches"
| Store s -> (
let repo = S.repo s.t in
get_store_tree s >>= function
| Some (origin, old_tree) -> (
let batch = { repo; tree = old_tree; origin } in
let b = Batch batch in
f { t with store = b } >>= fun result ->
get_store_tree s >>= function
| None ->
Lwt.return (Error `Retry)
| Some (_, main_tree) -> (
Irmin.Merge.f S.Tree.merge
~old:(Irmin.Merge.promise old_tree)
main_tree batch.tree
>>= function
| Error (`Conflict _) -> Lwt.return (Error `Retry)
| Ok new_tree -> (
S.set_tree s.t ~info s.root new_tree >|= function
| Ok () -> Ok result
| Error _ -> Error `Retry))))
in
let rec loop = function
| 0 -> Lwt.fail_with "Too many retries"
| n -> (
one t >>= function
| Error `Retry -> loop (n - 1)
| Ok r -> Lwt.return r)
in
loop retries >>= fun r ->
match t.store with
| Batch _ -> Fmt.failwith "No recursive batches"
| Store s -> (
RO.Sync.push s.t t.remote >>= function
| Ok _ -> Lwt.return r
| Error e -> Lwt.fail_with (Fmt.to_to_string RO.Sync.pp_push_error e))
end
module Mem = struct
module G = Irmin_git.Mem
include Maker (G)
module Maker = struct
module Ref = Ref (G)
module KV = KV (G)
end
module Ref = Maker.Ref
module KV = Maker.KV
module KV_RO = KV_RO (G)
module KV_RW = KV_RW (G)
end
|
8a658fab26cca6502a2a9f6c12b056b276c5411e9955124a7b2e66efb68c0b46 | mfikes/coal-mine | problem_110.cljc | (ns coal-mine.problem-110
(:require [coal-mine.checks :refer [defcheck-110] :rename {defcheck-110 defcheck}]
[clojure.test]))
(defn run-tests []
(clojure.test/run-tests 'coal-mine.problem-110))
(defn -main []
(run-tests))
#?(:cljs (set! *main-cli-fn* -main))
| null | https://raw.githubusercontent.com/mfikes/coal-mine/0961d085b37f4e59489a8cf6a2b8fef0a698d8fb/src/coal_mine/problem_110.cljc | clojure | (ns coal-mine.problem-110
(:require [coal-mine.checks :refer [defcheck-110] :rename {defcheck-110 defcheck}]
[clojure.test]))
(defn run-tests []
(clojure.test/run-tests 'coal-mine.problem-110))
(defn -main []
(run-tests))
#?(:cljs (set! *main-cli-fn* -main))
| |
aaa9124b1988ab17c2ea2914721f633638745211335295ee33d0f144b077d401 | SimulaVR/godot-haskell | VisualScriptSwitch.hs | # LANGUAGE DerivingStrategies , GeneralizedNewtypeDeriving ,
TypeFamilies , TypeOperators , FlexibleContexts , DataKinds ,
MultiParamTypeClasses #
TypeFamilies, TypeOperators, FlexibleContexts, DataKinds,
MultiParamTypeClasses #-}
module Godot.Core.VisualScriptSwitch () where
import Data.Coerce
import Foreign.C
import Godot.Internal.Dispatch
import qualified Data.Vector as V
import Linear(V2(..),V3(..),M22)
import Data.Colour(withOpacity)
import Data.Colour.SRGB(sRGB)
import System.IO.Unsafe
import Godot.Gdnative.Internal
import Godot.Api.Types
import Godot.Core.VisualScriptNode() | null | https://raw.githubusercontent.com/SimulaVR/godot-haskell/e8f2c45f1b9cc2f0586ebdc9ec6002c8c2d384ae/src/Godot/Core/VisualScriptSwitch.hs | haskell | # LANGUAGE DerivingStrategies , GeneralizedNewtypeDeriving ,
TypeFamilies , TypeOperators , FlexibleContexts , DataKinds ,
MultiParamTypeClasses #
TypeFamilies, TypeOperators, FlexibleContexts, DataKinds,
MultiParamTypeClasses #-}
module Godot.Core.VisualScriptSwitch () where
import Data.Coerce
import Foreign.C
import Godot.Internal.Dispatch
import qualified Data.Vector as V
import Linear(V2(..),V3(..),M22)
import Data.Colour(withOpacity)
import Data.Colour.SRGB(sRGB)
import System.IO.Unsafe
import Godot.Gdnative.Internal
import Godot.Api.Types
import Godot.Core.VisualScriptNode() | |
1a53e0a08f6ee619dd9ef3bd0c4513f70fa6277031cf06af31393b33670d4dc2 | BnMcGn/clath | bottom.lisp | (in-package :clath)
(defparameter *callback-extension* "callback/")
(defparameter *login-extension* "login/")
;;Because north supports oauth 1.0a
(defparameter *callback-extension-north* "callback1a/")
(defparameter *login-extension-north* "login1a/")
(defvar *server-url*)
(defparameter *clath-version* "0.1")
(defun user-agent (provider)
"Some providers, such as Reddit, want a fairly unique user-agent."
(declare (ignore provider)) ;For now
(format nil "Clath/~a by BnMcGn" *clath-version*))
(setf drakma:*text-content-types*
(cons '("application" . "json") drakma:*text-content-types*))
(defun discover-endpoints (discovery-url)
(let ((disc (cl-json:decode-json-from-string (drakma:http-request discovery-url))))
(list
:auth-endpoint (assoc-cdr :authorization--endpoint disc)
:token-endpoint (assoc-cdr :token--endpoint disc)
:userinfo-endpoint (assoc-cdr :userinfo--endpoint disc)
:jwks-uri (assoc-cdr :jwks--uri disc))))
(defun get-jwk-key (jsonkey)
(let ((kty (cdr (assoc :kty jsonkey))))
(cond
((equal kty "RSA")
(let ((n (ironclad:octets-to-integer
(jose/base64:base64url-decode (cdr (assoc :n jsonkey)))))
(e (ironclad:octets-to-integer
(jose/base64:base64url-decode (cdr (assoc :e jsonkey))))))
(ironclad:make-public-key :rsa :e e :n n)))
(t
(warn "Key type not found.")
nil))))
(defun fetch-jwks (jwks-uri)
(let* ((data (cl-json:decode-json-from-string (drakma:http-request jwks-uri)))
(res nil)
(algs nil)
(alglist '(:hs256 :hs384 :hs512 :rs256 :rs384 :rs512 :ps256 :ps384 :ps512)))
(dolist (key (cdr (assoc :keys data)))
(when-let ((kobj (get-jwk-key key))
(alg (or
(find (cdr (assoc :alg key)) alglist :test #'string-equal)
:rs256)))
(push (cons (cdr (assoc :kid key)) kobj) res)
(push (cons (cdr (assoc :kid key)) alg) algs)))
(values (nreverse res) (nreverse algs))))
(defun update-jwks (provider jwks-uri)
(multiple-value-bind (keys algs) (fetch-jwks jwks-uri)
(setf (getf (getf *provider-info* provider) :keys) keys)
(setf (getf (getf *provider-info* provider) :algorithms) algs)))
(defun get-jwk (kid provider)
(when-let ((key (assoc kid (getf (getf *provider-info* provider) :keys) :test #'equal)))
(cdr key)))
(defun ensure-jwk (kid provider)
(or (get-jwk kid provider)
(progn
;;Try again. Maybe there is an update...
(update-jwks provider (getf (getf *provider-info* provider) :jwks-uri))
(or (get-jwk kid provider)
(error "Can't find the required signing key from OpenID Connect provider")))))
(defun unpack-and-check-jwt (jwt provider)
(multiple-value-bind (tokinfo keyinfo _) (jose:inspect-token jwt)
(declare (ignore _))
(let* ((kid (cdr (assoc "kid" keyinfo :test #'equal)))
(key (ensure-jwk kid provider))
(alg (cdr (assoc kid (getf (getf *provider-info* provider) :algorithms) :test #'equal))))
(if (jose:verify alg key jwt)
tokinfo
(error "Signature check failed on supplied JWT")))))
;;;FIXME: Endpoint discovery only done on startup. Should look at spec and see if it should
;;;happen more frequently.
(defun provider-info (provider)
(let ((prov (getf *provider-info* provider)))
(unless prov (error "Not a recognized provider"))
(if (getf prov :auth-endpoint)
(alist-plist
(extract-keywords
'(:auth-endpoint :token-endpoint :userinfo-endpoint :auth-scope
:token-processor :access-endpoint :request-endpoint :jwks-uri)
prov))
(progn
(unless (getf prov :endpoints-url)
(error "Provider must have :endpoints-url or endpoint definitions"))
(let ((res (discover-endpoints (getf prov :endpoints-url))))
(setf (getf *provider-info* provider)
(concatenate 'list prov res)))))))
(defun provider-secrets (provider)
(getf *provider-secrets* provider))
(defun provider-string (provider)
(if-let ((string (getf (getf *provider-info* provider) :string)))
string
(string-downcase (string provider))))
(defun provider-url-string (provider)
(if-let ((string (getf (getf *provider-info* provider) :url-string)))
string
(provider-string provider)))
(defun uses-north-p (provider)
(getf (getf *provider-info* provider) :use-north))
(defun basic-authorization (provider)
(let ((secrets (provider-secrets provider)))
(list (getf secrets :client-id) (getf secrets :secret))))
(defun make-login-url (provider)
(concatenate
'string *server-url*
(if (uses-north-p provider) *login-extension-north* *login-extension*)
(provider-string provider)))
(defun make-callback-url (provider)
(concatenate
'string *server-url*
(if (uses-north-p provider) *callback-extension-north* *callback-extension*)
(provider-url-string provider)))
(defun available-providers ()
(remove-if-not #'keywordp *provider-secrets*))
;;;FIXME: Audit me: this number is probably correct/random enough, because the public
;;;*probably* never sees it. Should get a knowledgable opionion on it though.
(defun gen-state (len)
(with-output-to-string (stream)
(let ((*print-base* 36))
(loop repeat len
do (princ (random 36) stream)))))
(defun special-url-p (url-path)
(or (sequence-starts-with (concatenate 'string "/" *callback-extension*) url-path)
(sequence-starts-with (concatenate 'string "/" *login-extension*) url-path)))
(defun request-user-auth-destination
(&key auth-scope client-id auth-endpoint state redirect-uri &allow-other-keys)
(drakma:http-request
auth-endpoint :redirect nil
:parameters `(("client_id" . ,client-id) ("app_id" . ,client-id)
("response_type" . "code") ("scope" . ,auth-scope)
("redirect_uri" . ,redirect-uri) ("state" . ,state))))
;;;WARNING: Function saves state to session!
(defun login-action (provider)
(unless (ningle:context :session)
(setf (ningle:context :session) (make-hash-table)))
(let ((state (gen-state 36)))
(setf (gethash 'state (ningle:context :session)) state)
(setf (gethash :clath-provider (ningle:context :session)) provider)
(multiple-value-bind (content resp-code headers uri)
(apply #'request-user-auth-destination :state state
:redirect-uri (make-callback-url provider)
:client-id (getf (provider-secrets provider) :client-id)
(provider-info provider))
(declare (ignore headers))
(if (< resp-code 400) `(302 (:location ,(format nil "~a" uri)))
content))))
;;;FIXME: Why does this need redirect_uri? Try without.
(defun request-access-token (provider code redirect-uri)
(let ((info (provider-info provider))
(secrets (provider-secrets provider)))
(multiple-value-bind (response code headers)
(drakma:http-request
(getf info :token-endpoint)
:method :post
:redirect nil
:user-agent (user-agent provider)
:basic-authorization (basic-authorization provider)
:parameters `(("code" . ,code)
("client_id" . ,(getf secrets :client-id))
("app_id" . ,(getf secrets :client-id))
("client_secret" . ,(getf secrets :secret))
("redirect_uri" . ,redirect-uri)
("grant_type" . "authorization_code")))
(declare (ignore code))
(let ((subtype (nth-value 1 (drakma:get-content-type headers))))
(check-for-error
(cond
((equal subtype "json")
(cl-json:decode-json-from-string response))
((equal subtype "x-www-form-urlencoded")
(quri:url-decode-params
(flexi-streams:octets-to-string response)))
((equal subtype "plain")
(quri:url-decode-params response))
(t (error
"Couldn't find parseable access token"))))))))
(defun get-access-token (atdata)
(if-let ((atok (assoc :access--token atdata)))
(cdr atok)
(cdr (assoc "access_token" atdata :test #'equal))))
(defun get-id-token (atdata provider)
(if-let ((itok (assoc :id--token atdata)))
(unpack-and-check-jwt (cdr itok) provider)
(get-access-token atdata)))
(defun valid-state (received-state)
(and (ningle:context :session)
(equal (gethash 'state (ningle:context :session)) received-state)))
FIXME : clath should n't be handling destination / redirect . It 's a more general
;;; problem. *login-destination* is a temporary hack to deal with that.
(defvar *login-destination* nil)
(defparameter *login-destination-hook* nil)
(defun destination-on-login ()
(if (functionp *login-destination-hook*)
(funcall *login-destination-hook*
:username (gethash :username (ningle:context :session)))
(if *login-destination* *login-destination*
(if-let ((dest (gethash :clath-destination
(ningle:context :session))))
dest
"/"))))
(defun userinfo-get-user-id (provider userinfo)
(declare (ignore provider)) ;;In future we may specialize
(cdr (assoc-or '(:sub :id :user--id) userinfo)))
;;FIXME: Could be more generalized
(defun try-request-user-info (provider access-token)
"Sometimes a newly generated access token won't instantly propagate in the provider's system, so we try a few times to give it a chance."
(let ((uinfo nil))
(dotimes (i 10)
(setf uinfo (request-user-info provider access-token))
(when (userinfo-get-user-id provider uinfo)
(return))
(sleep 1))
uinfo))
(defun callback-action (provider parameters &optional post-func)
(cond ((not (valid-state (assoc-cdr "state" parameters #'equal)))
'(403 '() "Login failed. State mismatch."))
((not (assoc-cdr "code" parameters #'equal))
'(403 '() "Login failed. Didn't receive code parameter from OAuth Server."))
(t
(let* ((at-data (request-access-token
provider
(assoc-cdr "code" parameters #'equal)
(make-callback-url provider)))
(access-token (get-access-token at-data)))
(when (assoc :error at-data)
(error (format nil "Error message from OAuth server: ~a"
(assoc-cdr :message at-data))))
(with-keys (:clath-access-token :clath-userinfo
:clath-id-token)
(ningle:context :session)
(setf clath-access-token access-token
clath-userinfo (try-request-user-info provider access-token)
clath-id-token (get-id-token at-data provider)))
(when (functionp post-func) (funcall post-func))
`(302 (:location ,(destination-on-login)))))))
(defun logout-action ()
(remhash 'state (ningle:context :session))
(remhash :clath-provider (ningle:context :session))
(remhash :clath-access-token (ningle:context :session))
(remhash :clath-userinfo (ningle:context :session))
(remhash :clath-id-token (ningle:context :session)))
;;;WARNING: Function saves state to session!
(defun login-action-north (provider)
(unless (ningle:context :session)
(setf (ningle:context :session) (make-hash-table)))
(let* ((provinfo (provider-info provider))
(nclient
(make-instance
'north:client
:key (getf (provider-secrets provider) :client-id)
:secret (getf (provider-secrets provider) :secret)
:authorize-uri (getf provinfo :auth-endpoint)
:access-token-uri (getf provinfo :access-endpoint)
:request-token-uri (getf provinfo :request-endpoint)
:callback (make-callback-url provider))))
(setf (gethash 'north-client (ningle:context :session)) nclient)
(setf (gethash :clath-provider (ningle:context :session)) provider)
`(302 (:location ,(north:initiate-authentication nclient)))))
(defun callback-action-north (provider parameters &optional post-func)
(let* ((nclient (gethash 'north-client (ningle:context :session)))
(token (north:token nclient)))
(cond ((not (equal token (assoc-cdr "oauth_token" parameters #'equal)))
'(403 '() "Login failed. State mismatch."))
((not (assoc-cdr "oauth_verifier" parameters #'equal))
'(403 '()
"Login failed. Didn't receive code parameter from OAuth Server."))
(t
(north:complete-authentication
nclient
(assoc-cdr "oauth_verifier" parameters #'equal))
(setf (gethash :clath-userinfo (ningle:context :session))
(request-user-info-north provider nclient))
(when (functionp post-func) (funcall post-func))
`(302 (:location ,(destination-on-login)))))))
| null | https://raw.githubusercontent.com/BnMcGn/clath/8e1787a9819386dceea45b45f753b81c28a5f575/bottom.lisp | lisp | Because north supports oauth 1.0a
For now
Try again. Maybe there is an update...
FIXME: Endpoint discovery only done on startup. Should look at spec and see if it should
happen more frequently.
FIXME: Audit me: this number is probably correct/random enough, because the public
*probably* never sees it. Should get a knowledgable opionion on it though.
WARNING: Function saves state to session!
FIXME: Why does this need redirect_uri? Try without.
problem. *login-destination* is a temporary hack to deal with that.
In future we may specialize
FIXME: Could be more generalized
WARNING: Function saves state to session! | (in-package :clath)
(defparameter *callback-extension* "callback/")
(defparameter *login-extension* "login/")
(defparameter *callback-extension-north* "callback1a/")
(defparameter *login-extension-north* "login1a/")
(defvar *server-url*)
(defparameter *clath-version* "0.1")
(defun user-agent (provider)
"Some providers, such as Reddit, want a fairly unique user-agent."
(format nil "Clath/~a by BnMcGn" *clath-version*))
(setf drakma:*text-content-types*
(cons '("application" . "json") drakma:*text-content-types*))
(defun discover-endpoints (discovery-url)
(let ((disc (cl-json:decode-json-from-string (drakma:http-request discovery-url))))
(list
:auth-endpoint (assoc-cdr :authorization--endpoint disc)
:token-endpoint (assoc-cdr :token--endpoint disc)
:userinfo-endpoint (assoc-cdr :userinfo--endpoint disc)
:jwks-uri (assoc-cdr :jwks--uri disc))))
(defun get-jwk-key (jsonkey)
(let ((kty (cdr (assoc :kty jsonkey))))
(cond
((equal kty "RSA")
(let ((n (ironclad:octets-to-integer
(jose/base64:base64url-decode (cdr (assoc :n jsonkey)))))
(e (ironclad:octets-to-integer
(jose/base64:base64url-decode (cdr (assoc :e jsonkey))))))
(ironclad:make-public-key :rsa :e e :n n)))
(t
(warn "Key type not found.")
nil))))
(defun fetch-jwks (jwks-uri)
(let* ((data (cl-json:decode-json-from-string (drakma:http-request jwks-uri)))
(res nil)
(algs nil)
(alglist '(:hs256 :hs384 :hs512 :rs256 :rs384 :rs512 :ps256 :ps384 :ps512)))
(dolist (key (cdr (assoc :keys data)))
(when-let ((kobj (get-jwk-key key))
(alg (or
(find (cdr (assoc :alg key)) alglist :test #'string-equal)
:rs256)))
(push (cons (cdr (assoc :kid key)) kobj) res)
(push (cons (cdr (assoc :kid key)) alg) algs)))
(values (nreverse res) (nreverse algs))))
(defun update-jwks (provider jwks-uri)
(multiple-value-bind (keys algs) (fetch-jwks jwks-uri)
(setf (getf (getf *provider-info* provider) :keys) keys)
(setf (getf (getf *provider-info* provider) :algorithms) algs)))
(defun get-jwk (kid provider)
(when-let ((key (assoc kid (getf (getf *provider-info* provider) :keys) :test #'equal)))
(cdr key)))
(defun ensure-jwk (kid provider)
(or (get-jwk kid provider)
(progn
(update-jwks provider (getf (getf *provider-info* provider) :jwks-uri))
(or (get-jwk kid provider)
(error "Can't find the required signing key from OpenID Connect provider")))))
(defun unpack-and-check-jwt (jwt provider)
(multiple-value-bind (tokinfo keyinfo _) (jose:inspect-token jwt)
(declare (ignore _))
(let* ((kid (cdr (assoc "kid" keyinfo :test #'equal)))
(key (ensure-jwk kid provider))
(alg (cdr (assoc kid (getf (getf *provider-info* provider) :algorithms) :test #'equal))))
(if (jose:verify alg key jwt)
tokinfo
(error "Signature check failed on supplied JWT")))))
(defun provider-info (provider)
(let ((prov (getf *provider-info* provider)))
(unless prov (error "Not a recognized provider"))
(if (getf prov :auth-endpoint)
(alist-plist
(extract-keywords
'(:auth-endpoint :token-endpoint :userinfo-endpoint :auth-scope
:token-processor :access-endpoint :request-endpoint :jwks-uri)
prov))
(progn
(unless (getf prov :endpoints-url)
(error "Provider must have :endpoints-url or endpoint definitions"))
(let ((res (discover-endpoints (getf prov :endpoints-url))))
(setf (getf *provider-info* provider)
(concatenate 'list prov res)))))))
(defun provider-secrets (provider)
(getf *provider-secrets* provider))
(defun provider-string (provider)
(if-let ((string (getf (getf *provider-info* provider) :string)))
string
(string-downcase (string provider))))
(defun provider-url-string (provider)
(if-let ((string (getf (getf *provider-info* provider) :url-string)))
string
(provider-string provider)))
(defun uses-north-p (provider)
(getf (getf *provider-info* provider) :use-north))
(defun basic-authorization (provider)
(let ((secrets (provider-secrets provider)))
(list (getf secrets :client-id) (getf secrets :secret))))
(defun make-login-url (provider)
(concatenate
'string *server-url*
(if (uses-north-p provider) *login-extension-north* *login-extension*)
(provider-string provider)))
(defun make-callback-url (provider)
(concatenate
'string *server-url*
(if (uses-north-p provider) *callback-extension-north* *callback-extension*)
(provider-url-string provider)))
(defun available-providers ()
(remove-if-not #'keywordp *provider-secrets*))
(defun gen-state (len)
(with-output-to-string (stream)
(let ((*print-base* 36))
(loop repeat len
do (princ (random 36) stream)))))
(defun special-url-p (url-path)
(or (sequence-starts-with (concatenate 'string "/" *callback-extension*) url-path)
(sequence-starts-with (concatenate 'string "/" *login-extension*) url-path)))
(defun request-user-auth-destination
(&key auth-scope client-id auth-endpoint state redirect-uri &allow-other-keys)
(drakma:http-request
auth-endpoint :redirect nil
:parameters `(("client_id" . ,client-id) ("app_id" . ,client-id)
("response_type" . "code") ("scope" . ,auth-scope)
("redirect_uri" . ,redirect-uri) ("state" . ,state))))
(defun login-action (provider)
(unless (ningle:context :session)
(setf (ningle:context :session) (make-hash-table)))
(let ((state (gen-state 36)))
(setf (gethash 'state (ningle:context :session)) state)
(setf (gethash :clath-provider (ningle:context :session)) provider)
(multiple-value-bind (content resp-code headers uri)
(apply #'request-user-auth-destination :state state
:redirect-uri (make-callback-url provider)
:client-id (getf (provider-secrets provider) :client-id)
(provider-info provider))
(declare (ignore headers))
(if (< resp-code 400) `(302 (:location ,(format nil "~a" uri)))
content))))
(defun request-access-token (provider code redirect-uri)
(let ((info (provider-info provider))
(secrets (provider-secrets provider)))
(multiple-value-bind (response code headers)
(drakma:http-request
(getf info :token-endpoint)
:method :post
:redirect nil
:user-agent (user-agent provider)
:basic-authorization (basic-authorization provider)
:parameters `(("code" . ,code)
("client_id" . ,(getf secrets :client-id))
("app_id" . ,(getf secrets :client-id))
("client_secret" . ,(getf secrets :secret))
("redirect_uri" . ,redirect-uri)
("grant_type" . "authorization_code")))
(declare (ignore code))
(let ((subtype (nth-value 1 (drakma:get-content-type headers))))
(check-for-error
(cond
((equal subtype "json")
(cl-json:decode-json-from-string response))
((equal subtype "x-www-form-urlencoded")
(quri:url-decode-params
(flexi-streams:octets-to-string response)))
((equal subtype "plain")
(quri:url-decode-params response))
(t (error
"Couldn't find parseable access token"))))))))
(defun get-access-token (atdata)
(if-let ((atok (assoc :access--token atdata)))
(cdr atok)
(cdr (assoc "access_token" atdata :test #'equal))))
(defun get-id-token (atdata provider)
(if-let ((itok (assoc :id--token atdata)))
(unpack-and-check-jwt (cdr itok) provider)
(get-access-token atdata)))
(defun valid-state (received-state)
(and (ningle:context :session)
(equal (gethash 'state (ningle:context :session)) received-state)))
FIXME : clath should n't be handling destination / redirect . It 's a more general
(defvar *login-destination* nil)
(defparameter *login-destination-hook* nil)
(defun destination-on-login ()
(if (functionp *login-destination-hook*)
(funcall *login-destination-hook*
:username (gethash :username (ningle:context :session)))
(if *login-destination* *login-destination*
(if-let ((dest (gethash :clath-destination
(ningle:context :session))))
dest
"/"))))
(defun userinfo-get-user-id (provider userinfo)
(cdr (assoc-or '(:sub :id :user--id) userinfo)))
(defun try-request-user-info (provider access-token)
"Sometimes a newly generated access token won't instantly propagate in the provider's system, so we try a few times to give it a chance."
(let ((uinfo nil))
(dotimes (i 10)
(setf uinfo (request-user-info provider access-token))
(when (userinfo-get-user-id provider uinfo)
(return))
(sleep 1))
uinfo))
(defun callback-action (provider parameters &optional post-func)
(cond ((not (valid-state (assoc-cdr "state" parameters #'equal)))
'(403 '() "Login failed. State mismatch."))
((not (assoc-cdr "code" parameters #'equal))
'(403 '() "Login failed. Didn't receive code parameter from OAuth Server."))
(t
(let* ((at-data (request-access-token
provider
(assoc-cdr "code" parameters #'equal)
(make-callback-url provider)))
(access-token (get-access-token at-data)))
(when (assoc :error at-data)
(error (format nil "Error message from OAuth server: ~a"
(assoc-cdr :message at-data))))
(with-keys (:clath-access-token :clath-userinfo
:clath-id-token)
(ningle:context :session)
(setf clath-access-token access-token
clath-userinfo (try-request-user-info provider access-token)
clath-id-token (get-id-token at-data provider)))
(when (functionp post-func) (funcall post-func))
`(302 (:location ,(destination-on-login)))))))
(defun logout-action ()
(remhash 'state (ningle:context :session))
(remhash :clath-provider (ningle:context :session))
(remhash :clath-access-token (ningle:context :session))
(remhash :clath-userinfo (ningle:context :session))
(remhash :clath-id-token (ningle:context :session)))
(defun login-action-north (provider)
(unless (ningle:context :session)
(setf (ningle:context :session) (make-hash-table)))
(let* ((provinfo (provider-info provider))
(nclient
(make-instance
'north:client
:key (getf (provider-secrets provider) :client-id)
:secret (getf (provider-secrets provider) :secret)
:authorize-uri (getf provinfo :auth-endpoint)
:access-token-uri (getf provinfo :access-endpoint)
:request-token-uri (getf provinfo :request-endpoint)
:callback (make-callback-url provider))))
(setf (gethash 'north-client (ningle:context :session)) nclient)
(setf (gethash :clath-provider (ningle:context :session)) provider)
`(302 (:location ,(north:initiate-authentication nclient)))))
(defun callback-action-north (provider parameters &optional post-func)
(let* ((nclient (gethash 'north-client (ningle:context :session)))
(token (north:token nclient)))
(cond ((not (equal token (assoc-cdr "oauth_token" parameters #'equal)))
'(403 '() "Login failed. State mismatch."))
((not (assoc-cdr "oauth_verifier" parameters #'equal))
'(403 '()
"Login failed. Didn't receive code parameter from OAuth Server."))
(t
(north:complete-authentication
nclient
(assoc-cdr "oauth_verifier" parameters #'equal))
(setf (gethash :clath-userinfo (ningle:context :session))
(request-user-info-north provider nclient))
(when (functionp post-func) (funcall post-func))
`(302 (:location ,(destination-on-login)))))))
|
40a02c3f5b8171ba22ded59a3d6430d42677ed04979b319dd2782255ae8e6236 | racket/typed-racket | top-level-begin.rkt | #lang racket
;; Test various (begin ...)s at the top-level. In
;; particular, avoid a (begin) regression.
(define ns (make-base-namespace))
(eval '(require typed/racket) ns)
(eval '(begin) ns)
(eval '(begin 1 2) ns)
(eval '(begin (+ 1 2) 5 3 "foo") ns)
| null | https://raw.githubusercontent.com/racket/typed-racket/0236151e3b95d6d39276353cb5005197843e16e4/typed-racket-test/succeed/top-level-begin.rkt | racket | Test various (begin ...)s at the top-level. In
particular, avoid a (begin) regression. | #lang racket
(define ns (make-base-namespace))
(eval '(require typed/racket) ns)
(eval '(begin) ns)
(eval '(begin 1 2) ns)
(eval '(begin (+ 1 2) 5 3 "foo") ns)
|
eb1794dafd373dcb225d5babd4fe513461a6e3e8197549cb11dcdc62a60798fe | tdrhq/easy-macros | run-circleci.lisp | (load "~/quicklisp/setup.lisp")
(push #P "./" asdf:*central-registry*)
(ql:quickload :quick-patch)
(quick-patch:register "-matchers.git"
"master")
(quick-patch:checkout-all "build/quick-patch-oss/")
(ql:quickload :easy-macros/tests)
(unless (fiveam:run-all-tests)
(uiop:quit 1))
(uiop:quit 0)
| null | https://raw.githubusercontent.com/tdrhq/easy-macros/8b6e994f405f78bce24128b117cff9d3212a3c85/run-circleci.lisp | lisp | (load "~/quicklisp/setup.lisp")
(push #P "./" asdf:*central-registry*)
(ql:quickload :quick-patch)
(quick-patch:register "-matchers.git"
"master")
(quick-patch:checkout-all "build/quick-patch-oss/")
(ql:quickload :easy-macros/tests)
(unless (fiveam:run-all-tests)
(uiop:quit 1))
(uiop:quit 0)
| |
73f93d112ce7ae20956727a118047ab884ef031e3d7f42532b2dee211ecdf799 | strise/gintonic | helpers.ml |
external readFileSync: name: string -> (_ [@bs.as "utf8"]) -> string = "readFileSync" [@@bs.module "fs"]
| null | https://raw.githubusercontent.com/strise/gintonic/25c0ebc4f492cac40f71de8dee4565f0d89bfa4b/packages/gintonic/__tests__/helpers.ml | ocaml |
external readFileSync: name: string -> (_ [@bs.as "utf8"]) -> string = "readFileSync" [@@bs.module "fs"]
| |
11f474de95711ec58a4e81248b9108e231bb7ca7bd52dd83582cfb243a2d2e89 | scrintal/heroicons-reagent | building_office_2.cljs | (ns com.scrintal.heroicons.outline.building-office-2)
(defn render []
[:svg {:xmlns ""
:fill "none"
:viewBox "0 0 24 24"
:strokeWidth "1.5"
:stroke "currentColor"
:aria-hidden "true"}
[:path {:strokeLinecap "round"
:strokeLinejoin "round"
:d "M2.25 21h19.5m-18-18v18m10.5-18v18m6-13.5V21M6.75 6.75h.75m-.75 3h.75m-.75 3h.75m3-6h.75m-.75 3h.75m-.75 3h.75M6.75 21v-3.375c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125V21M3 3h12m-.75 4.5H21m-3.75 3.75h.008v.008h-.008v-.008zm0 3h.008v.008h-.008v-.008zm0 3h.008v.008h-.008v-.008z"}]]) | null | https://raw.githubusercontent.com/scrintal/heroicons-reagent/572f51d2466697ec4d38813663ee2588960365b6/src/com/scrintal/heroicons/outline/building_office_2.cljs | clojure | (ns com.scrintal.heroicons.outline.building-office-2)
(defn render []
[:svg {:xmlns ""
:fill "none"
:viewBox "0 0 24 24"
:strokeWidth "1.5"
:stroke "currentColor"
:aria-hidden "true"}
[:path {:strokeLinecap "round"
:strokeLinejoin "round"
:d "M2.25 21h19.5m-18-18v18m10.5-18v18m6-13.5V21M6.75 6.75h.75m-.75 3h.75m-.75 3h.75m3-6h.75m-.75 3h.75m-.75 3h.75M6.75 21v-3.375c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125V21M3 3h12m-.75 4.5H21m-3.75 3.75h.008v.008h-.008v-.008zm0 3h.008v.008h-.008v-.008zm0 3h.008v.008h-.008v-.008z"}]]) | |
2b38b9f4743aba5679deebb5b62840f03a2b4a5515410868b311806cd1334cf5 | clojure-interop/java-jdk | Style.clj | (ns javax.swing.text.Style
"A collection of attributes to associate with an element in a document.
Since these are typically used to associate character and paragraph
styles with the element, operations for this are provided. Other
customized attributes that get associated with the element will
effectively be name-value pairs that live in a hierarchy and if a name
(key) is not found locally, the request is forwarded to the parent.
Commonly used attributes are separated out to facilitate alternative
implementations that are more efficient."
(:refer-clojure :only [require comment defn ->])
(:import [javax.swing.text Style]))
(defn get-name
"Fetches the name of the style. A style is not required to be named,
so null is returned if there is no name
associated with the style.
returns: the name - `java.lang.String`"
(^java.lang.String [^Style this]
(-> this (.getName))))
(defn add-change-listener
"Adds a listener to track whenever an attribute
has been changed.
l - the change listener - `javax.swing.event.ChangeListener`"
([^Style this ^javax.swing.event.ChangeListener l]
(-> this (.addChangeListener l))))
(defn remove-change-listener
"Removes a listener that was tracking attribute changes.
l - the change listener - `javax.swing.event.ChangeListener`"
([^Style this ^javax.swing.event.ChangeListener l]
(-> this (.removeChangeListener l))))
| null | https://raw.githubusercontent.com/clojure-interop/java-jdk/8d7a223e0f9a0965eb0332fad595cf7649d9d96e/javax.swing/src/javax/swing/text/Style.clj | clojure | (ns javax.swing.text.Style
"A collection of attributes to associate with an element in a document.
Since these are typically used to associate character and paragraph
styles with the element, operations for this are provided. Other
customized attributes that get associated with the element will
effectively be name-value pairs that live in a hierarchy and if a name
(key) is not found locally, the request is forwarded to the parent.
Commonly used attributes are separated out to facilitate alternative
implementations that are more efficient."
(:refer-clojure :only [require comment defn ->])
(:import [javax.swing.text Style]))
(defn get-name
"Fetches the name of the style. A style is not required to be named,
so null is returned if there is no name
associated with the style.
returns: the name - `java.lang.String`"
(^java.lang.String [^Style this]
(-> this (.getName))))
(defn add-change-listener
"Adds a listener to track whenever an attribute
has been changed.
l - the change listener - `javax.swing.event.ChangeListener`"
([^Style this ^javax.swing.event.ChangeListener l]
(-> this (.addChangeListener l))))
(defn remove-change-listener
"Removes a listener that was tracking attribute changes.
l - the change listener - `javax.swing.event.ChangeListener`"
([^Style this ^javax.swing.event.ChangeListener l]
(-> this (.removeChangeListener l))))
| |
ce783b7ccd55b07449d1aa6322f01d58daf13fe7b1723e1241451150859b2b2b | jsa-aerial/DMM | oct_19_2016_experiment.clj | (ns dmm.examples.oct-19-2016-experiment
(:require [dmm.core :as dc
:refer [v-accum v-identity
down-movement up-movement
rec-map-sum]]))
; trying to build a very small network to reproduce the essence of
Project Fluid Aug 27 , 2016 experiment
(def init-matrix
{v-accum {:self {:accum {v-accum {:self {:single 1}}}}}})
(def update-1-matrix-hook
{v-identity {:update-1 {:single {v-identity {:update-1 {:single 1}}}}}})
(def update-2-matrix-hook
{v-identity {:update-2 {:single {v-identity {:update-2 {:single 1}}}}}})
(def update-3-matrix-hook
{v-identity {:update-3 {:single {v-identity {:update-3 {:single 1}}}}}})
(def start-update-of-network-matrix
{v-accum {:self {:delta {v-identity {:update-1 {:single 1}}}}}})
(def start-matrix
(rec-map-sum
init-matrix update-1-matrix-hook update-2-matrix-hook
update-3-matrix-hook start-update-of-network-matrix))
(def update-1-matrix
(rec-map-sum {v-accum {:self {:delta {v-identity {:update-1 {:single -1}}}}}}
{v-accum {:self {:delta {v-identity {:update-2 {:single 1}}}}}}))
(def update-2-matrix
(rec-map-sum {v-accum {:self {:delta {v-identity {:update-2 {:single -1}}}}}}
{v-accum {:self {:delta {v-identity {:update-3 {:single 1}}}}}}))
(def update-3-matrix
(rec-map-sum {v-accum {:self {:delta {v-identity {:update-3 {:single -1}}}}}}
{v-accum {:self {:delta {v-identity {:update-1 {:single 1}}}}}}))
; (def init-output {v-accum {:self {:single init-matrix}}})
(def init-output
(rec-map-sum {v-accum {:self {:single start-matrix}}}
{v-identity {:update-1 {:single update-1-matrix}}}
{v-identity {:update-2 {:single update-2-matrix}}}
{v-identity {:update-3 {:single update-3-matrix}}}))
(defn extract-matrix [current-output]
(((current-output v-accum) :self) :single))
(defn extract-delta [current-output]
((((extract-matrix current-output) v-accum) :self) :delta))
recording the experiment here on Oct 20 after the switch from
;;; accum to (var accum), and from identity to (var identity)
;;;
;;; also the difference here is that we are using iter-apply-fns to
;;; run network steps and that we actually re-run the network from the
;;; start each time (just because it's less typing and because we can)
(comment
(->> (dc/iter-apply-fns init-output down-movement up-movement)
rest (dc/map-every-other extract-delta)
(take 20)
(filter v-identity)
clojure.pprint/pprint)
user>
({#'clojure.core/identity {:update-2 {:single 1}}}
{#'clojure.core/identity {:update-3 {:single 1}}}
{#'clojure.core/identity {:update-1 {:single 1}}}
{#'clojure.core/identity {:update-2 {:single 1}}}
{#'clojure.core/identity {:update-3 {:single 1}}}
{#'clojure.core/identity {:update-1 {:single 1}}}
{#'clojure.core/identity {:update-2 {:single 1}}}
{#'clojure.core/identity {:update-3 {:single 1}}}
{#'clojure.core/identity {:update-1 {:single 1}}}
{#'clojure.core/identity {:update-2 {:single 1}}}))
; user=> (extract-delta init-output)
; {#'clojure.core/identity {:update-1 {:single 1}}}
user= > ( extract - delta ( first ( drop 2 ( iter - apply - fns init - output down - movement up - movement ) ) ) )
; {#'clojure.core/identity {:update-2 {:single 1}}}
user= > ( extract - delta ( first ( drop 4 ( iter - apply - fns init - output down - movement up - movement ) ) ) )
{ # ' clojure.core/identity { : update-3 { : single 1 } } }
user= > ( extract - delta ( first ( drop 6 ( iter - apply - fns init - output down - movement up - movement ) ) ) )
; {#'clojure.core/identity {:update-1 {:single 1}}}
user= > ( extract - delta ( first ( drop 8 ( iter - apply - fns init - output down - movement up - movement ) ) ) )
; {#'clojure.core/identity {:update-2 {:single 1}}}
user= > ( extract - delta ( first ( drop 10 ( iter - apply - fns init - output down - movement up - movement ) ) ) )
{ # ' clojure.core/identity { : update-3 { : single 1 } } }
user= > ( extract - delta ( first ( drop 12 ( iter - apply - fns init - output down - movement up - movement ) ) ) )
; {#'clojure.core/identity {:update-1 {:single 1}}}
| null | https://raw.githubusercontent.com/jsa-aerial/DMM/2baf47aaab227e8e1e0af64c187acf2384d205c5/examples/dmm/oct_19_2016_experiment.clj | clojure | trying to build a very small network to reproduce the essence of
(def init-output {v-accum {:self {:single init-matrix}}})
accum to (var accum), and from identity to (var identity)
also the difference here is that we are using iter-apply-fns to
run network steps and that we actually re-run the network from the
start each time (just because it's less typing and because we can)
user=> (extract-delta init-output)
{#'clojure.core/identity {:update-1 {:single 1}}}
{#'clojure.core/identity {:update-2 {:single 1}}}
{#'clojure.core/identity {:update-1 {:single 1}}}
{#'clojure.core/identity {:update-2 {:single 1}}}
{#'clojure.core/identity {:update-1 {:single 1}}} | (ns dmm.examples.oct-19-2016-experiment
(:require [dmm.core :as dc
:refer [v-accum v-identity
down-movement up-movement
rec-map-sum]]))
Project Fluid Aug 27 , 2016 experiment
(def init-matrix
{v-accum {:self {:accum {v-accum {:self {:single 1}}}}}})
(def update-1-matrix-hook
{v-identity {:update-1 {:single {v-identity {:update-1 {:single 1}}}}}})
(def update-2-matrix-hook
{v-identity {:update-2 {:single {v-identity {:update-2 {:single 1}}}}}})
(def update-3-matrix-hook
{v-identity {:update-3 {:single {v-identity {:update-3 {:single 1}}}}}})
(def start-update-of-network-matrix
{v-accum {:self {:delta {v-identity {:update-1 {:single 1}}}}}})
(def start-matrix
(rec-map-sum
init-matrix update-1-matrix-hook update-2-matrix-hook
update-3-matrix-hook start-update-of-network-matrix))
(def update-1-matrix
(rec-map-sum {v-accum {:self {:delta {v-identity {:update-1 {:single -1}}}}}}
{v-accum {:self {:delta {v-identity {:update-2 {:single 1}}}}}}))
(def update-2-matrix
(rec-map-sum {v-accum {:self {:delta {v-identity {:update-2 {:single -1}}}}}}
{v-accum {:self {:delta {v-identity {:update-3 {:single 1}}}}}}))
(def update-3-matrix
(rec-map-sum {v-accum {:self {:delta {v-identity {:update-3 {:single -1}}}}}}
{v-accum {:self {:delta {v-identity {:update-1 {:single 1}}}}}}))
(def init-output
(rec-map-sum {v-accum {:self {:single start-matrix}}}
{v-identity {:update-1 {:single update-1-matrix}}}
{v-identity {:update-2 {:single update-2-matrix}}}
{v-identity {:update-3 {:single update-3-matrix}}}))
(defn extract-matrix [current-output]
(((current-output v-accum) :self) :single))
(defn extract-delta [current-output]
((((extract-matrix current-output) v-accum) :self) :delta))
recording the experiment here on Oct 20 after the switch from
(comment
(->> (dc/iter-apply-fns init-output down-movement up-movement)
rest (dc/map-every-other extract-delta)
(take 20)
(filter v-identity)
clojure.pprint/pprint)
user>
({#'clojure.core/identity {:update-2 {:single 1}}}
{#'clojure.core/identity {:update-3 {:single 1}}}
{#'clojure.core/identity {:update-1 {:single 1}}}
{#'clojure.core/identity {:update-2 {:single 1}}}
{#'clojure.core/identity {:update-3 {:single 1}}}
{#'clojure.core/identity {:update-1 {:single 1}}}
{#'clojure.core/identity {:update-2 {:single 1}}}
{#'clojure.core/identity {:update-3 {:single 1}}}
{#'clojure.core/identity {:update-1 {:single 1}}}
{#'clojure.core/identity {:update-2 {:single 1}}}))
user= > ( extract - delta ( first ( drop 2 ( iter - apply - fns init - output down - movement up - movement ) ) ) )
user= > ( extract - delta ( first ( drop 4 ( iter - apply - fns init - output down - movement up - movement ) ) ) )
{ # ' clojure.core/identity { : update-3 { : single 1 } } }
user= > ( extract - delta ( first ( drop 6 ( iter - apply - fns init - output down - movement up - movement ) ) ) )
user= > ( extract - delta ( first ( drop 8 ( iter - apply - fns init - output down - movement up - movement ) ) ) )
user= > ( extract - delta ( first ( drop 10 ( iter - apply - fns init - output down - movement up - movement ) ) ) )
{ # ' clojure.core/identity { : update-3 { : single 1 } } }
user= > ( extract - delta ( first ( drop 12 ( iter - apply - fns init - output down - movement up - movement ) ) ) )
|
de2ad071520e6cd1df24813a7947eb9e260c95ed851e207ba280fa72c001b70f | tsloughter/kuberl | kuberl_v1beta1_job_template_spec.erl | -module(kuberl_v1beta1_job_template_spec).
-export([encode/1]).
-export_type([kuberl_v1beta1_job_template_spec/0]).
-type kuberl_v1beta1_job_template_spec() ::
#{ 'metadata' => kuberl_v1_object_meta:kuberl_v1_object_meta(),
'spec' => kuberl_v1_job_spec:kuberl_v1_job_spec()
}.
encode(#{ 'metadata' := Metadata,
'spec' := Spec
}) ->
#{ 'metadata' => Metadata,
'spec' => Spec
}.
| null | https://raw.githubusercontent.com/tsloughter/kuberl/f02ae6680d6ea5db6e8b6c7acbee8c4f9df482e2/gen/kuberl_v1beta1_job_template_spec.erl | erlang | -module(kuberl_v1beta1_job_template_spec).
-export([encode/1]).
-export_type([kuberl_v1beta1_job_template_spec/0]).
-type kuberl_v1beta1_job_template_spec() ::
#{ 'metadata' => kuberl_v1_object_meta:kuberl_v1_object_meta(),
'spec' => kuberl_v1_job_spec:kuberl_v1_job_spec()
}.
encode(#{ 'metadata' := Metadata,
'spec' := Spec
}) ->
#{ 'metadata' => Metadata,
'spec' => Spec
}.
| |
3ab2cea8aca1ea33f48ee8e36a3e6742725d2431ae9c51561a0d4c3855fb14e0 | rob7hunter/lawnelephant | settings-localhost.scm | (require (planet "settings.scm" ("vegashacker" "leftparen.plt" 5 (= 1))))
(setting-set! *PORT* 8765)
;; use #f if you want to listen to all incoming IPs:
(setting-set! *LISTEN_IP* "127.0.0.1")
(setting-set! *WEB_APP_URL* ":8765/")
;;(setting-set! *ALLOW_DEFINE_DEBUG* #t)
| null | https://raw.githubusercontent.com/rob7hunter/lawnelephant/9d3fdec5568e8f7a2165009debfd7a7075e750b3/settings-localhost.scm | scheme | use #f if you want to listen to all incoming IPs:
(setting-set! *ALLOW_DEFINE_DEBUG* #t) | (require (planet "settings.scm" ("vegashacker" "leftparen.plt" 5 (= 1))))
(setting-set! *PORT* 8765)
(setting-set! *LISTEN_IP* "127.0.0.1")
(setting-set! *WEB_APP_URL* ":8765/")
|
8e75455445da6516e735824a23a240eba1c08897e8be618e08fa05ee87ecc8f5 | clojure-quant/infra-guix | alacritty.scm | (define-module (awb99 home alacritty)
#:use-module (guix gexp)
#:use-module (guix packages)
#:use-module (gnu home services)
#:use-module (gnu home-services terminals))
(define-public alacritty-services
(list
(service home-alacritty-service-type
(home-alacritty-configuration
(config
`((window . ((dynamic_title . true)))
(cursor . ((style . ((shape . Beam)))))
(font . ((normal . ((family . Iosevka)
(style . Light)))
(bold . ((family . Iosevka)
(style . Light)))
(italic . ((family . Iosevka)
(style . Light)))
(size . 18.0)))
(draw_bold_text_with_bright_colors . true)
(colors . ((primary . ((background . "#FFFFFF")
(foreground . "#000000")))
(cursor . ((cursor . "#000000")))
(selection . ((background . "#E8DFD1")
(foreground . "#000000")))
(normal . ((black . "#000000")
(red . "#A60000")
(green . "#005E00")
(yellow . "#813E00")
(blue . "#0031A9")
(magenta . "#721045")
(cyan . "#00538B")
(white . "#BFBFBF")))
(bright . ((black . "#595959")
(red . "#972500")
(green . "#315B00")
(yellow . "#70480F")
(blue . "#2544BB")
(magenta . "#5317AC")
(cyan . "#005A5F")
(white . "#FFFFFF")))))
(key_bindings . #(((key . C)
(mods . Alt)
(action . Copy))
;((key . C)
; (mods . Control)
; (action . Copy))
((key . V)
(mods . Control)
(action . Paste)))))))))) | null | https://raw.githubusercontent.com/clojure-quant/infra-guix/e98de1ab81bb0d68cdd4f1971ebd73d0b2cc7414/modules/awb99/home/alacritty.scm | scheme | ((key . C)
(mods . Control)
(action . Copy)) | (define-module (awb99 home alacritty)
#:use-module (guix gexp)
#:use-module (guix packages)
#:use-module (gnu home services)
#:use-module (gnu home-services terminals))
(define-public alacritty-services
(list
(service home-alacritty-service-type
(home-alacritty-configuration
(config
`((window . ((dynamic_title . true)))
(cursor . ((style . ((shape . Beam)))))
(font . ((normal . ((family . Iosevka)
(style . Light)))
(bold . ((family . Iosevka)
(style . Light)))
(italic . ((family . Iosevka)
(style . Light)))
(size . 18.0)))
(draw_bold_text_with_bright_colors . true)
(colors . ((primary . ((background . "#FFFFFF")
(foreground . "#000000")))
(cursor . ((cursor . "#000000")))
(selection . ((background . "#E8DFD1")
(foreground . "#000000")))
(normal . ((black . "#000000")
(red . "#A60000")
(green . "#005E00")
(yellow . "#813E00")
(blue . "#0031A9")
(magenta . "#721045")
(cyan . "#00538B")
(white . "#BFBFBF")))
(bright . ((black . "#595959")
(red . "#972500")
(green . "#315B00")
(yellow . "#70480F")
(blue . "#2544BB")
(magenta . "#5317AC")
(cyan . "#005A5F")
(white . "#FFFFFF")))))
(key_bindings . #(((key . C)
(mods . Alt)
(action . Copy))
((key . V)
(mods . Control)
(action . Paste)))))))))) |
547b1f83c8957761f99b904fdd7c8a4c3155b66f4e65c22ae9f3b3854938a3a9 | Simspace/postgresql-tx | Unsafe.hs | module Database.PostgreSQL.Tx.Unsafe
( -- * Introduction
-- $intro
-- ** Operations
unsafeRunIOInTxM
, unsafeWithRunInIOTxM
-- ** For adaptor libraries
, unsafeUnTxM
, unsafeRunTxM
, unsafeMkTxM
, unsafeMksTxM
, unsafeLookupTxEnvIO
, unsafeMkTxException
) where
import Database.PostgreSQL.Tx.Internal
-- $intro
--
-- @postgresql-tx@ discourages performing arbitrary 'IO' within a database
-- transaction, but sometimes performing this 'IO' is necessary. This module
-- provides operations and infrastructure for performing "unsafe" 'IO' actions
-- within 'TxM' or a specific database library implementation monad. It also
-- provides utilities for use in adaptor libraries.
--
-- Clients must explicitly import this module to perform 'IO' in 'TxM' or a
-- specific database library implementation monad. All functions this module
provides are prefixed with @unsafe*@. These two factors serve as annotation
-- to simplify understanding exactly which parts of transactional database code
are performing arbitary ' IO ' .
| null | https://raw.githubusercontent.com/Simspace/postgresql-tx/6769f10a4b928aa37c47ffa5f89f0fa3a9c6fc01/src/Database/PostgreSQL/Tx/Unsafe.hs | haskell | * Introduction
$intro
** Operations
** For adaptor libraries
$intro
@postgresql-tx@ discourages performing arbitrary 'IO' within a database
transaction, but sometimes performing this 'IO' is necessary. This module
provides operations and infrastructure for performing "unsafe" 'IO' actions
within 'TxM' or a specific database library implementation monad. It also
provides utilities for use in adaptor libraries.
Clients must explicitly import this module to perform 'IO' in 'TxM' or a
specific database library implementation monad. All functions this module
to simplify understanding exactly which parts of transactional database code | module Database.PostgreSQL.Tx.Unsafe
unsafeRunIOInTxM
, unsafeWithRunInIOTxM
, unsafeUnTxM
, unsafeRunTxM
, unsafeMkTxM
, unsafeMksTxM
, unsafeLookupTxEnvIO
, unsafeMkTxException
) where
import Database.PostgreSQL.Tx.Internal
provides are prefixed with @unsafe*@. These two factors serve as annotation
are performing arbitary ' IO ' .
|
e6da88c890cc0f5a499845ccc4745175e9930dbc5d2b918fb010c5f99487a581 | GaloisInc/semmc | Components.hs | module SemMC.Architecture.ARM.Components
(
-- * Parsing
Parser
)
where
import Text.Megaparsec
import Text . .
import Text . . .
type Parser = Parsec String String
| null | https://raw.githubusercontent.com/GaloisInc/semmc/4dc4439720b3b0de8812a68f8156dc89da76da57/semmc-arm/src/SemMC/Architecture/ARM/Components.hs | haskell | * Parsing | module SemMC.Architecture.ARM.Components
(
Parser
)
where
import Text.Megaparsec
import Text . .
import Text . . .
type Parser = Parsec String String
|
99754f9737f4c9f6c3317f65ee1b417a8e22ff0a8ad1bc46e4d67e80bfe47a0a | froggey/Mezzano | ata.lisp | Legacy PCI ATA disk driver
(defpackage :mezzano.supervisor.ata
(:use :cl)
(:local-nicknames (:sup :mezzano.supervisor)
(:pci :mezzano.supervisor.pci)
(:sys.int :mezzano.internals))
(:export #:read-ata-string
;; Bits in registers.
#:+ata-dev+
#:+ata-lba+
#:+ata-err+
#:+ata-drq+
#:+ata-df+
#:+ata-drdy+
#:+ata-bsy+
#:+ata-nien+
#:+ata-srst+
#:+ata-hob+
#:+ata-abrt+
;; Commands.
#:+ata-command-read-sectors+
#:+ata-command-read-sectors-ext+
#:+ata-command-read-dma+
#:+ata-command-read-dma-ext+
#:+ata-command-write-sectors+
#:+ata-command-write-sectors-ext+
#:+ata-command-write-dma+
#:+ata-command-write-dma-ext+
#:+ata-command-flush-cache+
#:+ata-command-flush-cache-ext+
#:+ata-command-identify+
#:+ata-command-identify-packet+
#:+ata-command-packet+))
(in-package :mezzano.supervisor.ata)
(defconstant +ata-compat-primary-command+ #x1F0)
(defconstant +ata-compat-primary-control+ #x3F0)
(defconstant +ata-compat-primary-irq+ 14)
(defconstant +ata-compat-secondary-command+ #x170)
(defconstant +ata-compat-secondary-control+ #x370)
(defconstant +ata-compat-secondary-irq+ 15)
(defconstant +ata-register-data+ 0) ; read/write
(defconstant +ata-register-error+ 1) ; read
(defconstant +ata-register-features+ 1) ; write
(defconstant +ata-register-count+ 2) ; read/write
(defconstant +ata-register-lba-low+ 3) ; read/write
(defconstant +ata-register-lba-mid+ 4) ; read/write
(defconstant +ata-register-lba-high+ 5) ; read/write
(defconstant +ata-register-device+ 6) ; read/write
(defconstant +ata-register-status+ 7) ; read
(defconstant +ata-register-command+ 7) ; write
(defconstant +ata-register-alt-status+ 6) ; read
(defconstant +ata-register-device-control+ 6) ; write
(defconstant +ata-bmr-command+ 0) ; write
(defconstant +ata-bmr-status+ 2) ; write
(defconstant +ata-bmr-prdt-address+ 4) ; write
(defconstant +ata-bmr-command-start+ #x01)
(defconstant +ata-bmr-direction-read/write+ #x08) ; set to read, clear to write.
(defconstant +ata-bmr-status-active+ #x01)
(defconstant +ata-bmr-status-error+ #x02)
(defconstant +ata-bmr-status-interrupt+ #x04)
(defconstant +ata-bmr-status-drive-0-dma-capable+ #x20)
(defconstant +ata-bmr-status-drive-1-dma-capable+ #x40)
(defconstant +ata-bmr-status-simplex+ #x80)
;; Device bits.
(defconstant +ata-dev+ #x10 "Select device 0 when clear, device 1 when set.")
(defconstant +ata-lba+ #x40 "Set when using LBA.")
;; Status bits.
(defconstant +ata-err+ #x01 "An error occured during command execution.")
(defconstant +ata-drq+ #x08 "Device is ready to transfer data.")
(defconstant +ata-df+ #x20 "Device fault.")
(defconstant +ata-drdy+ #x40 "Device is ready to accept commands.")
(defconstant +ata-bsy+ #x80 "Device is busy.")
;; Device Control bits.
(defconstant +ata-nien+ #x02 "Mask interrupts.")
(defconstant +ata-srst+ #x04 "Initiate a software reset.")
(defconstant +ata-hob+ #x80 "Read LBA48 high-order bytes.")
;; Error bits.
(defconstant +ata-abrt+ #x04 "Command aborted by device.")
;; Commands.
(defconstant +ata-command-read-sectors+ #x20)
(defconstant +ata-command-read-sectors-ext+ #x24)
(defconstant +ata-command-read-dma+ #xC8)
(defconstant +ata-command-read-dma-ext+ #x25)
(defconstant +ata-command-write-sectors+ #x30)
(defconstant +ata-command-write-sectors-ext+ #x3A)
(defconstant +ata-command-write-dma+ #xCA)
(defconstant +ata-command-write-dma-ext+ #x35)
(defconstant +ata-command-flush-cache+ #xE7)
(defconstant +ata-command-flush-cache-ext+ #xEA)
(defconstant +ata-command-identify+ #xEC)
(defconstant +ata-command-identify-packet+ #xA1)
(defconstant +ata-command-packet+ #xA0)
(defstruct (ata-controller
(:area :wired))
command
control
bus-master-register
prdt-phys
irq
current-channel
irq-latch
irq-timeout-timer
irq-watcher
bounce-buffer)
(defstruct (ata-device
(:area :wired))
controller
channel
block-size
sector-count
lba48-capable)
(defstruct (atapi-device
(:area :wired))
controller
channel
cdb-size
initialized-p)
(defun ata-error (controller)
"Read the error register."
(sys.int::io-port/8 (+ (ata-controller-command controller)
+ata-register-error+)))
(defun ata-status (controller)
"Read the status register."
(sys.int::io-port/8 (+ (ata-controller-command controller)
+ata-register-status+)))
(defun ata-alt-status (controller)
"Read the alternate status register."
(sys.int::io-port/8 (+ (ata-controller-control controller)
+ata-register-alt-status+)))
(defun ata-wait-for-controller (controller mask value timeout)
"Wait for the bits in the alt-status register masked by MASK to become equal to VALUE.
Returns true when the bits are equal, false when the timeout expires or if the device sets ERR."
(loop
(let ((status (ata-alt-status controller)))
(when (logtest status +ata-err+)
(return nil))
(when (eql (logand status mask) value)
(return t)))
(when (<= timeout 0)
(return nil))
;; FIXME: Depends on the granularity of the timer, as does
;; intel-8042::+delay+.
(sup:safe-sleep 0.01)
(decf timeout 0.01)))
(defun ata-select-device (controller channel)
;; select-device should never be called with a command in progress on the controller.
(when (logtest (logior +ata-bsy+ +ata-drq+)
(ata-alt-status controller))
(sup:debug-print-line "ATA-SELECT-DEVICE called with command in progress.")
(return-from ata-select-device nil))
(when (not (eql (ata-controller-current-channel controller) channel))
(assert (or (eql channel :device-0) (eql channel :device-1)))
(setf (sys.int::io-port/8 (+ (ata-controller-command controller)
+ata-register-device+))
(ecase channel
(:device-0 0)
(:device-1 +ata-dev+)))
Again , neither BSY nor DRQ should be set .
(when (logtest (logior +ata-bsy+ +ata-drq+)
(ata-alt-status controller))
(sup:debug-print-line "ATA-SELECT-DEVICE called with command in progress.")
(return-from ata-select-device nil))
(setf (ata-controller-current-channel controller) channel))
t)
(defun ata-detect-packet-device (controller channel)
(let ((buf (sys.int::make-simple-vector 256 :wired)))
;; Select the device.
(when (not (ata-select-device controller channel))
(sup:debug-print-line "Could not select ata device when probing.")
(return-from ata-detect-packet-device nil))
;; Issue IDENTIFY.
(setf (sys.int::io-port/8 (+ (ata-controller-command controller)
+ata-register-command+))
+ata-command-identify-packet+)
after writing command .
(ata-alt-status controller)
Wait for BSY to clear and DRQ to go high .
Use a 1 second timeout .
;; I don't know if there's a standard timeout for this, but
I figure that the device should respond to IDENTIFY quickly .
Wrong blah ! - wait - for - controller is nonsense .
if = 0 & drq = 0 , then there was an error .
(let ((success (ata-wait-for-controller controller (logior +ata-bsy+ +ata-drq+) +ata-drq+ 1)))
;; Read the status register to clear the pending interrupt flag.
(sys.int::io-port/8 (+ (ata-controller-command controller)
+ata-register-status+))
Check before checking for timeout .
ATAPI devices will abort , and wait - for - controller will time out .
(when (logtest (ata-alt-status controller) +ata-err+)
(sup:debug-print-line "IDENTIFY PACKET aborted by device.")
(return-from ata-detect-packet-device))
(when (not success)
(sup:debug-print-line "Timeout while waiting for DRQ during IDENTIFY PACKET.")
(return-from ata-detect-packet-device)))
;; Read data.
(dotimes (i 256)
(setf (svref buf i) (sys.int::io-port/16 (+ (ata-controller-command controller)
+ata-register-data+))))
(let* ((general-config (svref buf 0))
(cdb-size (case (ldb (byte 2 0) general-config)
(0 12)
(1 16))))
(sup:debug-print-line "PACKET device:")
(sup:debug-print-line " General configuration: " general-config)
(sup:debug-print-line " Specific configuration: " (svref buf 2))
(sup:debug-print-line " Capabilities: " (svref buf 49) " " (svref buf 50))
(sup:debug-print-line " Field validity: " (svref buf 53))
(sup:debug-print-line " DMADIR: " (svref buf 62))
(sup:debug-print-line " Multiword DMA transfer: " (svref buf 63))
(sup:debug-print-line " PIO transfer mode supported: " (svref buf 64))
(sup:debug-print-line " Features: " (svref buf 82) " " (svref buf 83) " " (svref buf 84) " " (svref buf 85) " " (svref buf 86) " " (svref buf 87))
(sup:debug-print-line " Removable Media Notification: " (svref buf 127))
(when (or (not (logbitp 15 general-config))
(logbitp 14 general-config))
(sup:debug-print-line "Device does not implement the PACKET command set.")
(return-from ata-detect-packet-device))
(when (not (eql (ldb (byte 5 8) general-config) 5))
(sup:debug-print-line "PACKET device is not a CD-ROM drive.")
(return-from ata-detect-packet-device))
(when (not cdb-size)
(sup:debug-print-line "PACKET device has unsupported CDB size " (ldb (byte 2 0) (svref buf 0)))
(return-from ata-detect-packet-device))
(let ((device (make-atapi-device :controller controller
:channel channel
:cdb-size cdb-size
:initialized-p nil)))
(mezzano.supervisor.cdrom:cdrom-initialize-device device cdb-size 'ata-issue-packet-command)
(setf (atapi-device-initialized-p device) t)))))
(defun read-ata-string (identify-data start end read-fn)
(let ((len (* (- end start) 2)))
;; Size the string, can't resize wired strings yet...
(loop
(when (zerop len)
(return))
(let* ((word (funcall read-fn identify-data (+ start (ash (1- len) -1))))
(byte (if (logtest (1- len) 1)
(ldb (byte 8 0) word)
(ldb (byte 8 8) word))))
(when (not (eql byte #x20))
(return)))
(decf len))
(let ((string (mezzano.runtime::make-wired-string len)))
(dotimes (i len)
(let* ((word (funcall read-fn identify-data (+ start (ash i -1))))
(byte (if (logtest i 1)
(ldb (byte 8 0) word)
(ldb (byte 8 8) word))))
(setf (char string i) (code-char byte))))
string)))
(defun ata-detect-drive (controller channel)
(let ((buf (sys.int::make-simple-vector 256 :wired)))
;; Select the device.
(when (not (ata-select-device controller channel))
(sup:debug-print-line "Could not select ata device when probing.")
(return-from ata-detect-drive nil))
;; Issue IDENTIFY.
(setf (sys.int::io-port/8 (+ (ata-controller-command controller)
+ata-register-command+))
+ata-command-identify+)
after writing command .
(ata-alt-status controller)
Wait for BSY to clear and DRQ to go high .
Use a 1 second timeout .
;; I don't know if there's a standard timeout for this, but
I figure that the device should respond to IDENTIFY quickly .
Wrong blah ! - wait - for - controller is nonsense .
if = 0 & drq = 0 , then there was an error .
(let ((success (ata-wait-for-controller controller (logior +ata-bsy+ +ata-drq+) +ata-drq+ 1)))
;; Read the status register to clear the pending interrupt flag.
(sys.int::io-port/8 (+ (ata-controller-command controller)
+ata-register-status+))
Check before checking for timeout .
ATAPI devices will abort , and wait - for - controller will time out .
(when (logtest (ata-alt-status controller) +ata-err+)
(if (and (logtest (sys.int::io-port/8 (+ (ata-controller-command controller)
+ata-register-error+))
+ata-abrt+)
;; The LBA low and interrupt reason registers should both be set to #x01,
;; but some hardware is broken and doesn't do this.
(eql (sys.int::io-port/8 (+ (ata-controller-command controller)
+ata-register-lba-mid+))
#x14)
(eql (sys.int::io-port/8 (+ (ata-controller-command controller)
+ata-register-lba-high+))
#xEB))
(return-from ata-detect-drive
(ata-detect-packet-device controller channel))
(sup:debug-print-line "IDENTIFY aborted by device."))
(return-from ata-detect-drive))
(when (not success)
(sup:debug-print-line "Timeout while waiting for DRQ during IDENTIFY.")
(return-from ata-detect-drive)))
;; Read data.
(dotimes (i 256)
(setf (svref buf i) (sys.int::io-port/16 (+ (ata-controller-command controller)
+ata-register-data+))))
(let* ((supported-command-sets (svref buf 83))
(lba48-capable (logbitp 10 supported-command-sets))
(sector-size (if (and (logbitp 14 (svref buf 106))
(not (logbitp 13 (svref buf 106))))
;; Data in logical sector size field valid.
(logior (svref buf 117)
(ash (svref buf 118) 16))
Not valid , use 512 .
512))
(sector-count (if lba48-capable
(logior (svref buf 100)
(ash (svref buf 101) 16)
(ash (svref buf 102) 32)
(ash (svref buf 103) 48))
(logior (svref buf 60)
(ash (svref buf 61) 16))))
(device (make-ata-device :controller controller
:channel channel
:block-size sector-size
:sector-count sector-count
:lba48-capable lba48-capable))
(serial-number (read-ata-string buf 10 20 #'svref))
(model-number (read-ata-string buf 27 47 #'svref)))
(when (eql sector-size 0)
VmWare seems to do this , are we not interpreting the identify data properly ?
(sup:debug-print-line "*** Disk is reporting sector size? Assuming 512 bytes")
(setf sector-size 512))
(sup:debug-print-line "Features (83): " supported-command-sets)
(sup:debug-print-line "Sector size: " sector-size)
(sup:debug-print-line "Sector count: " sector-count)
(sup:debug-print-line "Serial: " serial-number)
(sup:debug-print-line "Model: " model-number)
(sup:register-disk device
t
(ata-device-sector-count device)
(ata-device-block-size device)
256
'ata-read 'ata-write 'ata-flush
(sys.int::cons-in-area
model-number
(sys.int::cons-in-area
serial-number
nil
:wired)
:wired)))))
(defun ata-issue-lba28-command (device lba count command)
(let ((controller (ata-device-controller device)))
;; Select the device.
(when (not (ata-select-device controller (ata-device-channel device)))
(sup:debug-print-line "Could not select ata device.")
(return-from ata-issue-lba28-command nil))
(setf (sup:event-state (ata-controller-irq-latch controller)) nil)
;; HI3: Write_parameters
(setf (sys.int::io-port/8 (+ (ata-controller-command controller)
+ata-register-count+))
(if (eql count 256)
0
count))
(setf (sys.int::io-port/8 (+ (ata-controller-command controller)
+ata-register-lba-low+))
(ldb (byte 8 0) lba))
(setf (sys.int::io-port/8 (+ (ata-controller-command controller)
+ata-register-lba-mid+))
(ldb (byte 8 8) lba))
(setf (sys.int::io-port/8 (+ (ata-controller-command controller)
+ata-register-lba-high+))
(ldb (byte 8 16) lba))
(setf (sys.int::io-port/8 (+ (ata-controller-command controller)
+ata-register-device+))
(logior (ecase (ata-device-channel device)
(:device-0 0)
(:device-1 +ata-dev+))
+ata-lba+
(ldb (byte 4 24) lba)))
HI4 : Write_command
(setf (sys.int::io-port/8 (+ (ata-controller-command controller)
+ata-register-command+))
command))
t)
(defun ata-issue-lba48-command (device lba count command)
(let* ((controller (ata-device-controller device))
(command-base (ata-controller-command controller)))
;; Select the device.
(when (not (ata-select-device controller (ata-device-channel device)))
(sup:debug-print-line "Could not select ata device.")
(return-from ata-issue-lba48-command nil))
(setf (sup:event-state (ata-controller-irq-latch controller)) nil)
;; HI3: Write_parameters
(when (eql count 65536)
(setf count 0))
(flet ((wr (reg val)
(setf (sys.int::io-port/8 (+ command-base reg)) val)))
(declare (dynamic-extent #'wr))
(wr +ata-register-count+ (ldb (byte 8 8) count))
(wr +ata-register-count+ (ldb (byte 8 0) count))
(wr +ata-register-lba-high+ (ldb (byte 8 40) lba))
(wr +ata-register-lba-mid+ (ldb (byte 8 32) lba))
(wr +ata-register-lba-low+ (ldb (byte 8 24) lba))
(wr +ata-register-lba-high+ (ldb (byte 8 16) lba))
(wr +ata-register-lba-mid+ (ldb (byte 8 8) lba))
(wr +ata-register-lba-low+ (ldb (byte 8 0) lba))
(wr +ata-register-device+ (logior (ecase (ata-device-channel device)
(:device-0 0)
(:device-1 +ata-dev+))
+ata-lba+))
HI4 : Write_command
(wr +ata-register-command+ command)))
t)
(defun ata-check-status (controller &optional (timeout 30))
"Wait until BSY clears, then return two values.
First is true if DRQ is set, false if DRQ is clear or timeout.
Second is true if the timeout expired.
This is used to implement the Check_Status states of the various command protocols."
;; Sample the alt-status register for the required delay.
(ata-alt-status controller)
(loop
(let ((status (ata-alt-status controller)))
(when (not (logtest status +ata-bsy+))
(return (values (logtest status +ata-drq+)
nil)))
Stay in Check_Status .
(when (<= timeout 0)
(return (values nil t)))
(sup:safe-sleep 0.001)
(decf timeout 0.001))))
(defun ata-intrq-wait (controller &optional (timeout 30))
"Wait for a interrupt from the device.
This is used to implement the INTRQ_Wait state."
(sup:timer-arm timeout (ata-controller-irq-timeout-timer controller))
(sup:watcher-wait (ata-controller-irq-watcher controller))
(when (not (sup:event-state (ata-controller-irq-latch controller)))
(sup:ensure (sup:timer-expired-p (ata-controller-irq-timeout-timer controller)))
;; FIXME: Do something better than this.
(sup:debug-print-line "*** ATA-INTRQ-WAIT TIMEOUT EXPIRED! ***"))
;; -absolute is non-consing
(sup:timer-disarm-absolute (ata-controller-irq-timeout-timer controller))
(setf (sup:event-state (ata-controller-irq-latch controller)) nil))
(defun ata-pio-data-in (device count mem-addr)
"Implement the PIO data-in protocol."
(let ((controller (ata-device-controller device)))
(loop
HPIOI0 : INTRQ_wait
(ata-intrq-wait controller)
HPIOI1 : Check_Status
(multiple-value-bind (drq timed-out)
(ata-check-status controller)
(when timed-out
;; FIXME: Should reset the device here.
(sup:debug-print-line "Device timeout during PIO data in.")
(return-from ata-pio-data-in nil))
(when (not drq)
;; FIXME: Should reset the device here.
(sup:debug-print-line "Device error during PIO data in.")
(return-from ata-pio-data-in nil)))
;; HPIOI2: Transfer_Data
FIXME : non-512 byte sectors , non 2 - byte words .
(setf (sys.int::memref-unsigned-byte-16 mem-addr 0)
(sys.int::io-port/16 (+ (ata-controller-command controller)
+ata-register-data+)))
(incf mem-addr 2))
;; If there are no more blocks to transfer, transition back to host idle,
otherwise return to HPIOI0 .
(when (zerop (decf count))
(return t)))))
(defun ata-pio-data-out (device count mem-addr)
"Implement the PIO data-out protocol."
(let ((controller (ata-device-controller device)))
(loop
HPIOO0 : Check_Status
(multiple-value-bind (drq timed-out)
(ata-check-status controller)
(when timed-out
;; FIXME: Should reset the device here.
(sup:debug-print-line "Device timeout during PIO data out.")
(return-from ata-pio-data-out nil))
(when (not drq)
(cond ((zerop count)
;; All data transfered successfully.
(return-from ata-pio-data-out t))
(t ;; Error?
;; FIXME: Should reset the device here.
(sup:debug-print-line "Device error during PIO data out.")
(return-from ata-pio-data-out nil)))))
;; HPIOO1: Transfer_Data
FIXME : non-512 byte sectors , non 2 - byte words .
(setf (sys.int::io-port/16 (+ (ata-controller-command controller)
+ata-register-data+))
(sys.int::memref-unsigned-byte-16 mem-addr 0))
(incf mem-addr 2))
;; HPIOO2: INTRQ_Wait
(ata-intrq-wait controller)
;; Return to HPIOO0.
(decf count))))
(defun ata-configure-prdt (controller phys-addr n-octets direction)
(let* ((prdt (ata-controller-prdt-phys controller))
(prdt-virt (sup::convert-to-pmap-address prdt)))
(sup:ensure (<= (+ phys-addr n-octets) #x100000000))
(sup:ensure (not (eql n-octets 0)))
(do ((offset 0 (+ offset 2)))
((<= n-octets #x10000)
;; Write final chunk.
(setf (sys.int::memref-unsigned-byte-32 prdt-virt offset) phys-addr
(sys.int::memref-unsigned-byte-32 prdt-virt (1+ offset)) (logior #x80000000 n-octets)))
Write 64k chunks .
(setf (sys.int::memref-unsigned-byte-32 prdt-virt offset) phys-addr
0 = 64k
(incf phys-addr #x10000)
(decf n-octets #x10000))
Write the PRDT location .
(setf (pci:pci-io-region/32 (ata-controller-bus-master-register controller) +ata-bmr-prdt-address+) prdt
Clear DMA status . Yup . You have to write 1 to clear bits .
(pci:pci-io-region/8 (ata-controller-bus-master-register controller) +ata-bmr-status+) (logior +ata-bmr-status-error+ +ata-bmr-status-interrupt+)
;; Set direction.
(pci:pci-io-region/8 (ata-controller-bus-master-register controller) +ata-bmr-command+) (ecase direction
(:read +ata-bmr-direction-read/write+)
(:write 0)))))
(defun ata-read-write (device lba count mem-addr what dma-fn pio-fn)
(let ((controller (ata-device-controller device)))
(sup:ensure (>= lba 0))
(sup:ensure (>= count 0))
(sup:ensure (<= (+ lba count) (ata-device-sector-count device)))
(cond
((ata-device-lba48-capable device)
(when (> count 65536)
(sup:debug-print-line "Can't do " what " of more than 65,536 sectors.")
(return-from ata-read-write (values nil :too-many-sectors))))
(t
(when (> count 256)
(sup:debug-print-line "Can't do " what " of more than 256 sectors.")
(return-from ata-read-write (values nil :too-many-sectors)))))
(when (eql count 0)
(return-from ata-read-write t))
(cond ((and (<= sup::+physical-map-base+ mem-addr)
4 GB limit .
(< mem-addr (+ sup::+physical-map-base+ (* 4 1024 1024 1024))))
(funcall dma-fn controller device lba count (- mem-addr sup::+physical-map-base+)))
((eql (* count (ata-device-block-size device)) sup::+4k-page-size+)
;; Transfer is small enough that the bounce page can be used.
(let* ((bounce-frame (ata-controller-bounce-buffer controller))
(bounce-phys (ash bounce-frame 12))
(bounce-virt (sup::convert-to-pmap-address bounce-phys)))
;; FIXME: Don't copy a whole page
(when (eql what :write)
(sup::%fast-page-copy bounce-virt mem-addr))
(funcall dma-fn controller device lba count bounce-phys)
(when (eql what :read)
(sup::%fast-page-copy mem-addr bounce-virt))))
Give up and do a slow PIO transfer .
(funcall pio-fn controller device lba count mem-addr))))
t)
(defun ata-issue-lba-command (device lba count command28 command48)
(if (ata-device-lba48-capable device)
(ata-issue-lba48-command device lba count command48)
(ata-issue-lba28-command device lba count command28)))
(defun ata-read-pio (controller device lba count mem-addr)
(declare (ignore controller))
(when (not (ata-issue-lba-command device lba count
+ata-command-read-sectors+
+ata-command-read-sectors-ext+))
(return-from ata-read-pio (values nil :device-error)))
(when (not (ata-pio-data-in device count mem-addr))
(return-from ata-read-pio (values nil :device-error))))
(defun ata-read-dma (controller device lba count phys-addr)
(ata-configure-prdt controller phys-addr (* count 512) :read)
(when (not (ata-issue-lba-command device lba count
+ata-command-read-dma+
+ata-command-read-dma-ext+))
(return-from ata-read-dma (values nil :device-error)))
Start DMA .
FIXME : has absurd timing requirements here . Needs to be * immediately * ( tens of instructions )
;; after the command write.
(setf (pci:pci-io-region/8 (ata-controller-bus-master-register controller) +ata-bmr-command+) (logior +ata-bmr-command-start+
+ata-bmr-direction-read/write+))
;; Wait for completion.
(ata-intrq-wait controller)
(let ((status (pci:pci-io-region/8 (ata-controller-bus-master-register controller) +ata-bmr-status+)))
;; Stop the transfer.
(setf (pci:pci-io-region/8 (ata-controller-bus-master-register controller) +ata-bmr-command+) +ata-bmr-direction-read/write+)
;; Clear error bit.
(setf (pci:pci-io-region/8 (ata-controller-bus-master-register controller) +ata-bmr-status+) (logior status +ata-bmr-status-error+ +ata-bmr-status-interrupt+))
(if (logtest status +ata-bmr-status-error+)
(values nil :device-error)
t)))
(defun ata-read (device lba count mem-addr)
(ata-read-write device lba count mem-addr
:read #'ata-read-dma #'ata-read-pio))
(defun ata-write-pio (controller device lba count mem-addr)
(declare (ignore controller))
(when (not (ata-issue-lba-command device lba count
+ata-command-write-sectors+
+ata-command-write-sectors-ext+))
(return-from ata-write-pio (values nil :device-error)))
(when (not (ata-pio-data-out device count mem-addr))
(return-from ata-write-pio (values nil :device-error))))
(defun ata-write-dma (controller device lba count phys-addr)
(ata-configure-prdt controller phys-addr (* count 512) :write)
(when (not (ata-issue-lba-command device lba count
+ata-command-write-dma+
+ata-command-write-dma-ext+))
(return-from ata-write-dma (values nil :device-error)))
Start DMA .
FIXME : has absurd timing requirements here . Needs to be * immediately * ( tens of instructions )
;; after the command write.
(setf (pci:pci-io-region/8 (ata-controller-bus-master-register controller) +ata-bmr-command+) +ata-bmr-command-start+)
;; Wait for completion.
(ata-intrq-wait controller)
(let ((status (pci:pci-io-region/8 (ata-controller-bus-master-register controller) +ata-bmr-status+)))
;; Stop the transfer.
(setf (pci:pci-io-region/8 (ata-controller-bus-master-register controller) +ata-bmr-command+) 0)
;; Clear error bit.
(setf (pci:pci-io-region/8 (ata-controller-bus-master-register controller) +ata-bmr-status+) (logior status +ata-bmr-status-error+ +ata-bmr-status-interrupt+))
(if (logtest status +ata-bmr-status-error+)
(values nil :device-error)
t)))
(defun ata-write (device lba count mem-addr)
(ata-read-write device lba count mem-addr
:write #'ata-write-dma #'ata-write-pio))
(defun ata-flush (device)
(let ((controller (ata-device-controller device)))
(when (not (ata-issue-lba-command device 0 0
+ata-command-flush-cache+
+ata-command-flush-cache-ext+))
(return-from ata-flush (values nil :device-error)))
;; HND0: INTRQ_Wait
(ata-intrq-wait controller)
HND1 : Check_Status
;; Sample the alt-status register for the required delay.
(ata-alt-status controller)
(loop
Spec sez flush can take longer than 30 but I ca n't find an upper bound .
do
(when (not (logtest (ata-alt-status controller) +ata-bsy+))
(return))
Stay in Check_Status .
(when (<= timeout 0)
;; FIXME: Should reset the device here.
(sup:debug-print-line "Device timeout during flush.")
(return-from ata-flush (values nil :device-error)))
(sup:safe-sleep 0.001)
(decf timeout 0.001))
;; Transition to Host_Idle, checking error status.
(when (logtest (ata-alt-status controller) +ata-err+)
(sup:debug-print-line "Device error " (ata-error controller) " during flush.")
(return-from ata-flush (values nil :device-error)))
t))
(defun ata-submit-packet-command (device cdb result-len dma dmadir)
(let* ((controller (atapi-device-controller device))
(command-base (ata-controller-command controller)))
;; Select the device.
(when (not (ata-select-device controller (atapi-device-channel device)))
(sup:debug-print-line "Could not select ata device.")
(return-from ata-submit-packet-command nil))
(setf (sup:event-state (ata-controller-irq-latch controller)) nil)
;; HI3: Write_parameters
(flet ((wr (reg val)
(setf (sys.int::io-port/8 (+ command-base reg)) val)))
(declare (dynamic-extent #'wr))
(wr +ata-register-features+ (if dma
(logior #b0001
(ecase dmadir
(:device-to-host #b0100)
(:host-to-device #b0000)))
#b0000))
;; Set maximum transfer size.
(cond ((eql result-len 0)
;; Some devices use 0 to mean some other value, use a tiny result instead.
(wr +ata-register-lba-mid+ 2)
(wr +ata-register-lba-high+ 0))
(t
(wr +ata-register-lba-mid+ (ldb (byte 8 0) result-len))
(wr +ata-register-lba-high+ (ldb (byte 8 8) result-len))))
HI4 : Write_command
(wr +ata-register-command+ +ata-command-packet+))
after writing command .
(ata-alt-status controller)
;; HP0: Check_Status_A
(multiple-value-bind (drq timed-out)
(ata-check-status controller)
(when timed-out
;; FIXME: Should reset the device here.
(sup:debug-print-line "Device timeout during PACKET Check_Status_A.")
(return-from ata-submit-packet-command nil))
(when (not drq)
;; FIXME: Should reset the device here.
(sup:debug-print-line "Device error " (ata-error controller) " during PACKET Check_Status_A.")
(return-from ata-submit-packet-command nil)))
;; HP1: Send_Packet
;; Send the command a word at a time.
(loop
for i from 0 by 2 below (atapi-device-cdb-size device)
for lo = (svref cdb i)
for hi = (svref cdb (1+ i))
for word = (logior lo (ash hi 8))
do (setf (sys.int::io-port/16 (+ command-base +ata-register-data+)) word)))
t)
(defun ata-issue-pio-packet-command (device cdb result-buffer result-len)
(let* ((controller (atapi-device-controller device))
(command-base (ata-controller-command controller)))
(when (not (ata-submit-packet-command device cdb result-len nil nil))
(return-from ata-issue-pio-packet-command nil))
;; HP3: INTRQ_wait
(when (atapi-device-initialized-p device)
(ata-intrq-wait controller))
;; HP2: Check_Status_B
(multiple-value-bind (drq timed-out)
(ata-check-status controller)
(when timed-out
;; FIXME: Should reset the device here.
(sup:debug-print-line "Device timeout during PACKET Check_Status_B.")
(return-from ata-issue-pio-packet-command nil))
(when (logtest +ata-err+ (ata-alt-status controller))
;; FIXME: Should reset the device here.
(sup:debug-print-line "Device error " (ata-error controller) " during PACKET Check_Status_B.")
(return-from ata-issue-pio-packet-command nil))
(cond (drq
;; Data ready for transfer.
;; HP4: Transfer_Data
(let ((len (logior (sys.int::io-port/8 (+ command-base +ata-register-lba-mid+))
(ash (sys.int::io-port/8 (+ command-base +ata-register-lba-high+)) 8))))
(loop
for i from 0 by 2 below (min len result-len)
do
(setf (sys.int::memref-unsigned-byte-16 (+ result-buffer i))
(sys.int::io-port/16 (+ (ata-controller-command controller)
+ata-register-data+))))
;; Read any remaining data.
(loop
for i from 0 by 2 below (- len result-len)
do (sys.int::io-port/16 (+ (ata-controller-command controller)
+ata-register-data+)))
len))
(t
;; No data to transfer.
0)))))
(defun ata-issue-dma-packet-command (device cdb result-buffer-phys result-len)
(let* ((controller (atapi-device-controller device)))
(ata-configure-prdt controller result-buffer-phys result-len :read)
(when (not (ata-submit-packet-command device cdb result-len t :device-to-host))
(return-from ata-issue-dma-packet-command nil))
Start DMA .
(setf (pci:pci-io-region/8 (ata-controller-bus-master-register controller) +ata-bmr-command+) (logior +ata-bmr-command-start+
+ata-bmr-direction-read/write+))
;; Wait for completion.
(ata-intrq-wait controller)
;; FIXME: Should go to Check_Status_B here.
(let ((status (pci:pci-io-region/8 (ata-controller-bus-master-register controller) +ata-bmr-status+)))
;; Stop the transfer.
(setf (pci:pci-io-region/8 (ata-controller-bus-master-register controller) +ata-bmr-command+) +ata-bmr-direction-read/write+)
;; Clear error bit.
(setf (pci:pci-io-region/8 (ata-controller-bus-master-register controller) +ata-bmr-status+) (logior status +ata-bmr-status-error+ +ata-bmr-status-interrupt+))
(if (logtest status +ata-bmr-status-error+)
(values nil :device-error)
t))))
(defun ata-issue-packet-command (device cdb result-buffer result-len)
(sup:ensure (eql (sys.int::simple-vector-length cdb)
(atapi-device-cdb-size device)))
(sup:ensure (eql (rem result-len 4) 0))
(cond ((not (atapi-device-initialized-p device))
(ata-issue-pio-packet-command device cdb result-buffer result-len))
((or (null result-buffer)
(and (<= sup::+physical-map-base+ result-buffer)
4 GB limit .
(< result-buffer (+ sup::+physical-map-base+ (* 4 1024 1024 1024)))))
(ata-issue-dma-packet-command device
cdb
(if result-buffer
(- result-buffer sup::+physical-map-base+)
0)
result-len))
((eql result-len sup::+4k-page-size+)
;; Transfer is small enough that the bounce page can be used.
(let* ((controller (atapi-device-controller device))
(bounce-frame (ata-controller-bounce-buffer controller))
(bounce-phys (ash bounce-frame 12))
(bounce-virt (sup::convert-to-pmap-address bounce-phys)))
(ata-issue-dma-packet-command device
cdb
bounce-phys
result-len)
;; FIXME: Don't copy a whole page.
(sup::%fast-page-copy result-buffer bounce-virt)))
Give up and do a slow PIO transfer .
(ata-issue-pio-packet-command device cdb result-buffer result-len))))
(defun ata-irq-handler (controller)
;; Read the status register to clear the interrupt pending state.
(sys.int::io-port/8 (+ (ata-controller-command controller)
+ata-register-status+))
(setf (sup:event-state (ata-controller-irq-latch controller)) t))
(defun init-ata-controller (command-base control-base bus-master-register prdt-phys irq)
(declare (mezzano.compiler::closure-allocation :wired))
(sup:debug-print-line "New controller at " command-base " " control-base " " bus-master-register " " irq)
(let* ((dma32-bounce-buffer (sup::allocate-physical-pages 1
:mandatory-p "ATA DMA bounce buffer"
:32-bit-only t))
(controller (make-ata-controller :command command-base
:control control-base
:bus-master-register bus-master-register
:prdt-phys prdt-phys
:irq irq
:bounce-buffer dma32-bounce-buffer)))
;; Set up a watcher with a timer to deal with timeouts waiting for IRQs
(setf (ata-controller-irq-latch controller)
(sup:make-event :name controller))
(setf (ata-controller-irq-timeout-timer controller)
(sup:make-timer :name controller))
(setf (ata-controller-irq-watcher controller)
(sup:make-watcher :name controller))
(sup:watcher-add-object (ata-controller-irq-latch controller)
(ata-controller-irq-watcher controller))
(sup:watcher-add-object (ata-controller-irq-timeout-timer controller)
(ata-controller-irq-watcher controller))
;; Disable IRQs on the controller and reset both drives.
(setf (sys.int::io-port/8 (+ control-base +ata-register-device-control+))
(logior +ata-srst+ +ata-nien+))
Hold SRST high for 5µs .
(setf (sys.int::io-port/8 (+ control-base +ata-register-device-control+))
+ata-nien+)
Hold SRST low for 2ms before probing for drives .
Now wait for BSY to clear . It may take up to 31 seconds for the
;; reset to finish, which is a bit silly...
(when (not (ata-wait-for-controller controller +ata-bsy+ 0 2))
BSY did not go low , no devices on this controller .
(sup:debug-print-line "No devices on ata controller.")
(return-from init-ata-controller))
(sup:debug-print-line "Probing ata controller.")
;; Attach interrupt handler.
(sup:irq-attach irq
(lambda (interrupt-frame irq)
(declare (ignore interrupt-frame irq))
(ata-irq-handler controller)
:completed)
controller
:exclusive t)
;; Probe drives.
(ata-detect-drive controller :device-0)
(ata-detect-drive controller :device-1)
;; Enable controller interrupts.
(setf (sys.int::io-port/8 (+ control-base +ata-register-device-control+)) 0)))
(defun pci::ata-pci-register (location)
(let* ((prdt-page (sup::allocate-physical-pages 1
:mandatory-p "ATA PRDT page"
:32-bit-only t)))
Make sure to enable PCI bus mastering for this device .
(setf (pci:pci-bus-master-enabled location) t)
;; Ignore controllers not in compatibility mode, they share IRQs.
It 's not a problem for the ATA driver , but the supervisor 's IRQ handling
;; doesn't deal with shared IRQs at all.
(when (not (logbitp 0 (pci:pci-programming-interface location)))
(init-ata-controller +ata-compat-primary-command+
+ata-compat-primary-control+
(pci:pci-bar location 4)
(* prdt-page sup::+4k-page-size+)
(sup:platform-irq +ata-compat-primary-irq+)))
(when (not (logbitp 2 (pci:pci-programming-interface location)))
(init-ata-controller +ata-compat-secondary-command+
+ata-compat-secondary-control+
(+ (pci:pci-bar location 4) 8)
(+ (* prdt-page sup::+4k-page-size+) 2048)
(sup:platform-irq +ata-compat-secondary-irq+)))))
| null | https://raw.githubusercontent.com/froggey/Mezzano/8c95a9729bb7b8db8c086976dbac04bedbc26995/supervisor/ata.lisp | lisp | Bits in registers.
Commands.
read/write
read
write
read/write
read/write
read/write
read/write
read/write
read
write
read
write
write
write
write
set to read, clear to write.
Device bits.
Status bits.
Device Control bits.
Error bits.
Commands.
FIXME: Depends on the granularity of the timer, as does
intel-8042::+delay+.
select-device should never be called with a command in progress on the controller.
Select the device.
Issue IDENTIFY.
I don't know if there's a standard timeout for this, but
Read the status register to clear the pending interrupt flag.
Read data.
Size the string, can't resize wired strings yet...
Select the device.
Issue IDENTIFY.
I don't know if there's a standard timeout for this, but
Read the status register to clear the pending interrupt flag.
The LBA low and interrupt reason registers should both be set to #x01,
but some hardware is broken and doesn't do this.
Read data.
Data in logical sector size field valid.
Select the device.
HI3: Write_parameters
Select the device.
HI3: Write_parameters
Sample the alt-status register for the required delay.
FIXME: Do something better than this.
-absolute is non-consing
FIXME: Should reset the device here.
FIXME: Should reset the device here.
HPIOI2: Transfer_Data
If there are no more blocks to transfer, transition back to host idle,
FIXME: Should reset the device here.
All data transfered successfully.
Error?
FIXME: Should reset the device here.
HPIOO1: Transfer_Data
HPIOO2: INTRQ_Wait
Return to HPIOO0.
Write final chunk.
Set direction.
Transfer is small enough that the bounce page can be used.
FIXME: Don't copy a whole page
after the command write.
Wait for completion.
Stop the transfer.
Clear error bit.
after the command write.
Wait for completion.
Stop the transfer.
Clear error bit.
HND0: INTRQ_Wait
Sample the alt-status register for the required delay.
FIXME: Should reset the device here.
Transition to Host_Idle, checking error status.
Select the device.
HI3: Write_parameters
Set maximum transfer size.
Some devices use 0 to mean some other value, use a tiny result instead.
HP0: Check_Status_A
FIXME: Should reset the device here.
FIXME: Should reset the device here.
HP1: Send_Packet
Send the command a word at a time.
HP3: INTRQ_wait
HP2: Check_Status_B
FIXME: Should reset the device here.
FIXME: Should reset the device here.
Data ready for transfer.
HP4: Transfer_Data
Read any remaining data.
No data to transfer.
Wait for completion.
FIXME: Should go to Check_Status_B here.
Stop the transfer.
Clear error bit.
Transfer is small enough that the bounce page can be used.
FIXME: Don't copy a whole page.
Read the status register to clear the interrupt pending state.
Set up a watcher with a timer to deal with timeouts waiting for IRQs
Disable IRQs on the controller and reset both drives.
reset to finish, which is a bit silly...
Attach interrupt handler.
Probe drives.
Enable controller interrupts.
Ignore controllers not in compatibility mode, they share IRQs.
doesn't deal with shared IRQs at all. | Legacy PCI ATA disk driver
(defpackage :mezzano.supervisor.ata
(:use :cl)
(:local-nicknames (:sup :mezzano.supervisor)
(:pci :mezzano.supervisor.pci)
(:sys.int :mezzano.internals))
(:export #:read-ata-string
#:+ata-dev+
#:+ata-lba+
#:+ata-err+
#:+ata-drq+
#:+ata-df+
#:+ata-drdy+
#:+ata-bsy+
#:+ata-nien+
#:+ata-srst+
#:+ata-hob+
#:+ata-abrt+
#:+ata-command-read-sectors+
#:+ata-command-read-sectors-ext+
#:+ata-command-read-dma+
#:+ata-command-read-dma-ext+
#:+ata-command-write-sectors+
#:+ata-command-write-sectors-ext+
#:+ata-command-write-dma+
#:+ata-command-write-dma-ext+
#:+ata-command-flush-cache+
#:+ata-command-flush-cache-ext+
#:+ata-command-identify+
#:+ata-command-identify-packet+
#:+ata-command-packet+))
(in-package :mezzano.supervisor.ata)
(defconstant +ata-compat-primary-command+ #x1F0)
(defconstant +ata-compat-primary-control+ #x3F0)
(defconstant +ata-compat-primary-irq+ 14)
(defconstant +ata-compat-secondary-command+ #x170)
(defconstant +ata-compat-secondary-control+ #x370)
(defconstant +ata-compat-secondary-irq+ 15)
(defconstant +ata-bmr-command-start+ #x01)
(defconstant +ata-bmr-status-active+ #x01)
(defconstant +ata-bmr-status-error+ #x02)
(defconstant +ata-bmr-status-interrupt+ #x04)
(defconstant +ata-bmr-status-drive-0-dma-capable+ #x20)
(defconstant +ata-bmr-status-drive-1-dma-capable+ #x40)
(defconstant +ata-bmr-status-simplex+ #x80)
(defconstant +ata-dev+ #x10 "Select device 0 when clear, device 1 when set.")
(defconstant +ata-lba+ #x40 "Set when using LBA.")
(defconstant +ata-err+ #x01 "An error occured during command execution.")
(defconstant +ata-drq+ #x08 "Device is ready to transfer data.")
(defconstant +ata-df+ #x20 "Device fault.")
(defconstant +ata-drdy+ #x40 "Device is ready to accept commands.")
(defconstant +ata-bsy+ #x80 "Device is busy.")
(defconstant +ata-nien+ #x02 "Mask interrupts.")
(defconstant +ata-srst+ #x04 "Initiate a software reset.")
(defconstant +ata-hob+ #x80 "Read LBA48 high-order bytes.")
(defconstant +ata-abrt+ #x04 "Command aborted by device.")
(defconstant +ata-command-read-sectors+ #x20)
(defconstant +ata-command-read-sectors-ext+ #x24)
(defconstant +ata-command-read-dma+ #xC8)
(defconstant +ata-command-read-dma-ext+ #x25)
(defconstant +ata-command-write-sectors+ #x30)
(defconstant +ata-command-write-sectors-ext+ #x3A)
(defconstant +ata-command-write-dma+ #xCA)
(defconstant +ata-command-write-dma-ext+ #x35)
(defconstant +ata-command-flush-cache+ #xE7)
(defconstant +ata-command-flush-cache-ext+ #xEA)
(defconstant +ata-command-identify+ #xEC)
(defconstant +ata-command-identify-packet+ #xA1)
(defconstant +ata-command-packet+ #xA0)
(defstruct (ata-controller
(:area :wired))
command
control
bus-master-register
prdt-phys
irq
current-channel
irq-latch
irq-timeout-timer
irq-watcher
bounce-buffer)
(defstruct (ata-device
(:area :wired))
controller
channel
block-size
sector-count
lba48-capable)
(defstruct (atapi-device
(:area :wired))
controller
channel
cdb-size
initialized-p)
(defun ata-error (controller)
"Read the error register."
(sys.int::io-port/8 (+ (ata-controller-command controller)
+ata-register-error+)))
(defun ata-status (controller)
"Read the status register."
(sys.int::io-port/8 (+ (ata-controller-command controller)
+ata-register-status+)))
(defun ata-alt-status (controller)
"Read the alternate status register."
(sys.int::io-port/8 (+ (ata-controller-control controller)
+ata-register-alt-status+)))
(defun ata-wait-for-controller (controller mask value timeout)
"Wait for the bits in the alt-status register masked by MASK to become equal to VALUE.
Returns true when the bits are equal, false when the timeout expires or if the device sets ERR."
(loop
(let ((status (ata-alt-status controller)))
(when (logtest status +ata-err+)
(return nil))
(when (eql (logand status mask) value)
(return t)))
(when (<= timeout 0)
(return nil))
(sup:safe-sleep 0.01)
(decf timeout 0.01)))
(defun ata-select-device (controller channel)
(when (logtest (logior +ata-bsy+ +ata-drq+)
(ata-alt-status controller))
(sup:debug-print-line "ATA-SELECT-DEVICE called with command in progress.")
(return-from ata-select-device nil))
(when (not (eql (ata-controller-current-channel controller) channel))
(assert (or (eql channel :device-0) (eql channel :device-1)))
(setf (sys.int::io-port/8 (+ (ata-controller-command controller)
+ata-register-device+))
(ecase channel
(:device-0 0)
(:device-1 +ata-dev+)))
Again , neither BSY nor DRQ should be set .
(when (logtest (logior +ata-bsy+ +ata-drq+)
(ata-alt-status controller))
(sup:debug-print-line "ATA-SELECT-DEVICE called with command in progress.")
(return-from ata-select-device nil))
(setf (ata-controller-current-channel controller) channel))
t)
(defun ata-detect-packet-device (controller channel)
(let ((buf (sys.int::make-simple-vector 256 :wired)))
(when (not (ata-select-device controller channel))
(sup:debug-print-line "Could not select ata device when probing.")
(return-from ata-detect-packet-device nil))
(setf (sys.int::io-port/8 (+ (ata-controller-command controller)
+ata-register-command+))
+ata-command-identify-packet+)
after writing command .
(ata-alt-status controller)
Wait for BSY to clear and DRQ to go high .
Use a 1 second timeout .
I figure that the device should respond to IDENTIFY quickly .
Wrong blah ! - wait - for - controller is nonsense .
if = 0 & drq = 0 , then there was an error .
(let ((success (ata-wait-for-controller controller (logior +ata-bsy+ +ata-drq+) +ata-drq+ 1)))
(sys.int::io-port/8 (+ (ata-controller-command controller)
+ata-register-status+))
Check before checking for timeout .
ATAPI devices will abort , and wait - for - controller will time out .
(when (logtest (ata-alt-status controller) +ata-err+)
(sup:debug-print-line "IDENTIFY PACKET aborted by device.")
(return-from ata-detect-packet-device))
(when (not success)
(sup:debug-print-line "Timeout while waiting for DRQ during IDENTIFY PACKET.")
(return-from ata-detect-packet-device)))
(dotimes (i 256)
(setf (svref buf i) (sys.int::io-port/16 (+ (ata-controller-command controller)
+ata-register-data+))))
(let* ((general-config (svref buf 0))
(cdb-size (case (ldb (byte 2 0) general-config)
(0 12)
(1 16))))
(sup:debug-print-line "PACKET device:")
(sup:debug-print-line " General configuration: " general-config)
(sup:debug-print-line " Specific configuration: " (svref buf 2))
(sup:debug-print-line " Capabilities: " (svref buf 49) " " (svref buf 50))
(sup:debug-print-line " Field validity: " (svref buf 53))
(sup:debug-print-line " DMADIR: " (svref buf 62))
(sup:debug-print-line " Multiword DMA transfer: " (svref buf 63))
(sup:debug-print-line " PIO transfer mode supported: " (svref buf 64))
(sup:debug-print-line " Features: " (svref buf 82) " " (svref buf 83) " " (svref buf 84) " " (svref buf 85) " " (svref buf 86) " " (svref buf 87))
(sup:debug-print-line " Removable Media Notification: " (svref buf 127))
(when (or (not (logbitp 15 general-config))
(logbitp 14 general-config))
(sup:debug-print-line "Device does not implement the PACKET command set.")
(return-from ata-detect-packet-device))
(when (not (eql (ldb (byte 5 8) general-config) 5))
(sup:debug-print-line "PACKET device is not a CD-ROM drive.")
(return-from ata-detect-packet-device))
(when (not cdb-size)
(sup:debug-print-line "PACKET device has unsupported CDB size " (ldb (byte 2 0) (svref buf 0)))
(return-from ata-detect-packet-device))
(let ((device (make-atapi-device :controller controller
:channel channel
:cdb-size cdb-size
:initialized-p nil)))
(mezzano.supervisor.cdrom:cdrom-initialize-device device cdb-size 'ata-issue-packet-command)
(setf (atapi-device-initialized-p device) t)))))
(defun read-ata-string (identify-data start end read-fn)
(let ((len (* (- end start) 2)))
(loop
(when (zerop len)
(return))
(let* ((word (funcall read-fn identify-data (+ start (ash (1- len) -1))))
(byte (if (logtest (1- len) 1)
(ldb (byte 8 0) word)
(ldb (byte 8 8) word))))
(when (not (eql byte #x20))
(return)))
(decf len))
(let ((string (mezzano.runtime::make-wired-string len)))
(dotimes (i len)
(let* ((word (funcall read-fn identify-data (+ start (ash i -1))))
(byte (if (logtest i 1)
(ldb (byte 8 0) word)
(ldb (byte 8 8) word))))
(setf (char string i) (code-char byte))))
string)))
(defun ata-detect-drive (controller channel)
(let ((buf (sys.int::make-simple-vector 256 :wired)))
(when (not (ata-select-device controller channel))
(sup:debug-print-line "Could not select ata device when probing.")
(return-from ata-detect-drive nil))
(setf (sys.int::io-port/8 (+ (ata-controller-command controller)
+ata-register-command+))
+ata-command-identify+)
after writing command .
(ata-alt-status controller)
Wait for BSY to clear and DRQ to go high .
Use a 1 second timeout .
I figure that the device should respond to IDENTIFY quickly .
Wrong blah ! - wait - for - controller is nonsense .
if = 0 & drq = 0 , then there was an error .
(let ((success (ata-wait-for-controller controller (logior +ata-bsy+ +ata-drq+) +ata-drq+ 1)))
(sys.int::io-port/8 (+ (ata-controller-command controller)
+ata-register-status+))
Check before checking for timeout .
ATAPI devices will abort , and wait - for - controller will time out .
(when (logtest (ata-alt-status controller) +ata-err+)
(if (and (logtest (sys.int::io-port/8 (+ (ata-controller-command controller)
+ata-register-error+))
+ata-abrt+)
(eql (sys.int::io-port/8 (+ (ata-controller-command controller)
+ata-register-lba-mid+))
#x14)
(eql (sys.int::io-port/8 (+ (ata-controller-command controller)
+ata-register-lba-high+))
#xEB))
(return-from ata-detect-drive
(ata-detect-packet-device controller channel))
(sup:debug-print-line "IDENTIFY aborted by device."))
(return-from ata-detect-drive))
(when (not success)
(sup:debug-print-line "Timeout while waiting for DRQ during IDENTIFY.")
(return-from ata-detect-drive)))
(dotimes (i 256)
(setf (svref buf i) (sys.int::io-port/16 (+ (ata-controller-command controller)
+ata-register-data+))))
(let* ((supported-command-sets (svref buf 83))
(lba48-capable (logbitp 10 supported-command-sets))
(sector-size (if (and (logbitp 14 (svref buf 106))
(not (logbitp 13 (svref buf 106))))
(logior (svref buf 117)
(ash (svref buf 118) 16))
Not valid , use 512 .
512))
(sector-count (if lba48-capable
(logior (svref buf 100)
(ash (svref buf 101) 16)
(ash (svref buf 102) 32)
(ash (svref buf 103) 48))
(logior (svref buf 60)
(ash (svref buf 61) 16))))
(device (make-ata-device :controller controller
:channel channel
:block-size sector-size
:sector-count sector-count
:lba48-capable lba48-capable))
(serial-number (read-ata-string buf 10 20 #'svref))
(model-number (read-ata-string buf 27 47 #'svref)))
(when (eql sector-size 0)
VmWare seems to do this , are we not interpreting the identify data properly ?
(sup:debug-print-line "*** Disk is reporting sector size? Assuming 512 bytes")
(setf sector-size 512))
(sup:debug-print-line "Features (83): " supported-command-sets)
(sup:debug-print-line "Sector size: " sector-size)
(sup:debug-print-line "Sector count: " sector-count)
(sup:debug-print-line "Serial: " serial-number)
(sup:debug-print-line "Model: " model-number)
(sup:register-disk device
t
(ata-device-sector-count device)
(ata-device-block-size device)
256
'ata-read 'ata-write 'ata-flush
(sys.int::cons-in-area
model-number
(sys.int::cons-in-area
serial-number
nil
:wired)
:wired)))))
(defun ata-issue-lba28-command (device lba count command)
(let ((controller (ata-device-controller device)))
(when (not (ata-select-device controller (ata-device-channel device)))
(sup:debug-print-line "Could not select ata device.")
(return-from ata-issue-lba28-command nil))
(setf (sup:event-state (ata-controller-irq-latch controller)) nil)
(setf (sys.int::io-port/8 (+ (ata-controller-command controller)
+ata-register-count+))
(if (eql count 256)
0
count))
(setf (sys.int::io-port/8 (+ (ata-controller-command controller)
+ata-register-lba-low+))
(ldb (byte 8 0) lba))
(setf (sys.int::io-port/8 (+ (ata-controller-command controller)
+ata-register-lba-mid+))
(ldb (byte 8 8) lba))
(setf (sys.int::io-port/8 (+ (ata-controller-command controller)
+ata-register-lba-high+))
(ldb (byte 8 16) lba))
(setf (sys.int::io-port/8 (+ (ata-controller-command controller)
+ata-register-device+))
(logior (ecase (ata-device-channel device)
(:device-0 0)
(:device-1 +ata-dev+))
+ata-lba+
(ldb (byte 4 24) lba)))
HI4 : Write_command
(setf (sys.int::io-port/8 (+ (ata-controller-command controller)
+ata-register-command+))
command))
t)
(defun ata-issue-lba48-command (device lba count command)
(let* ((controller (ata-device-controller device))
(command-base (ata-controller-command controller)))
(when (not (ata-select-device controller (ata-device-channel device)))
(sup:debug-print-line "Could not select ata device.")
(return-from ata-issue-lba48-command nil))
(setf (sup:event-state (ata-controller-irq-latch controller)) nil)
(when (eql count 65536)
(setf count 0))
(flet ((wr (reg val)
(setf (sys.int::io-port/8 (+ command-base reg)) val)))
(declare (dynamic-extent #'wr))
(wr +ata-register-count+ (ldb (byte 8 8) count))
(wr +ata-register-count+ (ldb (byte 8 0) count))
(wr +ata-register-lba-high+ (ldb (byte 8 40) lba))
(wr +ata-register-lba-mid+ (ldb (byte 8 32) lba))
(wr +ata-register-lba-low+ (ldb (byte 8 24) lba))
(wr +ata-register-lba-high+ (ldb (byte 8 16) lba))
(wr +ata-register-lba-mid+ (ldb (byte 8 8) lba))
(wr +ata-register-lba-low+ (ldb (byte 8 0) lba))
(wr +ata-register-device+ (logior (ecase (ata-device-channel device)
(:device-0 0)
(:device-1 +ata-dev+))
+ata-lba+))
HI4 : Write_command
(wr +ata-register-command+ command)))
t)
(defun ata-check-status (controller &optional (timeout 30))
"Wait until BSY clears, then return two values.
First is true if DRQ is set, false if DRQ is clear or timeout.
Second is true if the timeout expired.
This is used to implement the Check_Status states of the various command protocols."
(ata-alt-status controller)
(loop
(let ((status (ata-alt-status controller)))
(when (not (logtest status +ata-bsy+))
(return (values (logtest status +ata-drq+)
nil)))
Stay in Check_Status .
(when (<= timeout 0)
(return (values nil t)))
(sup:safe-sleep 0.001)
(decf timeout 0.001))))
(defun ata-intrq-wait (controller &optional (timeout 30))
"Wait for a interrupt from the device.
This is used to implement the INTRQ_Wait state."
(sup:timer-arm timeout (ata-controller-irq-timeout-timer controller))
(sup:watcher-wait (ata-controller-irq-watcher controller))
(when (not (sup:event-state (ata-controller-irq-latch controller)))
(sup:ensure (sup:timer-expired-p (ata-controller-irq-timeout-timer controller)))
(sup:debug-print-line "*** ATA-INTRQ-WAIT TIMEOUT EXPIRED! ***"))
(sup:timer-disarm-absolute (ata-controller-irq-timeout-timer controller))
(setf (sup:event-state (ata-controller-irq-latch controller)) nil))
(defun ata-pio-data-in (device count mem-addr)
"Implement the PIO data-in protocol."
(let ((controller (ata-device-controller device)))
(loop
HPIOI0 : INTRQ_wait
(ata-intrq-wait controller)
HPIOI1 : Check_Status
(multiple-value-bind (drq timed-out)
(ata-check-status controller)
(when timed-out
(sup:debug-print-line "Device timeout during PIO data in.")
(return-from ata-pio-data-in nil))
(when (not drq)
(sup:debug-print-line "Device error during PIO data in.")
(return-from ata-pio-data-in nil)))
FIXME : non-512 byte sectors , non 2 - byte words .
(setf (sys.int::memref-unsigned-byte-16 mem-addr 0)
(sys.int::io-port/16 (+ (ata-controller-command controller)
+ata-register-data+)))
(incf mem-addr 2))
otherwise return to HPIOI0 .
(when (zerop (decf count))
(return t)))))
(defun ata-pio-data-out (device count mem-addr)
"Implement the PIO data-out protocol."
(let ((controller (ata-device-controller device)))
(loop
HPIOO0 : Check_Status
(multiple-value-bind (drq timed-out)
(ata-check-status controller)
(when timed-out
(sup:debug-print-line "Device timeout during PIO data out.")
(return-from ata-pio-data-out nil))
(when (not drq)
(cond ((zerop count)
(return-from ata-pio-data-out t))
(sup:debug-print-line "Device error during PIO data out.")
(return-from ata-pio-data-out nil)))))
FIXME : non-512 byte sectors , non 2 - byte words .
(setf (sys.int::io-port/16 (+ (ata-controller-command controller)
+ata-register-data+))
(sys.int::memref-unsigned-byte-16 mem-addr 0))
(incf mem-addr 2))
(ata-intrq-wait controller)
(decf count))))
(defun ata-configure-prdt (controller phys-addr n-octets direction)
(let* ((prdt (ata-controller-prdt-phys controller))
(prdt-virt (sup::convert-to-pmap-address prdt)))
(sup:ensure (<= (+ phys-addr n-octets) #x100000000))
(sup:ensure (not (eql n-octets 0)))
(do ((offset 0 (+ offset 2)))
((<= n-octets #x10000)
(setf (sys.int::memref-unsigned-byte-32 prdt-virt offset) phys-addr
(sys.int::memref-unsigned-byte-32 prdt-virt (1+ offset)) (logior #x80000000 n-octets)))
Write 64k chunks .
(setf (sys.int::memref-unsigned-byte-32 prdt-virt offset) phys-addr
0 = 64k
(incf phys-addr #x10000)
(decf n-octets #x10000))
Write the PRDT location .
(setf (pci:pci-io-region/32 (ata-controller-bus-master-register controller) +ata-bmr-prdt-address+) prdt
Clear DMA status . Yup . You have to write 1 to clear bits .
(pci:pci-io-region/8 (ata-controller-bus-master-register controller) +ata-bmr-status+) (logior +ata-bmr-status-error+ +ata-bmr-status-interrupt+)
(pci:pci-io-region/8 (ata-controller-bus-master-register controller) +ata-bmr-command+) (ecase direction
(:read +ata-bmr-direction-read/write+)
(:write 0)))))
(defun ata-read-write (device lba count mem-addr what dma-fn pio-fn)
(let ((controller (ata-device-controller device)))
(sup:ensure (>= lba 0))
(sup:ensure (>= count 0))
(sup:ensure (<= (+ lba count) (ata-device-sector-count device)))
(cond
((ata-device-lba48-capable device)
(when (> count 65536)
(sup:debug-print-line "Can't do " what " of more than 65,536 sectors.")
(return-from ata-read-write (values nil :too-many-sectors))))
(t
(when (> count 256)
(sup:debug-print-line "Can't do " what " of more than 256 sectors.")
(return-from ata-read-write (values nil :too-many-sectors)))))
(when (eql count 0)
(return-from ata-read-write t))
(cond ((and (<= sup::+physical-map-base+ mem-addr)
4 GB limit .
(< mem-addr (+ sup::+physical-map-base+ (* 4 1024 1024 1024))))
(funcall dma-fn controller device lba count (- mem-addr sup::+physical-map-base+)))
((eql (* count (ata-device-block-size device)) sup::+4k-page-size+)
(let* ((bounce-frame (ata-controller-bounce-buffer controller))
(bounce-phys (ash bounce-frame 12))
(bounce-virt (sup::convert-to-pmap-address bounce-phys)))
(when (eql what :write)
(sup::%fast-page-copy bounce-virt mem-addr))
(funcall dma-fn controller device lba count bounce-phys)
(when (eql what :read)
(sup::%fast-page-copy mem-addr bounce-virt))))
Give up and do a slow PIO transfer .
(funcall pio-fn controller device lba count mem-addr))))
t)
(defun ata-issue-lba-command (device lba count command28 command48)
(if (ata-device-lba48-capable device)
(ata-issue-lba48-command device lba count command48)
(ata-issue-lba28-command device lba count command28)))
(defun ata-read-pio (controller device lba count mem-addr)
(declare (ignore controller))
(when (not (ata-issue-lba-command device lba count
+ata-command-read-sectors+
+ata-command-read-sectors-ext+))
(return-from ata-read-pio (values nil :device-error)))
(when (not (ata-pio-data-in device count mem-addr))
(return-from ata-read-pio (values nil :device-error))))
(defun ata-read-dma (controller device lba count phys-addr)
(ata-configure-prdt controller phys-addr (* count 512) :read)
(when (not (ata-issue-lba-command device lba count
+ata-command-read-dma+
+ata-command-read-dma-ext+))
(return-from ata-read-dma (values nil :device-error)))
Start DMA .
FIXME : has absurd timing requirements here . Needs to be * immediately * ( tens of instructions )
(setf (pci:pci-io-region/8 (ata-controller-bus-master-register controller) +ata-bmr-command+) (logior +ata-bmr-command-start+
+ata-bmr-direction-read/write+))
(ata-intrq-wait controller)
(let ((status (pci:pci-io-region/8 (ata-controller-bus-master-register controller) +ata-bmr-status+)))
(setf (pci:pci-io-region/8 (ata-controller-bus-master-register controller) +ata-bmr-command+) +ata-bmr-direction-read/write+)
(setf (pci:pci-io-region/8 (ata-controller-bus-master-register controller) +ata-bmr-status+) (logior status +ata-bmr-status-error+ +ata-bmr-status-interrupt+))
(if (logtest status +ata-bmr-status-error+)
(values nil :device-error)
t)))
(defun ata-read (device lba count mem-addr)
(ata-read-write device lba count mem-addr
:read #'ata-read-dma #'ata-read-pio))
(defun ata-write-pio (controller device lba count mem-addr)
(declare (ignore controller))
(when (not (ata-issue-lba-command device lba count
+ata-command-write-sectors+
+ata-command-write-sectors-ext+))
(return-from ata-write-pio (values nil :device-error)))
(when (not (ata-pio-data-out device count mem-addr))
(return-from ata-write-pio (values nil :device-error))))
(defun ata-write-dma (controller device lba count phys-addr)
(ata-configure-prdt controller phys-addr (* count 512) :write)
(when (not (ata-issue-lba-command device lba count
+ata-command-write-dma+
+ata-command-write-dma-ext+))
(return-from ata-write-dma (values nil :device-error)))
Start DMA .
FIXME : has absurd timing requirements here . Needs to be * immediately * ( tens of instructions )
(setf (pci:pci-io-region/8 (ata-controller-bus-master-register controller) +ata-bmr-command+) +ata-bmr-command-start+)
(ata-intrq-wait controller)
(let ((status (pci:pci-io-region/8 (ata-controller-bus-master-register controller) +ata-bmr-status+)))
(setf (pci:pci-io-region/8 (ata-controller-bus-master-register controller) +ata-bmr-command+) 0)
(setf (pci:pci-io-region/8 (ata-controller-bus-master-register controller) +ata-bmr-status+) (logior status +ata-bmr-status-error+ +ata-bmr-status-interrupt+))
(if (logtest status +ata-bmr-status-error+)
(values nil :device-error)
t)))
(defun ata-write (device lba count mem-addr)
(ata-read-write device lba count mem-addr
:write #'ata-write-dma #'ata-write-pio))
(defun ata-flush (device)
(let ((controller (ata-device-controller device)))
(when (not (ata-issue-lba-command device 0 0
+ata-command-flush-cache+
+ata-command-flush-cache-ext+))
(return-from ata-flush (values nil :device-error)))
(ata-intrq-wait controller)
HND1 : Check_Status
(ata-alt-status controller)
(loop
Spec sez flush can take longer than 30 but I ca n't find an upper bound .
do
(when (not (logtest (ata-alt-status controller) +ata-bsy+))
(return))
Stay in Check_Status .
(when (<= timeout 0)
(sup:debug-print-line "Device timeout during flush.")
(return-from ata-flush (values nil :device-error)))
(sup:safe-sleep 0.001)
(decf timeout 0.001))
(when (logtest (ata-alt-status controller) +ata-err+)
(sup:debug-print-line "Device error " (ata-error controller) " during flush.")
(return-from ata-flush (values nil :device-error)))
t))
(defun ata-submit-packet-command (device cdb result-len dma dmadir)
(let* ((controller (atapi-device-controller device))
(command-base (ata-controller-command controller)))
(when (not (ata-select-device controller (atapi-device-channel device)))
(sup:debug-print-line "Could not select ata device.")
(return-from ata-submit-packet-command nil))
(setf (sup:event-state (ata-controller-irq-latch controller)) nil)
(flet ((wr (reg val)
(setf (sys.int::io-port/8 (+ command-base reg)) val)))
(declare (dynamic-extent #'wr))
(wr +ata-register-features+ (if dma
(logior #b0001
(ecase dmadir
(:device-to-host #b0100)
(:host-to-device #b0000)))
#b0000))
(cond ((eql result-len 0)
(wr +ata-register-lba-mid+ 2)
(wr +ata-register-lba-high+ 0))
(t
(wr +ata-register-lba-mid+ (ldb (byte 8 0) result-len))
(wr +ata-register-lba-high+ (ldb (byte 8 8) result-len))))
HI4 : Write_command
(wr +ata-register-command+ +ata-command-packet+))
after writing command .
(ata-alt-status controller)
(multiple-value-bind (drq timed-out)
(ata-check-status controller)
(when timed-out
(sup:debug-print-line "Device timeout during PACKET Check_Status_A.")
(return-from ata-submit-packet-command nil))
(when (not drq)
(sup:debug-print-line "Device error " (ata-error controller) " during PACKET Check_Status_A.")
(return-from ata-submit-packet-command nil)))
(loop
for i from 0 by 2 below (atapi-device-cdb-size device)
for lo = (svref cdb i)
for hi = (svref cdb (1+ i))
for word = (logior lo (ash hi 8))
do (setf (sys.int::io-port/16 (+ command-base +ata-register-data+)) word)))
t)
(defun ata-issue-pio-packet-command (device cdb result-buffer result-len)
(let* ((controller (atapi-device-controller device))
(command-base (ata-controller-command controller)))
(when (not (ata-submit-packet-command device cdb result-len nil nil))
(return-from ata-issue-pio-packet-command nil))
(when (atapi-device-initialized-p device)
(ata-intrq-wait controller))
(multiple-value-bind (drq timed-out)
(ata-check-status controller)
(when timed-out
(sup:debug-print-line "Device timeout during PACKET Check_Status_B.")
(return-from ata-issue-pio-packet-command nil))
(when (logtest +ata-err+ (ata-alt-status controller))
(sup:debug-print-line "Device error " (ata-error controller) " during PACKET Check_Status_B.")
(return-from ata-issue-pio-packet-command nil))
(cond (drq
(let ((len (logior (sys.int::io-port/8 (+ command-base +ata-register-lba-mid+))
(ash (sys.int::io-port/8 (+ command-base +ata-register-lba-high+)) 8))))
(loop
for i from 0 by 2 below (min len result-len)
do
(setf (sys.int::memref-unsigned-byte-16 (+ result-buffer i))
(sys.int::io-port/16 (+ (ata-controller-command controller)
+ata-register-data+))))
(loop
for i from 0 by 2 below (- len result-len)
do (sys.int::io-port/16 (+ (ata-controller-command controller)
+ata-register-data+)))
len))
(t
0)))))
(defun ata-issue-dma-packet-command (device cdb result-buffer-phys result-len)
(let* ((controller (atapi-device-controller device)))
(ata-configure-prdt controller result-buffer-phys result-len :read)
(when (not (ata-submit-packet-command device cdb result-len t :device-to-host))
(return-from ata-issue-dma-packet-command nil))
Start DMA .
(setf (pci:pci-io-region/8 (ata-controller-bus-master-register controller) +ata-bmr-command+) (logior +ata-bmr-command-start+
+ata-bmr-direction-read/write+))
(ata-intrq-wait controller)
(let ((status (pci:pci-io-region/8 (ata-controller-bus-master-register controller) +ata-bmr-status+)))
(setf (pci:pci-io-region/8 (ata-controller-bus-master-register controller) +ata-bmr-command+) +ata-bmr-direction-read/write+)
(setf (pci:pci-io-region/8 (ata-controller-bus-master-register controller) +ata-bmr-status+) (logior status +ata-bmr-status-error+ +ata-bmr-status-interrupt+))
(if (logtest status +ata-bmr-status-error+)
(values nil :device-error)
t))))
(defun ata-issue-packet-command (device cdb result-buffer result-len)
(sup:ensure (eql (sys.int::simple-vector-length cdb)
(atapi-device-cdb-size device)))
(sup:ensure (eql (rem result-len 4) 0))
(cond ((not (atapi-device-initialized-p device))
(ata-issue-pio-packet-command device cdb result-buffer result-len))
((or (null result-buffer)
(and (<= sup::+physical-map-base+ result-buffer)
4 GB limit .
(< result-buffer (+ sup::+physical-map-base+ (* 4 1024 1024 1024)))))
(ata-issue-dma-packet-command device
cdb
(if result-buffer
(- result-buffer sup::+physical-map-base+)
0)
result-len))
((eql result-len sup::+4k-page-size+)
(let* ((controller (atapi-device-controller device))
(bounce-frame (ata-controller-bounce-buffer controller))
(bounce-phys (ash bounce-frame 12))
(bounce-virt (sup::convert-to-pmap-address bounce-phys)))
(ata-issue-dma-packet-command device
cdb
bounce-phys
result-len)
(sup::%fast-page-copy result-buffer bounce-virt)))
Give up and do a slow PIO transfer .
(ata-issue-pio-packet-command device cdb result-buffer result-len))))
(defun ata-irq-handler (controller)
(sys.int::io-port/8 (+ (ata-controller-command controller)
+ata-register-status+))
(setf (sup:event-state (ata-controller-irq-latch controller)) t))
(defun init-ata-controller (command-base control-base bus-master-register prdt-phys irq)
(declare (mezzano.compiler::closure-allocation :wired))
(sup:debug-print-line "New controller at " command-base " " control-base " " bus-master-register " " irq)
(let* ((dma32-bounce-buffer (sup::allocate-physical-pages 1
:mandatory-p "ATA DMA bounce buffer"
:32-bit-only t))
(controller (make-ata-controller :command command-base
:control control-base
:bus-master-register bus-master-register
:prdt-phys prdt-phys
:irq irq
:bounce-buffer dma32-bounce-buffer)))
(setf (ata-controller-irq-latch controller)
(sup:make-event :name controller))
(setf (ata-controller-irq-timeout-timer controller)
(sup:make-timer :name controller))
(setf (ata-controller-irq-watcher controller)
(sup:make-watcher :name controller))
(sup:watcher-add-object (ata-controller-irq-latch controller)
(ata-controller-irq-watcher controller))
(sup:watcher-add-object (ata-controller-irq-timeout-timer controller)
(ata-controller-irq-watcher controller))
(setf (sys.int::io-port/8 (+ control-base +ata-register-device-control+))
(logior +ata-srst+ +ata-nien+))
Hold SRST high for 5µs .
(setf (sys.int::io-port/8 (+ control-base +ata-register-device-control+))
+ata-nien+)
Hold SRST low for 2ms before probing for drives .
Now wait for BSY to clear . It may take up to 31 seconds for the
(when (not (ata-wait-for-controller controller +ata-bsy+ 0 2))
BSY did not go low , no devices on this controller .
(sup:debug-print-line "No devices on ata controller.")
(return-from init-ata-controller))
(sup:debug-print-line "Probing ata controller.")
(sup:irq-attach irq
(lambda (interrupt-frame irq)
(declare (ignore interrupt-frame irq))
(ata-irq-handler controller)
:completed)
controller
:exclusive t)
(ata-detect-drive controller :device-0)
(ata-detect-drive controller :device-1)
(setf (sys.int::io-port/8 (+ control-base +ata-register-device-control+)) 0)))
(defun pci::ata-pci-register (location)
(let* ((prdt-page (sup::allocate-physical-pages 1
:mandatory-p "ATA PRDT page"
:32-bit-only t)))
Make sure to enable PCI bus mastering for this device .
(setf (pci:pci-bus-master-enabled location) t)
It 's not a problem for the ATA driver , but the supervisor 's IRQ handling
(when (not (logbitp 0 (pci:pci-programming-interface location)))
(init-ata-controller +ata-compat-primary-command+
+ata-compat-primary-control+
(pci:pci-bar location 4)
(* prdt-page sup::+4k-page-size+)
(sup:platform-irq +ata-compat-primary-irq+)))
(when (not (logbitp 2 (pci:pci-programming-interface location)))
(init-ata-controller +ata-compat-secondary-command+
+ata-compat-secondary-control+
(+ (pci:pci-bar location 4) 8)
(+ (* prdt-page sup::+4k-page-size+) 2048)
(sup:platform-irq +ata-compat-secondary-irq+)))))
|
cdfc163993d4f0672f4b034681153f369081ace13ed11f8a7aff756cdff7d223 | craigfe/progress | config.ml | — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
Copyright ( c ) 2020–2021 < >
Distributed under the MIT license . See terms at the end of this file .
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
Copyright (c) 2020–2021 Craig Ferguson <>
Distributed under the MIT license. See terms at the end of this file.
————————————————————————————————————————————————————————————————————————————*)
type user_supplied =
{ ppf : Format.formatter option
; hide_cursor : bool option
; persistent : bool option
; max_width : int option option
; min_interval : Duration.t option option
}
module Default = struct
(* NOTE: changes here should be reflected in the doc-strings. *)
let ppf =
(* We avoid using [Format.err_formatter] directly since [Fmt] uses
physical equality to share configuration options. *)
let ppf = Format.formatter_of_out_channel stderr in
Fmt.set_style_renderer ppf `Ansi_tty;
Fmt.set_utf_8 ppf true;
ppf
let hide_cursor = true
let persistent = true
let max_width = None
let min_interval = Some (Duration.of_sec (1. /. 60.))
end
Boilerplate from here onwards . Someday I 'll write a PPX for this ...
let v ?ppf ?hide_cursor ?persistent ?max_width ?min_interval () =
{ ppf; hide_cursor; persistent; max_width; min_interval }
(* Merge two ['a option]s with a left [Some] taking priority *)
let merge_on ~f a b = match (f a, f b) with Some a, _ -> Some a | None, b -> b
let ( || ) a b =
{ ppf = merge_on a b ~f:(fun x -> x.ppf)
; hide_cursor = merge_on a b ~f:(fun x -> x.hide_cursor)
; persistent = merge_on a b ~f:(fun x -> x.persistent)
; max_width = merge_on a b ~f:(fun x -> x.max_width)
; min_interval = merge_on a b ~f:(fun x -> x.min_interval)
}
type t =
{ ppf : Format.formatter
; hide_cursor : bool
; persistent : bool
; max_width : int option
; min_interval : Duration.t option
}
let apply_defaults : user_supplied -> t =
fun { ppf; hide_cursor; persistent; max_width; min_interval } ->
{ ppf = Option.value ppf ~default:Default.ppf
; hide_cursor = Option.value hide_cursor ~default:Default.hide_cursor
; persistent = Option.value persistent ~default:Default.persistent
; max_width = Option.value max_width ~default:Default.max_width
; min_interval = Option.value min_interval ~default:Default.min_interval
}
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
Copyright ( c ) 2020–2021 < >
Permission to use , copy , modify , and/or distribute this software for any
purpose with or without fee is hereby granted , provided that the above
copyright notice and this permission notice appear in all copies .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY ,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
FROM , OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE .
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
Copyright (c) 2020–2021 Craig Ferguson <>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
————————————————————————————————————————————————————————————————————————————*)
| null | https://raw.githubusercontent.com/craigfe/progress/d7129b772d05c5589b8807630031155a6aeb27f0/src/progress/engine/config.ml | ocaml | NOTE: changes here should be reflected in the doc-strings.
We avoid using [Format.err_formatter] directly since [Fmt] uses
physical equality to share configuration options.
Merge two ['a option]s with a left [Some] taking priority | — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
Copyright ( c ) 2020–2021 < >
Distributed under the MIT license . See terms at the end of this file .
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
Copyright (c) 2020–2021 Craig Ferguson <>
Distributed under the MIT license. See terms at the end of this file.
————————————————————————————————————————————————————————————————————————————*)
type user_supplied =
{ ppf : Format.formatter option
; hide_cursor : bool option
; persistent : bool option
; max_width : int option option
; min_interval : Duration.t option option
}
module Default = struct
let ppf =
let ppf = Format.formatter_of_out_channel stderr in
Fmt.set_style_renderer ppf `Ansi_tty;
Fmt.set_utf_8 ppf true;
ppf
let hide_cursor = true
let persistent = true
let max_width = None
let min_interval = Some (Duration.of_sec (1. /. 60.))
end
Boilerplate from here onwards . Someday I 'll write a PPX for this ...
let v ?ppf ?hide_cursor ?persistent ?max_width ?min_interval () =
{ ppf; hide_cursor; persistent; max_width; min_interval }
let merge_on ~f a b = match (f a, f b) with Some a, _ -> Some a | None, b -> b
let ( || ) a b =
{ ppf = merge_on a b ~f:(fun x -> x.ppf)
; hide_cursor = merge_on a b ~f:(fun x -> x.hide_cursor)
; persistent = merge_on a b ~f:(fun x -> x.persistent)
; max_width = merge_on a b ~f:(fun x -> x.max_width)
; min_interval = merge_on a b ~f:(fun x -> x.min_interval)
}
type t =
{ ppf : Format.formatter
; hide_cursor : bool
; persistent : bool
; max_width : int option
; min_interval : Duration.t option
}
let apply_defaults : user_supplied -> t =
fun { ppf; hide_cursor; persistent; max_width; min_interval } ->
{ ppf = Option.value ppf ~default:Default.ppf
; hide_cursor = Option.value hide_cursor ~default:Default.hide_cursor
; persistent = Option.value persistent ~default:Default.persistent
; max_width = Option.value max_width ~default:Default.max_width
; min_interval = Option.value min_interval ~default:Default.min_interval
}
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
Copyright ( c ) 2020–2021 < >
Permission to use , copy , modify , and/or distribute this software for any
purpose with or without fee is hereby granted , provided that the above
copyright notice and this permission notice appear in all copies .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY ,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
FROM , OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE .
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
Copyright (c) 2020–2021 Craig Ferguson <>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
————————————————————————————————————————————————————————————————————————————*)
|
ab73618d68e8c4028ac83558c167e4e95b090adbe8f2129dd41f55a3d9d4d1bb | IUCompilerCourse/public-student-support-code | type-check-Cvec.rkt | #lang racket
(require "utilities.rkt")
(require "type-check-Cvar.rkt")
(require "type-check-Cif.rkt")
(require "type-check-Cwhile.rkt")
(require "type-check-Lvec.rkt")
(provide type-check-Cvec type-check-Cvec-mixin)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
type - check - Cvec
(define (type-check-Cvec-mixin super-class)
(class super-class
(super-new)
(inherit check-type-equal? exp-ready?)
(define/override (type-equal? t1 t2)
(debug 'type-equal? "lenient" t1 t2)
(match* (t1 t2)
[(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
(for/and ([t1 ts1] [t2 ts2])
(type-equal? t1 t2))]
[(other wise) (super type-equal? t1 t2)]))
(define/override (free-vars-exp e)
(define (recur e) (send this free-vars-exp e))
(match e
[(HasType e t) (recur e)]
[(Allocate size ty) (set)]
[(GlobalValue name) (set)]
[else (super free-vars-exp e)]))
(define/override (type-check-exp env)
(lambda (e)
(debug 'type-check-exp "Cvec" e)
(define recur (type-check-exp env))
(match e
[(Prim 'vector es)
(unless (<= (length es) 50)
(error 'type-check "vector too large ~a, max is 50" (length es)))
(define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
(define t `(Vector ,@t*))
(values (HasType (Prim 'vector e*) t) t)]
[(Prim 'vector-ref (list e1 (Int i)))
(define-values (e1^ t) (recur e1))
(match t
[`(Vector ,ts ...)
(unless (and (0 . <= . i) (i . < . (length ts)))
(error 'type-check "index ~a out of bounds\nin ~v" i e))
(values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
[else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
[(Prim 'vector-set! (list e1 (Int i) arg) )
(define-values (e-vec t-vec) (recur e1))
(define-values (e-arg^ t-arg) (recur arg))
(match t-vec
[`(Vector ,ts ...)
(unless (and (0 . <= . i) (i . < . (length ts)))
(error 'type-check "index ~a out of bounds\nin ~v" i e))
(check-type-equal? (list-ref ts i) t-arg e)
(values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
[else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
[(Prim 'vector-length (list e))
(define-values (e^ t) (recur e))
(match t
[`(Vector ,ts ...)
(values (Prim 'vector-length (list e^)) 'Integer)]
[else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
[(Prim 'eq? (list arg1 arg2))
(define-values (e1 t1) (recur arg1))
(define-values (e2 t2) (recur arg2))
(match* (t1 t2)
[(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
[(other wise) (check-type-equal? t1 t2 e)])
(values (Prim 'eq? (list e1 e2)) 'Boolean)]
[(GlobalValue name)
(values (GlobalValue name) 'Integer)]
[(Allocate size t)
(values (Allocate size t) t)]
[(Collect size)
(values (Collect size) 'Void)]
[else ((super type-check-exp env) e)])))
(define/override ((type-check-stmt env) s)
(match s
[(Collect size) (void)]
[(Prim 'vector-set! (list vec index rhs))
#:when (and (exp-ready? vec env) (exp-ready? index env)
(exp-ready? rhs env))
((type-check-exp env) s)]
[else ((super type-check-stmt env) s)]))
))
(define type-check-Cvec-class (type-check-Cvec-mixin
(type-check-Cwhile-mixin
(type-check-Cif-mixin
(type-check-Cvar-mixin
type-check-Lvec-class)))))
(define (type-check-Cvec p)
(send (new type-check-Cvec-class) type-check-program p))
| null | https://raw.githubusercontent.com/IUCompilerCourse/public-student-support-code/de33d84247885ea309db456cc8086a12c8cdd067/type-check-Cvec.rkt | racket | #lang racket
(require "utilities.rkt")
(require "type-check-Cvar.rkt")
(require "type-check-Cif.rkt")
(require "type-check-Cwhile.rkt")
(require "type-check-Lvec.rkt")
(provide type-check-Cvec type-check-Cvec-mixin)
type - check - Cvec
(define (type-check-Cvec-mixin super-class)
(class super-class
(super-new)
(inherit check-type-equal? exp-ready?)
(define/override (type-equal? t1 t2)
(debug 'type-equal? "lenient" t1 t2)
(match* (t1 t2)
[(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
(for/and ([t1 ts1] [t2 ts2])
(type-equal? t1 t2))]
[(other wise) (super type-equal? t1 t2)]))
(define/override (free-vars-exp e)
(define (recur e) (send this free-vars-exp e))
(match e
[(HasType e t) (recur e)]
[(Allocate size ty) (set)]
[(GlobalValue name) (set)]
[else (super free-vars-exp e)]))
(define/override (type-check-exp env)
(lambda (e)
(debug 'type-check-exp "Cvec" e)
(define recur (type-check-exp env))
(match e
[(Prim 'vector es)
(unless (<= (length es) 50)
(error 'type-check "vector too large ~a, max is 50" (length es)))
(define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
(define t `(Vector ,@t*))
(values (HasType (Prim 'vector e*) t) t)]
[(Prim 'vector-ref (list e1 (Int i)))
(define-values (e1^ t) (recur e1))
(match t
[`(Vector ,ts ...)
(unless (and (0 . <= . i) (i . < . (length ts)))
(error 'type-check "index ~a out of bounds\nin ~v" i e))
(values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
[else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
[(Prim 'vector-set! (list e1 (Int i) arg) )
(define-values (e-vec t-vec) (recur e1))
(define-values (e-arg^ t-arg) (recur arg))
(match t-vec
[`(Vector ,ts ...)
(unless (and (0 . <= . i) (i . < . (length ts)))
(error 'type-check "index ~a out of bounds\nin ~v" i e))
(check-type-equal? (list-ref ts i) t-arg e)
(values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
[else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
[(Prim 'vector-length (list e))
(define-values (e^ t) (recur e))
(match t
[`(Vector ,ts ...)
(values (Prim 'vector-length (list e^)) 'Integer)]
[else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
[(Prim 'eq? (list arg1 arg2))
(define-values (e1 t1) (recur arg1))
(define-values (e2 t2) (recur arg2))
(match* (t1 t2)
[(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
[(other wise) (check-type-equal? t1 t2 e)])
(values (Prim 'eq? (list e1 e2)) 'Boolean)]
[(GlobalValue name)
(values (GlobalValue name) 'Integer)]
[(Allocate size t)
(values (Allocate size t) t)]
[(Collect size)
(values (Collect size) 'Void)]
[else ((super type-check-exp env) e)])))
(define/override ((type-check-stmt env) s)
(match s
[(Collect size) (void)]
[(Prim 'vector-set! (list vec index rhs))
#:when (and (exp-ready? vec env) (exp-ready? index env)
(exp-ready? rhs env))
((type-check-exp env) s)]
[else ((super type-check-stmt env) s)]))
))
(define type-check-Cvec-class (type-check-Cvec-mixin
(type-check-Cwhile-mixin
(type-check-Cif-mixin
(type-check-Cvar-mixin
type-check-Lvec-class)))))
(define (type-check-Cvec p)
(send (new type-check-Cvec-class) type-check-program p))
| |
bffd5844cd0d63c7da7e4a57c574b423dcd6fab4c674921508f259c9455da34e | yuriy-chumak/ol | time.scm | ;
(define-library (scheme time)
(version 1.0)
(license MIT/LGPL3)
(keywords (scheme time))
(description "
Scheme time library.")
(import
(scheme core))
(export
current-jiffy
current-second
jiffies-per-second
)
(begin
(define (current-jiffy)
(cdr (syscall 96)))
(define (current-second)
(car (syscall 96)))
(define (jiffies-per-second)
1000000)
))
| null | https://raw.githubusercontent.com/yuriy-chumak/ol/83dd03d311339763682eab02cbe0c1321daa25bc/libraries/scheme/time.scm | scheme | (define-library (scheme time)
(version 1.0)
(license MIT/LGPL3)
(keywords (scheme time))
(description "
Scheme time library.")
(import
(scheme core))
(export
current-jiffy
current-second
jiffies-per-second
)
(begin
(define (current-jiffy)
(cdr (syscall 96)))
(define (current-second)
(car (syscall 96)))
(define (jiffies-per-second)
1000000)
))
| |
cf1c1039cc4c1ab1efce9e60641191056b60dcada40c1ae0e9ea9d5e7192ab2b | lemmaandrew/CodingBatHaskell | doubleChar.hs | From
Given a string , return a string where for every char in the original , there are two
chars .
Given a string, return a string where for every char in the original, there are two
chars.
-}
import Test.Hspec ( hspec, describe, it, shouldBe )
doubleChar :: String -> String
doubleChar str = undefined
main :: IO ()
main = hspec $ describe "Tests:" $ do
it "\"TThhee\"" $
doubleChar "The" `shouldBe` "TThhee"
it "\"AAAAbbbb\"" $
doubleChar "AAbb" `shouldBe` "AAAAbbbb"
it "\"HHii--TThheerree\"" $
doubleChar "Hi-There" `shouldBe` "HHii--TThheerree"
it "\"WWoorrdd!!\"" $
doubleChar "Word!" `shouldBe` "WWoorrdd!!"
it "\"!!!!\"" $
doubleChar "!!" `shouldBe` "!!!!"
it "\"\"" $
doubleChar "" `shouldBe` ""
it "\"aa\"" $
doubleChar "a" `shouldBe` "aa"
it "\"..\"" $
doubleChar "." `shouldBe` ".."
it "\"aaaa\"" $
doubleChar "aa" `shouldBe` "aaaa"
| null | https://raw.githubusercontent.com/lemmaandrew/CodingBatHaskell/d839118be02e1867504206657a0664fd79d04736/CodingBat/String-2/doubleChar.hs | haskell | TThheerree\"" $ | From
Given a string , return a string where for every char in the original , there are two
chars .
Given a string, return a string where for every char in the original, there are two
chars.
-}
import Test.Hspec ( hspec, describe, it, shouldBe )
doubleChar :: String -> String
doubleChar str = undefined
main :: IO ()
main = hspec $ describe "Tests:" $ do
it "\"TThhee\"" $
doubleChar "The" `shouldBe` "TThhee"
it "\"AAAAbbbb\"" $
doubleChar "AAbb" `shouldBe` "AAAAbbbb"
doubleChar "Hi-There" `shouldBe` "HHii--TThheerree"
it "\"WWoorrdd!!\"" $
doubleChar "Word!" `shouldBe` "WWoorrdd!!"
it "\"!!!!\"" $
doubleChar "!!" `shouldBe` "!!!!"
it "\"\"" $
doubleChar "" `shouldBe` ""
it "\"aa\"" $
doubleChar "a" `shouldBe` "aa"
it "\"..\"" $
doubleChar "." `shouldBe` ".."
it "\"aaaa\"" $
doubleChar "aa" `shouldBe` "aaaa"
|
651346cf2dc022daf24d9c9053ce39994e76ba6a239869d62d587dc4ccc2daa9 | pbv/codex | Utils.hs | {-# LANGUAGE OverloadedStrings #-}
# LANGUAGE RecordWildCards #
# LANGUAGE ScopedTypeVariables #
module Codex.Tester.Utils
( match
, withTemp, withTempDir
, assert
, fileExists
, removeFileIfExists
, cleanupFiles
, chmod
, readable, executable, writeable
, runCompiler
, safeExec
, unsafeExec
, getMetaArgs
, parseArgs
, globPatterns
) where
import Data.Text(Text)
import qualified Data.Text.IO as T
import Control.Exception hiding (assert)
import Control.Monad (when, unless)
import Control.Monad.Trans
import System.IO
import System.IO.Temp
import System.Exit
import System.Directory (doesFileExist, removeFile)
import System.Posix.Files
import System.Posix.Types (FileMode)
import System.FilePath.Glob(glob)
import System.FilePath ((</>))
import Control.Concurrent (forkIO)
import Control.Concurrent.Async (concurrently)
import System.Process (readProcessWithExitCode,
waitForProcess)
import System.IO.Streams (InputStream, OutputStream)
import qualified System.IO.Streams as Streams
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Builder as B
import qualified Data.ByteString.Lazy as LB
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.Encoding.Error as T
import Data.Int (Int64)
import Data.List (sort)
import Data.Bits
import Data.Maybe(catMaybes)
import Text.Pandoc(Meta)
import Codex.Page(lookupFromMeta)
import Codex.Tester.Result
import Codex.Tester.Limits
import qualified ShellWords
-- | match a piece of text
match :: Text -> Text -> Bool
match = T.isInfixOf
-- | aquire and release temporary files and directories
withTemp :: MonadIO m => FilePath -> Text -> (FilePath -> IO a) -> m a
withTemp name contents k
= liftIO $ withSystemTempFile name (\f h -> T.hPutStr h contents >> hClose h >> k f)
withTempDir :: MonadIO m => FilePath -> (FilePath -> IO a) -> m a
withTempDir name k
= liftIO $ withSystemTempDirectory name k
| ensure an test assertion ; throws MiscError otherwise
assert :: MonadIO m => IO Bool -> String -> m ()
assert chk msg = liftIO $ do
c <- chk
unless c $ throwIO (AssertionFailed msg)
fileExists :: FilePath -> IO Bool
fileExists = doesFileExist
-- | remove files if they exist, silently ignore otherwise
removeFileIfExists :: FilePath -> IO ()
removeFileIfExists f = do b<-doesFileExist f; when b (removeFile f)
cleanupFiles :: [FilePath] -> IO ()
cleanupFiles = mapM_ removeFileIfExists
chmod :: MonadIO m => (FileMode -> FileMode) -> FilePath -> m ()
chmod chg filepath = liftIO $ do
mode <- fileMode <$> getFileStatus filepath
setFileMode filepath (chg mode)
readable :: FileMode -> FileMode
readable mode =
mode .|. ownerReadMode .|. groupReadMode .|. otherReadMode
executable :: FileMode -> FileMode
executable mode =
mode .|. ownerExecuteMode .|. groupExecuteMode .|. otherExecuteMode
writeable :: FileMode -> FileMode
writeable mode =
mode .|. ownerWriteMode .|. groupWriteMode .|. otherWriteMode
-- | run a compiler (possibly under a safe sandbox)
runCompiler :: Maybe Limits -> FilePath -> [String] -> IO ()
runCompiler optLimits cmd args = do
(exitCode, out, err) <- case optLimits of
Nothing -> readTextProcessWithExitCode cmd args ""
Just limits -> safeExec limits cmd Nothing args ""
case exitCode of
ExitFailure _ ->
throwIO (compileError (out <> err))
ExitSuccess ->
return ()
readTextProcessWithExitCode cmd args stdin = do
(exitCode, out, err) <- readProcessWithExitCode cmd args stdin
return (exitCode, T.pack out, T.pack err)
-- | safeExec with text input/output
safeExec :: Limits
-> FilePath -- ^ command
-> Maybe FilePath -- ^ optional working directory
-> [String] -- ^ comand line arguments
^ stdin
-> IO (ExitCode, Text, Text)
-- ^ code, stdout, stderr
safeExec limits exec dir args stdin = do
(code, out, err) <- safeExecBS limits exec dir args (T.encodeUtf8 stdin)
return (code,
T.decodeUtf8With T.lenientDecode out,
T.decodeUtf8With T.lenientDecode err)
--
-- | safeExec using streaming I/O to handle output limits
--
safeExecBS :: Limits
-> FilePath -- ^ command
-> Maybe FilePath -- ^ working directory
-> [String] -- ^ arguments
^ stdin
-> IO (ExitCode, ByteString,ByteString)
-- ^ code, stdout, stderr
safeExecBS Limits{..} exec dir args inbs = do
(inp, outstream, errstream, pid) <-
(Streams.runInteractiveProcess "safeexec" (args' ++ args) dir Nothing)
(do forkIO (produceStream inp inbs)
(outbs, errbs) <- concurrently
(consumeStream outputLimit outstream)
(consumeStream outputLimit errstream)
code <- waitForProcess pid
return (code, outbs, errbs)
) `catch` (\(e :: SomeException) ->
do code <- waitForProcess pid
return (code, "", B.pack $ show e)
)
where
default output limit : 50 K bytes
outputLimit = maybe 50000 fromIntegral maxFSize
mkArg opt = maybe [] (\c -> [opt, show c])
args' = mkArg "--cpu" maxCpuTime
++
mkArg "--clock" maxClockTime
++
mkArg "--mem" maxMemory
++
mkArg "--stack" maxStack
++
mkArg "--fsize" maxFSize
++
mkArg "--core" maxCore
++
mkArg "--nproc" numProc
++
["--exec", exec]
produceStream :: OutputStream ByteString -> ByteString -> IO ()
produceStream out bs
= Streams.fromByteString bs >>= Streams.connectTo out
-- | concatenate bytes from an input stream upto a specified limit
NB : this function consumes the input stream until the end
--
consumeStream :: Int64 -> InputStream ByteString -> IO ByteString
consumeStream limit stream = do
(stream, getCount) <- Streams.countInput stream
LB.toStrict . B.toLazyByteString <$>
Streams.foldM (\builder bs -> do
c <- getCount
if c > limit
then return builder
else return (builder <> B.byteString bs)) mempty stream
unsafeExec :: FilePath -- ^ command
-> [String] -- ^ arguments
^ stdin
-> IO (ExitCode, Text, Text) -- ^ code, stdout, stderr
unsafeExec exec args inp = do
(code, out, err) <-
readProcessWithExitCode exec args (T.unpack inp)
return (code, T.pack out, T.pack err)
--
-- get comand line arguments from metadata field values
first list are keys that take arguments ;
second list are keys that control on / off switches
--
getMetaArgs :: [String] -> [String] -> Meta -> [String]
getMetaArgs argKeys switchKeys meta
= catMaybes ([ do str <- lookupFromMeta key meta
Just ("--" ++ key ++ "=" ++ str)
| key <- argKeys ]
++
[ do bool <- lookupFromMeta key meta
if bool then Just ("--" ++ key) else Nothing
| key <- switchKeys ]
)
-- | parse a command line string
parseArgs :: MonadIO m => String -> m [String]
parseArgs ""
= return [] -- special case to signal empty arguments
parseArgs txt = case ShellWords.parse txt of
Left msg ->
liftIO $ throwIO $ userError ("parse error in command-line arguments: " <> msg)
Right args ->
return args
globPattern :: MonadIO m => String -> m [FilePath]
globPattern patt = do
files <- sort <$> liftIO (glob patt)
when (null files) $
liftIO $ throwIO $ userError ("no files match " ++ show patt)
return files
globPatterns :: MonadIO m => FilePath -> [String] -> m [FilePath]
globPatterns dir patts = concat <$> mapM (globPattern . (dir</>)) patts
| null | https://raw.githubusercontent.com/pbv/codex/1a5a81965b12f834b436e2165c07120360aded99/src/Codex/Tester/Utils.hs | haskell | # LANGUAGE OverloadedStrings #
| match a piece of text
| aquire and release temporary files and directories
| remove files if they exist, silently ignore otherwise
| run a compiler (possibly under a safe sandbox)
| safeExec with text input/output
^ command
^ optional working directory
^ comand line arguments
^ code, stdout, stderr
| safeExec using streaming I/O to handle output limits
^ command
^ working directory
^ arguments
^ code, stdout, stderr
| concatenate bytes from an input stream upto a specified limit
^ command
^ arguments
^ code, stdout, stderr
get comand line arguments from metadata field values
| parse a command line string
special case to signal empty arguments | # LANGUAGE RecordWildCards #
# LANGUAGE ScopedTypeVariables #
module Codex.Tester.Utils
( match
, withTemp, withTempDir
, assert
, fileExists
, removeFileIfExists
, cleanupFiles
, chmod
, readable, executable, writeable
, runCompiler
, safeExec
, unsafeExec
, getMetaArgs
, parseArgs
, globPatterns
) where
import Data.Text(Text)
import qualified Data.Text.IO as T
import Control.Exception hiding (assert)
import Control.Monad (when, unless)
import Control.Monad.Trans
import System.IO
import System.IO.Temp
import System.Exit
import System.Directory (doesFileExist, removeFile)
import System.Posix.Files
import System.Posix.Types (FileMode)
import System.FilePath.Glob(glob)
import System.FilePath ((</>))
import Control.Concurrent (forkIO)
import Control.Concurrent.Async (concurrently)
import System.Process (readProcessWithExitCode,
waitForProcess)
import System.IO.Streams (InputStream, OutputStream)
import qualified System.IO.Streams as Streams
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Builder as B
import qualified Data.ByteString.Lazy as LB
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.Encoding.Error as T
import Data.Int (Int64)
import Data.List (sort)
import Data.Bits
import Data.Maybe(catMaybes)
import Text.Pandoc(Meta)
import Codex.Page(lookupFromMeta)
import Codex.Tester.Result
import Codex.Tester.Limits
import qualified ShellWords
match :: Text -> Text -> Bool
match = T.isInfixOf
withTemp :: MonadIO m => FilePath -> Text -> (FilePath -> IO a) -> m a
withTemp name contents k
= liftIO $ withSystemTempFile name (\f h -> T.hPutStr h contents >> hClose h >> k f)
withTempDir :: MonadIO m => FilePath -> (FilePath -> IO a) -> m a
withTempDir name k
= liftIO $ withSystemTempDirectory name k
| ensure an test assertion ; throws MiscError otherwise
assert :: MonadIO m => IO Bool -> String -> m ()
assert chk msg = liftIO $ do
c <- chk
unless c $ throwIO (AssertionFailed msg)
fileExists :: FilePath -> IO Bool
fileExists = doesFileExist
removeFileIfExists :: FilePath -> IO ()
removeFileIfExists f = do b<-doesFileExist f; when b (removeFile f)
cleanupFiles :: [FilePath] -> IO ()
cleanupFiles = mapM_ removeFileIfExists
chmod :: MonadIO m => (FileMode -> FileMode) -> FilePath -> m ()
chmod chg filepath = liftIO $ do
mode <- fileMode <$> getFileStatus filepath
setFileMode filepath (chg mode)
readable :: FileMode -> FileMode
readable mode =
mode .|. ownerReadMode .|. groupReadMode .|. otherReadMode
executable :: FileMode -> FileMode
executable mode =
mode .|. ownerExecuteMode .|. groupExecuteMode .|. otherExecuteMode
writeable :: FileMode -> FileMode
writeable mode =
mode .|. ownerWriteMode .|. groupWriteMode .|. otherWriteMode
runCompiler :: Maybe Limits -> FilePath -> [String] -> IO ()
runCompiler optLimits cmd args = do
(exitCode, out, err) <- case optLimits of
Nothing -> readTextProcessWithExitCode cmd args ""
Just limits -> safeExec limits cmd Nothing args ""
case exitCode of
ExitFailure _ ->
throwIO (compileError (out <> err))
ExitSuccess ->
return ()
readTextProcessWithExitCode cmd args stdin = do
(exitCode, out, err) <- readProcessWithExitCode cmd args stdin
return (exitCode, T.pack out, T.pack err)
safeExec :: Limits
^ stdin
-> IO (ExitCode, Text, Text)
safeExec limits exec dir args stdin = do
(code, out, err) <- safeExecBS limits exec dir args (T.encodeUtf8 stdin)
return (code,
T.decodeUtf8With T.lenientDecode out,
T.decodeUtf8With T.lenientDecode err)
safeExecBS :: Limits
^ stdin
-> IO (ExitCode, ByteString,ByteString)
safeExecBS Limits{..} exec dir args inbs = do
(inp, outstream, errstream, pid) <-
(Streams.runInteractiveProcess "safeexec" (args' ++ args) dir Nothing)
(do forkIO (produceStream inp inbs)
(outbs, errbs) <- concurrently
(consumeStream outputLimit outstream)
(consumeStream outputLimit errstream)
code <- waitForProcess pid
return (code, outbs, errbs)
) `catch` (\(e :: SomeException) ->
do code <- waitForProcess pid
return (code, "", B.pack $ show e)
)
where
default output limit : 50 K bytes
outputLimit = maybe 50000 fromIntegral maxFSize
mkArg opt = maybe [] (\c -> [opt, show c])
args' = mkArg "--cpu" maxCpuTime
++
mkArg "--clock" maxClockTime
++
mkArg "--mem" maxMemory
++
mkArg "--stack" maxStack
++
mkArg "--fsize" maxFSize
++
mkArg "--core" maxCore
++
mkArg "--nproc" numProc
++
["--exec", exec]
produceStream :: OutputStream ByteString -> ByteString -> IO ()
produceStream out bs
= Streams.fromByteString bs >>= Streams.connectTo out
NB : this function consumes the input stream until the end
consumeStream :: Int64 -> InputStream ByteString -> IO ByteString
consumeStream limit stream = do
(stream, getCount) <- Streams.countInput stream
LB.toStrict . B.toLazyByteString <$>
Streams.foldM (\builder bs -> do
c <- getCount
if c > limit
then return builder
else return (builder <> B.byteString bs)) mempty stream
^ stdin
unsafeExec exec args inp = do
(code, out, err) <-
readProcessWithExitCode exec args (T.unpack inp)
return (code, T.pack out, T.pack err)
first list are keys that take arguments ;
second list are keys that control on / off switches
getMetaArgs :: [String] -> [String] -> Meta -> [String]
getMetaArgs argKeys switchKeys meta
= catMaybes ([ do str <- lookupFromMeta key meta
Just ("--" ++ key ++ "=" ++ str)
| key <- argKeys ]
++
[ do bool <- lookupFromMeta key meta
if bool then Just ("--" ++ key) else Nothing
| key <- switchKeys ]
)
parseArgs :: MonadIO m => String -> m [String]
parseArgs ""
parseArgs txt = case ShellWords.parse txt of
Left msg ->
liftIO $ throwIO $ userError ("parse error in command-line arguments: " <> msg)
Right args ->
return args
globPattern :: MonadIO m => String -> m [FilePath]
globPattern patt = do
files <- sort <$> liftIO (glob patt)
when (null files) $
liftIO $ throwIO $ userError ("no files match " ++ show patt)
return files
globPatterns :: MonadIO m => FilePath -> [String] -> m [FilePath]
globPatterns dir patts = concat <$> mapM (globPattern . (dir</>)) patts
|
2c5530dea192bb4a58a939fa568c1adaf2d2b27d8b182fd2542ce2922ea31e18 | scravy/bed-and-breakfast | Sugar.hs | # LANGUAGE Haskell2010 , TemplateHaskell #
module Numeric.Matrix.Sugar (
iMatrix, dMatrix
) where
import Numeric.Matrix
import Language.Haskell.TH
import Language.Haskell.TH.Quote
import Data.Data
import Data.Complex
import Data.Ratio
type ReadM a = String -> Matrix a
iMatrix = QuasiQuoter
(quoter (read :: ReadM Integer))
undefined undefined undefined
dMatrix = QuasiQuoter
(quoter (read :: ReadM Double))
undefined undefined undefined
quoter :: (Data e, MatrixElement e)
=> (String -> Matrix e) -> String -> Q Exp
quoter read str = do
let qExp = dataToExpQ (const Nothing) (toList (read str))
[e| fromList $qExp |]
| null | https://raw.githubusercontent.com/scravy/bed-and-breakfast/e900464394bb13edeb7a439ec758f059dc4712db/src/Numeric/Matrix/Sugar.hs | haskell | # LANGUAGE Haskell2010 , TemplateHaskell #
module Numeric.Matrix.Sugar (
iMatrix, dMatrix
) where
import Numeric.Matrix
import Language.Haskell.TH
import Language.Haskell.TH.Quote
import Data.Data
import Data.Complex
import Data.Ratio
type ReadM a = String -> Matrix a
iMatrix = QuasiQuoter
(quoter (read :: ReadM Integer))
undefined undefined undefined
dMatrix = QuasiQuoter
(quoter (read :: ReadM Double))
undefined undefined undefined
quoter :: (Data e, MatrixElement e)
=> (String -> Matrix e) -> String -> Q Exp
quoter read str = do
let qExp = dataToExpQ (const Nothing) (toList (read str))
[e| fromList $qExp |]
| |
f66509b0f278811f1cc4d1a94ca93299b203202893fdba4f84af1da74b074740 | denisidoro/rosebud | graphite.clj | (ns rosebud.logic.graphite
(:require [clojure.string :as str]))
(defn kw->str
[kw]
(-> kw
str
(subs 1)
(str/replace #"[/\.]" "_")))
(defn any->str
[x]
(if (keyword? x)
(kw->str x)
x))
(defn kv->str
[[k v]]
(str (any->str k) "=" (any->str v)))
(defn one-line
([path amount timestamp]
(one-line path amount timestamp {}))
([path amount timestamp tags]
(str (str/join ";" (into [path] (map kv->str tags)))
" "
(->> amount bigdec (format "%.2f"))
" "
(int (/ timestamp 1000)))))
;; TODO: use interpolated value
(defn bucket->msg
[{:bucket/keys [path tags]
:history/keys [interpolated-gross gross]}]
(when (and path gross)
(let [path-str (->> path (map any->str) (str/join "."))
lines (->> (or interpolated-gross gross)
(map (fn [[timestamp amount]] (one-line path-str amount timestamp tags)))
(str/join "\n"))]
(str lines "\n"))))
(defn msg
[buckets]
(->> buckets
(mapv bucket->msg)
(keep identity)
(apply str)))
| null | https://raw.githubusercontent.com/denisidoro/rosebud/90385528d9a75a0e17803df487a4f6cfb87e981c/server/src/rosebud/logic/graphite.clj | clojure | TODO: use interpolated value | (ns rosebud.logic.graphite
(:require [clojure.string :as str]))
(defn kw->str
[kw]
(-> kw
str
(subs 1)
(str/replace #"[/\.]" "_")))
(defn any->str
[x]
(if (keyword? x)
(kw->str x)
x))
(defn kv->str
[[k v]]
(str (any->str k) "=" (any->str v)))
(defn one-line
([path amount timestamp]
(one-line path amount timestamp {}))
([path amount timestamp tags]
(str (str/join ";" (into [path] (map kv->str tags)))
" "
(->> amount bigdec (format "%.2f"))
" "
(int (/ timestamp 1000)))))
(defn bucket->msg
[{:bucket/keys [path tags]
:history/keys [interpolated-gross gross]}]
(when (and path gross)
(let [path-str (->> path (map any->str) (str/join "."))
lines (->> (or interpolated-gross gross)
(map (fn [[timestamp amount]] (one-line path-str amount timestamp tags)))
(str/join "\n"))]
(str lines "\n"))))
(defn msg
[buckets]
(->> buckets
(mapv bucket->msg)
(keep identity)
(apply str)))
|
4af65a3875258192bb07f3a5c6e8c0b24fcf187bdfcf7dee1f085d11c3d4063b | input-output-hk/rscoin-haskell | Update.hs | # LANGUAGE ExistentialQuantification #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
# LANGUAGE TupleSections #
{-# LANGUAGE TypeSynonymInstances #-}
| WIP
module Test.RSCoin.Pure.Update
( Update (..)
, execUpdate
, runUpdate
, execUpdateSafe
, runUpdateSafe
) where
import Control.Exception (Exception, fromException, throw)
import Control.Monad.Catch (MonadThrow (throwM),
SomeException (..))
import Control.Monad.Except (runExceptT)
import Control.Monad.Reader (MonadReader (ask, local))
import Control.Monad.State (State, get, modify, runState)
import Control.Monad.State.Class (MonadState)
import Control.Monad.Trans.Except (ExceptT, throwE)
newtype Update e s a =
Update { getUpdate :: ExceptT e (State s) a }
deriving (MonadState s, Monad, Applicative, Functor)
instance MonadReader s (Update e s) where
ask = get
local f m = modify f >> m
instance Exception e => MonadThrow (Update e s) where
throwM e = Update . maybe (throw e') throwE $ fromException e'
where
e' = SomeException e
execUpdate :: Exception e => Update e s a -> s -> s
execUpdate u = snd . runUpdate u
runUpdate :: Exception e => Update e s a -> s -> (a, s)
runUpdate upd storage = either throw (, newStorage) res
where
(res, newStorage) = runState (runExceptT $ getUpdate upd) storage
execUpdateSafe :: (MonadThrow m, Exception e) => Update e s a -> s -> m s
execUpdateSafe upd storage = snd <$> runUpdateSafe upd storage
runUpdateSafe :: (MonadThrow m, Exception e) => Update e s a -> s -> m (a, s)
runUpdateSafe upd storage = either throwM (return . (, newStorage)) res
where
(res, newStorage) = runState (runExceptT $ getUpdate upd) storage
| null | https://raw.githubusercontent.com/input-output-hk/rscoin-haskell/109d8f6f226e9d0b360fcaac14c5a90da112a810/test/Test/RSCoin/Pure/Update.hs | haskell | # LANGUAGE RankNTypes #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeSynonymInstances # | # LANGUAGE ExistentialQuantification #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE TupleSections #
| WIP
module Test.RSCoin.Pure.Update
( Update (..)
, execUpdate
, runUpdate
, execUpdateSafe
, runUpdateSafe
) where
import Control.Exception (Exception, fromException, throw)
import Control.Monad.Catch (MonadThrow (throwM),
SomeException (..))
import Control.Monad.Except (runExceptT)
import Control.Monad.Reader (MonadReader (ask, local))
import Control.Monad.State (State, get, modify, runState)
import Control.Monad.State.Class (MonadState)
import Control.Monad.Trans.Except (ExceptT, throwE)
newtype Update e s a =
Update { getUpdate :: ExceptT e (State s) a }
deriving (MonadState s, Monad, Applicative, Functor)
instance MonadReader s (Update e s) where
ask = get
local f m = modify f >> m
instance Exception e => MonadThrow (Update e s) where
throwM e = Update . maybe (throw e') throwE $ fromException e'
where
e' = SomeException e
execUpdate :: Exception e => Update e s a -> s -> s
execUpdate u = snd . runUpdate u
runUpdate :: Exception e => Update e s a -> s -> (a, s)
runUpdate upd storage = either throw (, newStorage) res
where
(res, newStorage) = runState (runExceptT $ getUpdate upd) storage
execUpdateSafe :: (MonadThrow m, Exception e) => Update e s a -> s -> m s
execUpdateSafe upd storage = snd <$> runUpdateSafe upd storage
runUpdateSafe :: (MonadThrow m, Exception e) => Update e s a -> s -> m (a, s)
runUpdateSafe upd storage = either throwM (return . (, newStorage)) res
where
(res, newStorage) = runState (runExceptT $ getUpdate upd) storage
|
03ae7018b0539addd408e163823fcd0a4bd6147352c5868a5fd5523b4dec3095 | mfussenegger/mkjson | bench.hs | {-# LANGUAGE OverloadedStrings #-}
import Criterion.Main
import Data.Aeson (Value (..))
import Expr (Expr (..))
import Fake (eval, runFakeT)
import Control.Monad (replicateM)
exec :: Expr -> IO Value
exec expr = runFakeT (Just 1) (eval expr)
execRepeated :: Int -> Expr -> IO [Value]
execRepeated num expr = runFakeT (Just 1) (replicateM num (eval expr))
main :: IO ()
main = defaultMain
[ bgroup "ids" [ bench "uuid1" $ nfIO (exec "uuid1")
, bench "uuid4" $ nfIO (exec "uuid4") ]
, bgroup "numbers" [ bench "randomInt-0-100" $ nfIO (exec "randomInt(0, 100)" )
, bench "randomInt-0-1000" $ nfIO (exec "randomInt(0, 1000)" ) ]
, bgroup "regex" [ bench "from-regex" $ nfIO (execRepeated 20 "fromRegex('[0-1]{10}')") ]
]
| null | https://raw.githubusercontent.com/mfussenegger/mkjson/a5fdcf81431a57906d2c55091f605e3ddf1f7448/benchmarks/bench.hs | haskell | # LANGUAGE OverloadedStrings # |
import Criterion.Main
import Data.Aeson (Value (..))
import Expr (Expr (..))
import Fake (eval, runFakeT)
import Control.Monad (replicateM)
exec :: Expr -> IO Value
exec expr = runFakeT (Just 1) (eval expr)
execRepeated :: Int -> Expr -> IO [Value]
execRepeated num expr = runFakeT (Just 1) (replicateM num (eval expr))
main :: IO ()
main = defaultMain
[ bgroup "ids" [ bench "uuid1" $ nfIO (exec "uuid1")
, bench "uuid4" $ nfIO (exec "uuid4") ]
, bgroup "numbers" [ bench "randomInt-0-100" $ nfIO (exec "randomInt(0, 100)" )
, bench "randomInt-0-1000" $ nfIO (exec "randomInt(0, 1000)" ) ]
, bgroup "regex" [ bench "from-regex" $ nfIO (execRepeated 20 "fromRegex('[0-1]{10}')") ]
]
|
5a2a692a776524e7e7fcb47931c33d1eb7055317ca9ccfc48f6cd294dd3addc6 | nunchaku-inria/nunchaku | TypeCheck.ml |
(* This file is free software, part of nunchaku. See file "license" for more details. *)
(** {1 Type Checking of a problem} *)
module TI = TermInner
module Stmt = Statement
let section = Utils.Section.(make ~parent:root "ty_check")
exception Error of string
let () = Printexc.register_printer
(function
| Error msg -> Some (Utils.err_sprintf "@[broken invariant:@ %s@]" msg)
| _ -> None)
let error_ msg = raise (Error msg)
let errorf_ msg = CCFormat.ksprintf ~f:error_ msg
module Make(T : TI.S) = struct
module U = TI.Util(T)
module P = TI.Print(T)
module TyCard = AnalyzeType.Make(T)
type t = {
env: (T.t, T.t) Env.t;
cache: TyCard.cache option;
}
let empty ?(check_non_empty_tys=false) ?(env=Env.create()) () : t = {
env;
cache=
if check_non_empty_tys then Some (TyCard.create_cache ()) else None;
}
let prop = U.ty_prop
let find_ty_ ~env id =
try Env.find_ty_exn ~env id
with Not_found ->
errorf_ "identifier %a not defined in scope" ID.pp_full id
let err_ty_mismatch t exp act =
errorf_ "@[<2>type of `@[%a@]`@ should be `@[%a@]`,@ but is `@[%a@]`@]"
P.pp t P.pp exp P.pp act
(* check that [ty = prop] *)
let check_prop t ty =
if not (U.ty_is_Prop ty)
then err_ty_mismatch t prop ty
(* check that [ty_a = ty_b] *)
let check_same_ a b ty_a ty_b =
if not (U.equal ty_a ty_b)
then errorf_
"@[<2>expected@ @[`@[%a@]` : `@[%a@]`@]@ and@ \
@[<2>`@[%a@]`@ : `@[%a@]`@]@ to have the same type@]"
P.pp a P.pp ty_a P.pp b P.pp ty_b;
()
let check_same_ty ty_a ty_b =
if not (U.equal ty_a ty_b)
then errorf_
"@[types@ `@[%a@]`@ and `@[%a@]`@ should be the same@]"
P.pp ty_a P.pp ty_b;
()
module VarSet = U.VarSet
(* check invariants recursively, return type of term *)
let rec check ~env bound t =
match T.repr t with
| TI.Const id -> find_ty_ ~env id
| TI.Builtin b ->
begin match b with
| `Imply (a,b) ->
let tya = check ~env bound a in
let tyb = check ~env bound b in
check_prop a tya;
check_prop b tyb;
prop
| `Or l
| `And l ->
List.iter
(fun t -> let tyt = check ~env bound t in check_prop t tyt)
l;
prop
| `Not f ->
let tyf = check ~env bound f in
check_prop f tyf;
prop
| `True
| `False -> prop
| `Ite (a,b,c) ->
let tya = check ~env bound a in
let tyb = check ~env bound b in
let tyc = check ~env bound c in
check_prop a tya;
check_same_ b c tyb tyc;
tyb
| `Eq (a,b) ->
let tya = check ~env bound a in
let tyb = check ~env bound b in
check_same_ a b tya tyb;
prop
| `DataTest id ->
i d : , where tau inductive ; is - id : tau->prop
let ty = find_ty_ ~env id in
U.ty_arrow (U.ty_returns ty) prop
| `DataSelect (id,n) ->
(* id: a_1->a_2->tau, where tau inductive; select-id-i: tau->a_i*)
let ty = find_ty_ ~env id in
begin match U.get_ty_arg ty n with
| Some ty_arg ->
U.ty_arrow (U.ty_returns ty) ty_arg
| _ ->
error_ "cannot infer type, wrong argument to DataSelect"
end
| `Unparsable ty
| `Undefined_atom (_,ty) ->
ignore (check_is_ty ~env bound ty); ty
| `Card_at_least (ty,_) ->
ignore (check_is_ty ~env bound ty); prop
| `Undefined_self t -> check ~env bound t
| `Guard (t, g) ->
List.iter (check_is_prop ~env bound) g.Builtin.asserting;
check ~env bound t
end
| TI.Var v ->
if not (VarSet.mem v bound)
then errorf_ "variable %a not bound in scope" Var.pp_full v;
Var.ty v
| TI.App (f,l) ->
U.ty_apply (check ~env bound f)
~terms:l ~tys:(List.map (check ~env bound) l)
| TI.Bind (b,v,body) ->
begin match b with
| Binder.Forall
| Binder.Exists
| Binder.Mu ->
let bound' = check_var ~env bound v in
check ~env bound' body
| Binder.Fun ->
let bound' = check_var ~env bound v in
let ty_body = check ~env bound' body in
if U.ty_returns_Type (Var.ty v)
then U.ty_forall v ty_body
else U.ty_arrow (Var.ty v) ty_body
| Binder.TyForall ->
(* type of [pi a:type. body] is [type],
and [body : type] is mandatory *)
check_ty_forall_var ~env bound t v;
check_is_ty ~env (VarSet.add v bound) body
end
| TI.Let (v,t',u) ->
let ty_t' = check ~env bound t' in
let bound' = check_var ~env bound v in
check_same_ (U.var v) t' (Var.ty v) ty_t';
check ~env bound' u
| TI.Match (_,m,def) ->
(* TODO: check that each constructor is present, and only once *)
let id, (_, vars, rhs) = ID.Map.choose m in
let bound' = List.fold_left (check_var ~env) bound vars in
(* reference type *)
let ty = check ~env bound' rhs in
(* check other branches *)
ID.Map.iter
(fun id' (_, vars, rhs') ->
if not (ID.equal id id')
then (
let bound' = List.fold_left (check_var ~env) bound vars in
let ty' = check ~env bound' rhs' in
check_same_ rhs rhs' ty ty'
))
m;
TI.iter_default_case
(fun rhs' ->
let ty' = check ~env bound rhs' in
check_same_ rhs rhs' ty ty')
def;
ty
| TI.TyMeta _ -> assert false
| TI.TyBuiltin b ->
begin match b with
| `Kind -> failwith "Term_ho.ty: kind has no type"
| `Type -> U.ty_kind
| `Prop -> U.ty_type
| `Unitype -> U.ty_type
end
| TI.TyArrow (a,b) ->
(* TODO: if a=type, then b=type is mandatory *)
ignore (check_is_ty_or_Type ~env bound a);
let ty_b = check_is_ty_or_Type ~env bound b in
ty_b
and check_is_prop ~env bound t =
let ty = check ~env bound t in
check_prop t ty;
()
and check_var ~env bound v =
let _ = check ~env bound (Var.ty v) in
VarSet.add v bound
(* check that [v] is a proper type var *)
and check_ty_forall_var ~env bound t v =
let tyv = check ~env bound (Var.ty v) in
if not (U.ty_is_Type (Var.ty v)) && not (U.ty_is_Type tyv)
then
errorf_
"@[<2>type of `@[%a@]` in `@[%a@]`@ should be a type or `type`,@ but is `@[%a@]`@]"
Var.pp_full v P.pp t P.pp tyv;
()
and check_is_ty ~env bound t =
let ty = check ~env bound t in
if not (U.ty_is_Type ty) then err_ty_mismatch t U.ty_type ty;
U.ty_type
and check_is_ty_or_Type ~env bound t =
let ty = check ~env bound t in
if not (U.ty_returns_Type t) && not (U.ty_returns_Type ty)
then err_ty_mismatch t U.ty_type ty;
ty
let check_eqns ~env ~bound id (eqn:(_,_) Stmt.equations) =
match eqn with
| Stmt.Eqn_single (vars, rhs) ->
check that [ freevars rhs ⊆ vars ]
let free_rhs = U.free_vars ~bound rhs in
let diff = VarSet.diff free_rhs (VarSet.of_list vars) in
if not (VarSet.is_empty diff)
then (
let module PStmt = Statement.Print(P)(P) in
errorf_ "in equation `@[%a@]`,@ variables @[%a@]@ occur in RHS-term but are not bound"
(PStmt.pp_eqns id) eqn (Utils.pp_iter Var.pp_full) (VarSet.to_iter diff)
);
let bound' = List.fold_left (check_var ~env) bound vars in
check_is_prop ~env bound'
(U.eq
(U.app (U.const id) (List.map U.var vars))
rhs)
| Stmt.Eqn_nested l ->
List.iter
(fun (vars, args, rhs, side) ->
let bound' = List.fold_left (check_var ~env) bound vars in
check_is_prop ~env bound'
(U.eq
(U.app (U.const id) args)
rhs);
List.iter (check_is_prop ~env bound') side)
l
| Stmt.Eqn_app (_, vars, lhs, rhs) ->
let bound' = List.fold_left (check_var ~env) bound vars in
check_is_prop ~env bound' (U.eq lhs rhs)
let check_statement t st =
Utils.debugf ~section 4 "@[<2>type check@ `@[%a@]`@]"
(fun k-> let module PStmt = Statement.Print(P)(P) in k PStmt.pp st);
(* update env *)
let env = Env.add_statement ~env:t.env st in
let t' = {t with env; } in
let check_top env bound _pol () t = ignore (check ~env bound t) in
let check_ty env bound () t = ignore (check ~env bound t) in
(* check cardinalities *)
CCOpt.iter
(fun cache -> TyCard.check_non_zero ~cache env st)
t.cache;
(* basic check *)
let default_check st =
Stmt.fold_bind VarSet.empty () st
~bind:(check_var ~env)
~term:(check_top env) ~ty:(check_ty env)
in
(* check types *)
begin match Stmt.view st with
| Stmt.Axiom (Stmt.Axiom_rec defs) ->
(* special checks *)
List.iter
(fun def ->
let tyvars = def.Stmt.rec_ty_vars in
let bound = List.fold_left (check_var ~env) VarSet.empty tyvars in
let {Stmt.defined_head=id; _} = def.Stmt.rec_defined in
check_eqns ~env ~bound id def.Stmt.rec_eqns)
defs
| Stmt.Axiom (Stmt.Axiom_spec spec) ->
let bound = VarSet.empty in
Stmt.defined_of_spec spec
|> Iter.map Stmt.ty_of_defined
|> Iter.iter (fun ty -> ignore (check_is_ty ~env bound ty));
let bound = List.fold_left (check_var ~env) bound spec.Stmt.spec_ty_vars in
List.iter (check_is_prop ~env bound) spec.Stmt.spec_axioms
| Stmt.Copy c ->
default_check st;
(* check additional invariants *)
check_same_ty
c.Stmt.copy_to
(U.ty_app (U.ty_const c.Stmt.copy_id) (List.map U.ty_var c.Stmt.copy_vars));
check_same_ty
c.Stmt.copy_abstract_ty
(U.ty_forall_l c.Stmt.copy_vars
(U.ty_arrow c.Stmt.copy_of c.Stmt.copy_to));
check_same_ty
c.Stmt.copy_concrete_ty
(U.ty_forall_l c.Stmt.copy_vars
(U.ty_arrow c.Stmt.copy_to c.Stmt.copy_of));
begin match c.Stmt.copy_wrt with
| Stmt.Wrt_nothing -> ()
| Stmt.Wrt_subset p ->
(* check that [p : copy_of -> prop] *)
let ty_p = check ~env VarSet.empty p in
check_same_ty
(U.ty_arrow c.Stmt.copy_of U.ty_prop)
ty_p
| Stmt.Wrt_quotient (_, r) ->
(* check that [r : copy_of -> copy_of -> prop] *)
let ty_r = check ~env VarSet.empty r in
check_same_ty
(U.ty_arrow_l [c.Stmt.copy_of; c.Stmt.copy_of] U.ty_prop)
ty_r
end;
| _ -> default_check st
end;
t'
let check_problem t pb =
let _ = CCVector.fold check_statement t (Problem.statements pb) in
()
end
| null | https://raw.githubusercontent.com/nunchaku-inria/nunchaku/16f33db3f5e92beecfb679a13329063b194f753d/src/core/TypeCheck.ml | ocaml | This file is free software, part of nunchaku. See file "license" for more details.
* {1 Type Checking of a problem}
check that [ty = prop]
check that [ty_a = ty_b]
check invariants recursively, return type of term
id: a_1->a_2->tau, where tau inductive; select-id-i: tau->a_i
type of [pi a:type. body] is [type],
and [body : type] is mandatory
TODO: check that each constructor is present, and only once
reference type
check other branches
TODO: if a=type, then b=type is mandatory
check that [v] is a proper type var
update env
check cardinalities
basic check
check types
special checks
check additional invariants
check that [p : copy_of -> prop]
check that [r : copy_of -> copy_of -> prop] |
module TI = TermInner
module Stmt = Statement
let section = Utils.Section.(make ~parent:root "ty_check")
exception Error of string
let () = Printexc.register_printer
(function
| Error msg -> Some (Utils.err_sprintf "@[broken invariant:@ %s@]" msg)
| _ -> None)
let error_ msg = raise (Error msg)
let errorf_ msg = CCFormat.ksprintf ~f:error_ msg
module Make(T : TI.S) = struct
module U = TI.Util(T)
module P = TI.Print(T)
module TyCard = AnalyzeType.Make(T)
type t = {
env: (T.t, T.t) Env.t;
cache: TyCard.cache option;
}
let empty ?(check_non_empty_tys=false) ?(env=Env.create()) () : t = {
env;
cache=
if check_non_empty_tys then Some (TyCard.create_cache ()) else None;
}
let prop = U.ty_prop
let find_ty_ ~env id =
try Env.find_ty_exn ~env id
with Not_found ->
errorf_ "identifier %a not defined in scope" ID.pp_full id
let err_ty_mismatch t exp act =
errorf_ "@[<2>type of `@[%a@]`@ should be `@[%a@]`,@ but is `@[%a@]`@]"
P.pp t P.pp exp P.pp act
let check_prop t ty =
if not (U.ty_is_Prop ty)
then err_ty_mismatch t prop ty
let check_same_ a b ty_a ty_b =
if not (U.equal ty_a ty_b)
then errorf_
"@[<2>expected@ @[`@[%a@]` : `@[%a@]`@]@ and@ \
@[<2>`@[%a@]`@ : `@[%a@]`@]@ to have the same type@]"
P.pp a P.pp ty_a P.pp b P.pp ty_b;
()
let check_same_ty ty_a ty_b =
if not (U.equal ty_a ty_b)
then errorf_
"@[types@ `@[%a@]`@ and `@[%a@]`@ should be the same@]"
P.pp ty_a P.pp ty_b;
()
module VarSet = U.VarSet
let rec check ~env bound t =
match T.repr t with
| TI.Const id -> find_ty_ ~env id
| TI.Builtin b ->
begin match b with
| `Imply (a,b) ->
let tya = check ~env bound a in
let tyb = check ~env bound b in
check_prop a tya;
check_prop b tyb;
prop
| `Or l
| `And l ->
List.iter
(fun t -> let tyt = check ~env bound t in check_prop t tyt)
l;
prop
| `Not f ->
let tyf = check ~env bound f in
check_prop f tyf;
prop
| `True
| `False -> prop
| `Ite (a,b,c) ->
let tya = check ~env bound a in
let tyb = check ~env bound b in
let tyc = check ~env bound c in
check_prop a tya;
check_same_ b c tyb tyc;
tyb
| `Eq (a,b) ->
let tya = check ~env bound a in
let tyb = check ~env bound b in
check_same_ a b tya tyb;
prop
| `DataTest id ->
i d : , where tau inductive ; is - id : tau->prop
let ty = find_ty_ ~env id in
U.ty_arrow (U.ty_returns ty) prop
| `DataSelect (id,n) ->
let ty = find_ty_ ~env id in
begin match U.get_ty_arg ty n with
| Some ty_arg ->
U.ty_arrow (U.ty_returns ty) ty_arg
| _ ->
error_ "cannot infer type, wrong argument to DataSelect"
end
| `Unparsable ty
| `Undefined_atom (_,ty) ->
ignore (check_is_ty ~env bound ty); ty
| `Card_at_least (ty,_) ->
ignore (check_is_ty ~env bound ty); prop
| `Undefined_self t -> check ~env bound t
| `Guard (t, g) ->
List.iter (check_is_prop ~env bound) g.Builtin.asserting;
check ~env bound t
end
| TI.Var v ->
if not (VarSet.mem v bound)
then errorf_ "variable %a not bound in scope" Var.pp_full v;
Var.ty v
| TI.App (f,l) ->
U.ty_apply (check ~env bound f)
~terms:l ~tys:(List.map (check ~env bound) l)
| TI.Bind (b,v,body) ->
begin match b with
| Binder.Forall
| Binder.Exists
| Binder.Mu ->
let bound' = check_var ~env bound v in
check ~env bound' body
| Binder.Fun ->
let bound' = check_var ~env bound v in
let ty_body = check ~env bound' body in
if U.ty_returns_Type (Var.ty v)
then U.ty_forall v ty_body
else U.ty_arrow (Var.ty v) ty_body
| Binder.TyForall ->
check_ty_forall_var ~env bound t v;
check_is_ty ~env (VarSet.add v bound) body
end
| TI.Let (v,t',u) ->
let ty_t' = check ~env bound t' in
let bound' = check_var ~env bound v in
check_same_ (U.var v) t' (Var.ty v) ty_t';
check ~env bound' u
| TI.Match (_,m,def) ->
let id, (_, vars, rhs) = ID.Map.choose m in
let bound' = List.fold_left (check_var ~env) bound vars in
let ty = check ~env bound' rhs in
ID.Map.iter
(fun id' (_, vars, rhs') ->
if not (ID.equal id id')
then (
let bound' = List.fold_left (check_var ~env) bound vars in
let ty' = check ~env bound' rhs' in
check_same_ rhs rhs' ty ty'
))
m;
TI.iter_default_case
(fun rhs' ->
let ty' = check ~env bound rhs' in
check_same_ rhs rhs' ty ty')
def;
ty
| TI.TyMeta _ -> assert false
| TI.TyBuiltin b ->
begin match b with
| `Kind -> failwith "Term_ho.ty: kind has no type"
| `Type -> U.ty_kind
| `Prop -> U.ty_type
| `Unitype -> U.ty_type
end
| TI.TyArrow (a,b) ->
ignore (check_is_ty_or_Type ~env bound a);
let ty_b = check_is_ty_or_Type ~env bound b in
ty_b
and check_is_prop ~env bound t =
let ty = check ~env bound t in
check_prop t ty;
()
and check_var ~env bound v =
let _ = check ~env bound (Var.ty v) in
VarSet.add v bound
and check_ty_forall_var ~env bound t v =
let tyv = check ~env bound (Var.ty v) in
if not (U.ty_is_Type (Var.ty v)) && not (U.ty_is_Type tyv)
then
errorf_
"@[<2>type of `@[%a@]` in `@[%a@]`@ should be a type or `type`,@ but is `@[%a@]`@]"
Var.pp_full v P.pp t P.pp tyv;
()
and check_is_ty ~env bound t =
let ty = check ~env bound t in
if not (U.ty_is_Type ty) then err_ty_mismatch t U.ty_type ty;
U.ty_type
and check_is_ty_or_Type ~env bound t =
let ty = check ~env bound t in
if not (U.ty_returns_Type t) && not (U.ty_returns_Type ty)
then err_ty_mismatch t U.ty_type ty;
ty
let check_eqns ~env ~bound id (eqn:(_,_) Stmt.equations) =
match eqn with
| Stmt.Eqn_single (vars, rhs) ->
check that [ freevars rhs ⊆ vars ]
let free_rhs = U.free_vars ~bound rhs in
let diff = VarSet.diff free_rhs (VarSet.of_list vars) in
if not (VarSet.is_empty diff)
then (
let module PStmt = Statement.Print(P)(P) in
errorf_ "in equation `@[%a@]`,@ variables @[%a@]@ occur in RHS-term but are not bound"
(PStmt.pp_eqns id) eqn (Utils.pp_iter Var.pp_full) (VarSet.to_iter diff)
);
let bound' = List.fold_left (check_var ~env) bound vars in
check_is_prop ~env bound'
(U.eq
(U.app (U.const id) (List.map U.var vars))
rhs)
| Stmt.Eqn_nested l ->
List.iter
(fun (vars, args, rhs, side) ->
let bound' = List.fold_left (check_var ~env) bound vars in
check_is_prop ~env bound'
(U.eq
(U.app (U.const id) args)
rhs);
List.iter (check_is_prop ~env bound') side)
l
| Stmt.Eqn_app (_, vars, lhs, rhs) ->
let bound' = List.fold_left (check_var ~env) bound vars in
check_is_prop ~env bound' (U.eq lhs rhs)
let check_statement t st =
Utils.debugf ~section 4 "@[<2>type check@ `@[%a@]`@]"
(fun k-> let module PStmt = Statement.Print(P)(P) in k PStmt.pp st);
let env = Env.add_statement ~env:t.env st in
let t' = {t with env; } in
let check_top env bound _pol () t = ignore (check ~env bound t) in
let check_ty env bound () t = ignore (check ~env bound t) in
CCOpt.iter
(fun cache -> TyCard.check_non_zero ~cache env st)
t.cache;
let default_check st =
Stmt.fold_bind VarSet.empty () st
~bind:(check_var ~env)
~term:(check_top env) ~ty:(check_ty env)
in
begin match Stmt.view st with
| Stmt.Axiom (Stmt.Axiom_rec defs) ->
List.iter
(fun def ->
let tyvars = def.Stmt.rec_ty_vars in
let bound = List.fold_left (check_var ~env) VarSet.empty tyvars in
let {Stmt.defined_head=id; _} = def.Stmt.rec_defined in
check_eqns ~env ~bound id def.Stmt.rec_eqns)
defs
| Stmt.Axiom (Stmt.Axiom_spec spec) ->
let bound = VarSet.empty in
Stmt.defined_of_spec spec
|> Iter.map Stmt.ty_of_defined
|> Iter.iter (fun ty -> ignore (check_is_ty ~env bound ty));
let bound = List.fold_left (check_var ~env) bound spec.Stmt.spec_ty_vars in
List.iter (check_is_prop ~env bound) spec.Stmt.spec_axioms
| Stmt.Copy c ->
default_check st;
check_same_ty
c.Stmt.copy_to
(U.ty_app (U.ty_const c.Stmt.copy_id) (List.map U.ty_var c.Stmt.copy_vars));
check_same_ty
c.Stmt.copy_abstract_ty
(U.ty_forall_l c.Stmt.copy_vars
(U.ty_arrow c.Stmt.copy_of c.Stmt.copy_to));
check_same_ty
c.Stmt.copy_concrete_ty
(U.ty_forall_l c.Stmt.copy_vars
(U.ty_arrow c.Stmt.copy_to c.Stmt.copy_of));
begin match c.Stmt.copy_wrt with
| Stmt.Wrt_nothing -> ()
| Stmt.Wrt_subset p ->
let ty_p = check ~env VarSet.empty p in
check_same_ty
(U.ty_arrow c.Stmt.copy_of U.ty_prop)
ty_p
| Stmt.Wrt_quotient (_, r) ->
let ty_r = check ~env VarSet.empty r in
check_same_ty
(U.ty_arrow_l [c.Stmt.copy_of; c.Stmt.copy_of] U.ty_prop)
ty_r
end;
| _ -> default_check st
end;
t'
let check_problem t pb =
let _ = CCVector.fold check_statement t (Problem.statements pb) in
()
end
|
193859ae39cedea166b3eb61696ec6b228afb200f64455d7a0e4d8d998342f15 | metaocaml/ber-metaocaml | pr5689.ml | (* TEST
* expect
*)
type inkind = [ `Link | `Nonlink ]
type _ inline_t =
| Text: string -> [< inkind > `Nonlink ] inline_t
| Bold: 'a inline_t list -> 'a inline_t
| Link: string -> [< inkind > `Link ] inline_t
| Mref: string * [ `Nonlink ] inline_t list -> [< inkind > `Link ] inline_t
;;
let uppercase seq =
let rec process: type a. a inline_t -> a inline_t = function
| Text txt -> Text (String.uppercase_ascii txt)
| Bold xs -> Bold (List.map process xs)
| Link lnk -> Link lnk
| Mref (lnk, xs) -> Mref (lnk, List.map process xs)
in List.map process seq
;;
[%%expect{|
type inkind = [ `Link | `Nonlink ]
type _ inline_t =
Text : string -> [< inkind > `Nonlink ] inline_t
| Bold : 'a inline_t list -> 'a inline_t
| Link : string -> [< inkind > `Link ] inline_t
| Mref : string *
[ `Nonlink ] inline_t list -> [< inkind > `Link ] inline_t
val uppercase : 'a inline_t list -> 'a inline_t list = <fun>
|}];;
type ast_t =
| Ast_Text of string
| Ast_Bold of ast_t list
| Ast_Link of string
| Ast_Mref of string * ast_t list
;;
let inlineseq_from_astseq seq =
let rec process_nonlink = function
| Ast_Text txt -> Text txt
| Ast_Bold xs -> Bold (List.map process_nonlink xs)
| _ -> assert false in
let rec process_any = function
| Ast_Text txt -> Text txt
| Ast_Bold xs -> Bold (List.map process_any xs)
| Ast_Link lnk -> Link lnk
| Ast_Mref (lnk, xs) -> Mref (lnk, List.map process_nonlink xs)
in List.map process_any seq
;;
[%%expect{|
type ast_t =
Ast_Text of string
| Ast_Bold of ast_t list
| Ast_Link of string
| Ast_Mref of string * ast_t list
val inlineseq_from_astseq : ast_t list -> inkind inline_t list = <fun>
|}];;
(* OK *)
type _ linkp =
| Nonlink : [ `Nonlink ] linkp
| Maylink : inkind linkp
;;
let inlineseq_from_astseq seq =
let rec process : type a. a linkp -> ast_t -> a inline_t =
fun allow_link ast ->
match (allow_link, ast) with
| (Maylink, Ast_Text txt) -> Text txt
| (Nonlink, Ast_Text txt) -> Text txt
| (x, Ast_Bold xs) -> Bold (List.map (process x) xs)
| (Maylink, Ast_Link lnk) -> Link lnk
| (Nonlink, Ast_Link _) -> assert false
| (Maylink, Ast_Mref (lnk, xs)) ->
Mref (lnk, List.map (process Nonlink) xs)
| (Nonlink, Ast_Mref _) -> assert false
in List.map (process Maylink) seq
;;
[%%expect{|
type _ linkp = Nonlink : [ `Nonlink ] linkp | Maylink : inkind linkp
val inlineseq_from_astseq : ast_t list -> inkind inline_t list = <fun>
|}];;
(* Bad *)
type _ linkp2 = Kind : 'a linkp -> ([< inkind ] as 'a) linkp2
;;
let inlineseq_from_astseq seq =
let rec process : type a. a linkp2 -> ast_t -> a inline_t =
fun allow_link ast ->
match (allow_link, ast) with
| (Kind _, Ast_Text txt) -> Text txt
| (x, Ast_Bold xs) -> Bold (List.map (process x) xs)
| (Kind Maylink, Ast_Link lnk) -> Link lnk
| (Kind Nonlink, Ast_Link _) -> assert false
| (Kind Maylink, Ast_Mref (lnk, xs)) ->
Mref (lnk, List.map (process (Kind Nonlink)) xs)
| (Kind Nonlink, Ast_Mref _) -> assert false
in List.map (process (Kind Maylink)) seq
;;
[%%expect{|
type _ linkp2 = Kind : 'a linkp -> ([< inkind ] as 'a) linkp2
Line 7, characters 35-43:
7 | | (Kind _, Ast_Text txt) -> Text txt
^^^^^^^^
Error: This expression has type ([< inkind > `Nonlink ] as 'a) inline_t
but an expression was expected of type a inline_t
Type 'a = [< `Link | `Nonlink > `Nonlink ] is not compatible with type
a = [< `Link | `Nonlink ]
The second variant type is bound to $'a,
it may not allow the tag(s) `Nonlink
|}];;
| null | https://raw.githubusercontent.com/metaocaml/ber-metaocaml/4992d1f87fc08ccb958817926cf9d1d739caf3a2/testsuite/tests/typing-gadts/pr5689.ml | ocaml | TEST
* expect
OK
Bad |
type inkind = [ `Link | `Nonlink ]
type _ inline_t =
| Text: string -> [< inkind > `Nonlink ] inline_t
| Bold: 'a inline_t list -> 'a inline_t
| Link: string -> [< inkind > `Link ] inline_t
| Mref: string * [ `Nonlink ] inline_t list -> [< inkind > `Link ] inline_t
;;
let uppercase seq =
let rec process: type a. a inline_t -> a inline_t = function
| Text txt -> Text (String.uppercase_ascii txt)
| Bold xs -> Bold (List.map process xs)
| Link lnk -> Link lnk
| Mref (lnk, xs) -> Mref (lnk, List.map process xs)
in List.map process seq
;;
[%%expect{|
type inkind = [ `Link | `Nonlink ]
type _ inline_t =
Text : string -> [< inkind > `Nonlink ] inline_t
| Bold : 'a inline_t list -> 'a inline_t
| Link : string -> [< inkind > `Link ] inline_t
| Mref : string *
[ `Nonlink ] inline_t list -> [< inkind > `Link ] inline_t
val uppercase : 'a inline_t list -> 'a inline_t list = <fun>
|}];;
type ast_t =
| Ast_Text of string
| Ast_Bold of ast_t list
| Ast_Link of string
| Ast_Mref of string * ast_t list
;;
let inlineseq_from_astseq seq =
let rec process_nonlink = function
| Ast_Text txt -> Text txt
| Ast_Bold xs -> Bold (List.map process_nonlink xs)
| _ -> assert false in
let rec process_any = function
| Ast_Text txt -> Text txt
| Ast_Bold xs -> Bold (List.map process_any xs)
| Ast_Link lnk -> Link lnk
| Ast_Mref (lnk, xs) -> Mref (lnk, List.map process_nonlink xs)
in List.map process_any seq
;;
[%%expect{|
type ast_t =
Ast_Text of string
| Ast_Bold of ast_t list
| Ast_Link of string
| Ast_Mref of string * ast_t list
val inlineseq_from_astseq : ast_t list -> inkind inline_t list = <fun>
|}];;
type _ linkp =
| Nonlink : [ `Nonlink ] linkp
| Maylink : inkind linkp
;;
let inlineseq_from_astseq seq =
let rec process : type a. a linkp -> ast_t -> a inline_t =
fun allow_link ast ->
match (allow_link, ast) with
| (Maylink, Ast_Text txt) -> Text txt
| (Nonlink, Ast_Text txt) -> Text txt
| (x, Ast_Bold xs) -> Bold (List.map (process x) xs)
| (Maylink, Ast_Link lnk) -> Link lnk
| (Nonlink, Ast_Link _) -> assert false
| (Maylink, Ast_Mref (lnk, xs)) ->
Mref (lnk, List.map (process Nonlink) xs)
| (Nonlink, Ast_Mref _) -> assert false
in List.map (process Maylink) seq
;;
[%%expect{|
type _ linkp = Nonlink : [ `Nonlink ] linkp | Maylink : inkind linkp
val inlineseq_from_astseq : ast_t list -> inkind inline_t list = <fun>
|}];;
type _ linkp2 = Kind : 'a linkp -> ([< inkind ] as 'a) linkp2
;;
let inlineseq_from_astseq seq =
let rec process : type a. a linkp2 -> ast_t -> a inline_t =
fun allow_link ast ->
match (allow_link, ast) with
| (Kind _, Ast_Text txt) -> Text txt
| (x, Ast_Bold xs) -> Bold (List.map (process x) xs)
| (Kind Maylink, Ast_Link lnk) -> Link lnk
| (Kind Nonlink, Ast_Link _) -> assert false
| (Kind Maylink, Ast_Mref (lnk, xs)) ->
Mref (lnk, List.map (process (Kind Nonlink)) xs)
| (Kind Nonlink, Ast_Mref _) -> assert false
in List.map (process (Kind Maylink)) seq
;;
[%%expect{|
type _ linkp2 = Kind : 'a linkp -> ([< inkind ] as 'a) linkp2
Line 7, characters 35-43:
7 | | (Kind _, Ast_Text txt) -> Text txt
^^^^^^^^
Error: This expression has type ([< inkind > `Nonlink ] as 'a) inline_t
but an expression was expected of type a inline_t
Type 'a = [< `Link | `Nonlink > `Nonlink ] is not compatible with type
a = [< `Link | `Nonlink ]
The second variant type is bound to $'a,
it may not allow the tag(s) `Nonlink
|}];;
|
87ee2381dee6041031c5addc223fb613ca23c82abe7bd8b965cba071f4706428 | theodormoroianu/SecondYearCourses | HaskellChurch_20210415162050.hs | {-# LANGUAGE RankNTypes #-}
module HaskellChurch where
A boolean is any way to choose between two alternatives
newtype CBool = CBool {cIf :: forall t. t -> t -> t}
An instance to show as regular Booleans
instance Show CBool where
show b = show $ cIf b True False
The boolean constant true always chooses the first alternative
cTrue :: CBool
cTrue = undefined
The boolean constant false always chooses the second alternative
cFalse :: CBool
cFalse = undefined
--The boolean negation switches the alternatives
cNot :: CBool -> CBool
cNot = undefined
--The boolean conjunction can be built as a conditional
(&&:) :: CBool -> CBool -> CBool
(&&:) = undefined
infixr 3 &&:
--The boolean disjunction can be built as a conditional
(||:) :: CBool -> CBool -> CBool
(||:) = undefined
infixr 2 ||:
-- a pair is a way to compute something based on the values
-- contained within the pair.
newtype CPair a b = CPair { cOn :: forall c . (a -> b -> c) -> c }
An instance to show CPairs as regular pairs .
instance (Show a, Show b) => Show (CPair a b) where
show p = show $ cOn p (,)
builds a pair out of two values as an object which , when given
--a function to be applied on the values, it will apply it on them.
cPair :: a -> b -> CPair a b
cPair = undefined
first projection uses the function selecting first component on a pair
cFst :: CPair a b -> a
cFst = undefined
second projection
cSnd :: CPair a b -> b
cSnd = undefined
-- A natural number is any way to iterate a function s a number of times
-- over an initial value z
newtype CNat = CNat { cFor :: forall t. (t -> t) -> t -> t }
-- An instance to show CNats as regular natural numbers
instance Show CNat where
show n = show $ cFor n (1 +) (0 :: Integer)
--0 will iterate the function s 0 times over z, producing z
c0 :: CNat
c0 = undefined
1 is the the function s iterated 1 times over z , that is , z
c1 :: CNat
c1 = undefined
--Successor n either
- applies s one more time in addition to what n does
-- - iterates s n times over (s z)
cS :: CNat -> CNat
cS = undefined
--Addition of m and n is done by iterating s n times over m
(+:) :: CNat -> CNat -> CNat
(+:) = undefined
infixl 6 +:
--Multiplication of m and n can be done by composing n and m
(*:) :: CNat -> CNat -> CNat
(*:) = \n m -> CNat $ cFor n . cFor m
infixl 7 *:
--Exponentiation of m and n can be done by applying n to m
(^:) :: CNat -> CNat -> CNat
(^:) = \m n -> CNat $ cFor n (cFor m)
infixr 8 ^:
--Testing whether a value is 0 can be done through iteration
-- using a function constantly false and an initial value true
cIs0 :: CNat -> CBool
cIs0 = \n -> cFor n (\_ -> cFalse) cTrue
Predecessor ( evaluating to 0 for 0 ) can be defined iterating
over pairs , starting from an initial value ( 0 , 0 )
cPred :: CNat -> CNat
cPred = undefined
substraction from m n ( evaluating to 0 if m < n ) is repeated application
-- of the predeccesor function
(-:) :: CNat -> CNat -> CNat
(-:) = \m n -> cFor n cPred m
Transform a value into a CNat ( should yield c0 for nums < = 0 )
cNat :: (Ord p, Num p) => p -> CNat
cNat n = undefined
We can define an instance Num CNat which will allow us to see any
integer constant as a CNat ( e.g. 12 : : CNat ) and also use regular
-- arithmetic
instance Num CNat where
(+) = (+:)
(*) = (*:)
(-) = (-:)
abs = id
signum n = cIf (cIs0 n) 0 1
fromInteger = cNat
-- m is less than (or equal to) n if when substracting n from m we get 0
(<=:) :: CNat -> CNat -> CBool
(<=:) = undefined
infix 4 <=:
(>=:) :: CNat -> CNat -> CBool
(>=:) = \m n -> n <=: m
infix 4 >=:
(<:) :: CNat -> CNat -> CBool
(<:) = \m n -> cNot (m >=: n)
infix 4 <:
(>:) :: CNat -> CNat -> CBool
(>:) = \m n -> n <: m
infix 4 >:
-- equality on naturals can be defined my means of comparisons
(==:) :: CNat -> CNat -> CBool
(==:) = undefined
--Fun with arithmetic and pairs
--Define factorial. You can iterate over a pair to contain the current index and
cFactorial :: CNat -> CNat
cFactorial = \n -> cSnd $ cFor n (\p -> cPair (cFst p) (cFst p * cSnd p)) (cPair 1 1)
churchFibonacci :: Term
churchFibonacci = lam "n" (churchFst $$
(v "n"
$$ lam "p"
(churchPair
$$ (churchSnd $$ v "p")
$$ (churchPlus $$ (churchFst $$ v "p") $$ (churchSnd $$ v "p"))
)
$$ (churchPair $$ church0 $$ church1)
))
cFibonacci :: CNat -> CNat
cFibonacci = \n -> cFst $ cFor n (\p -> cPair (cSnd p) (cFst p + cSnd p)) (cPair 0 1)
churchDivMod :: Term
churchDivMod =
lams ["m", "n"]
(v "m"
$$ lam "pair"
(churchIf
$$ (churchLte $$ v "n" $$ (churchSnd $$ v "pair"))
$$ (churchPair
$$ (churchS $$ (churchFst $$ v "pair"))
$$ (churchSub
$$ (churchSnd $$ v "pair")
$$ v "n"
)
)
$$ v "pair"
)
$$ (churchPair $$ church0 $$ v "m")
)
cDivMod :: CNat -> CNat -> CPair CNat CNat
cDivMod = \m n -> cFor m (\p -> cIf (n <=: cSnd p) (cPair (cS (cFst p)) (cSnd p - n)) p) (cPair 0 m)
| null | https://raw.githubusercontent.com/theodormoroianu/SecondYearCourses/5e359e6a7cf588a527d27209bf53b4ce6b8d5e83/FLP/Laboratoare/Lab%209/.history/HaskellChurch_20210415162050.hs | haskell | # LANGUAGE RankNTypes #
The boolean negation switches the alternatives
The boolean conjunction can be built as a conditional
The boolean disjunction can be built as a conditional
a pair is a way to compute something based on the values
contained within the pair.
a function to be applied on the values, it will apply it on them.
A natural number is any way to iterate a function s a number of times
over an initial value z
An instance to show CNats as regular natural numbers
0 will iterate the function s 0 times over z, producing z
Successor n either
- iterates s n times over (s z)
Addition of m and n is done by iterating s n times over m
Multiplication of m and n can be done by composing n and m
Exponentiation of m and n can be done by applying n to m
Testing whether a value is 0 can be done through iteration
using a function constantly false and an initial value true
of the predeccesor function
arithmetic
m is less than (or equal to) n if when substracting n from m we get 0
equality on naturals can be defined my means of comparisons
Fun with arithmetic and pairs
Define factorial. You can iterate over a pair to contain the current index and | module HaskellChurch where
A boolean is any way to choose between two alternatives
newtype CBool = CBool {cIf :: forall t. t -> t -> t}
An instance to show as regular Booleans
instance Show CBool where
show b = show $ cIf b True False
The boolean constant true always chooses the first alternative
cTrue :: CBool
cTrue = undefined
The boolean constant false always chooses the second alternative
cFalse :: CBool
cFalse = undefined
cNot :: CBool -> CBool
cNot = undefined
(&&:) :: CBool -> CBool -> CBool
(&&:) = undefined
infixr 3 &&:
(||:) :: CBool -> CBool -> CBool
(||:) = undefined
infixr 2 ||:
newtype CPair a b = CPair { cOn :: forall c . (a -> b -> c) -> c }
An instance to show CPairs as regular pairs .
instance (Show a, Show b) => Show (CPair a b) where
show p = show $ cOn p (,)
builds a pair out of two values as an object which , when given
cPair :: a -> b -> CPair a b
cPair = undefined
first projection uses the function selecting first component on a pair
cFst :: CPair a b -> a
cFst = undefined
second projection
cSnd :: CPair a b -> b
cSnd = undefined
newtype CNat = CNat { cFor :: forall t. (t -> t) -> t -> t }
instance Show CNat where
show n = show $ cFor n (1 +) (0 :: Integer)
c0 :: CNat
c0 = undefined
1 is the the function s iterated 1 times over z , that is , z
c1 :: CNat
c1 = undefined
- applies s one more time in addition to what n does
cS :: CNat -> CNat
cS = undefined
(+:) :: CNat -> CNat -> CNat
(+:) = undefined
infixl 6 +:
(*:) :: CNat -> CNat -> CNat
(*:) = \n m -> CNat $ cFor n . cFor m
infixl 7 *:
(^:) :: CNat -> CNat -> CNat
(^:) = \m n -> CNat $ cFor n (cFor m)
infixr 8 ^:
cIs0 :: CNat -> CBool
cIs0 = \n -> cFor n (\_ -> cFalse) cTrue
Predecessor ( evaluating to 0 for 0 ) can be defined iterating
over pairs , starting from an initial value ( 0 , 0 )
cPred :: CNat -> CNat
cPred = undefined
substraction from m n ( evaluating to 0 if m < n ) is repeated application
(-:) :: CNat -> CNat -> CNat
(-:) = \m n -> cFor n cPred m
Transform a value into a CNat ( should yield c0 for nums < = 0 )
cNat :: (Ord p, Num p) => p -> CNat
cNat n = undefined
We can define an instance Num CNat which will allow us to see any
integer constant as a CNat ( e.g. 12 : : CNat ) and also use regular
instance Num CNat where
(+) = (+:)
(*) = (*:)
(-) = (-:)
abs = id
signum n = cIf (cIs0 n) 0 1
fromInteger = cNat
(<=:) :: CNat -> CNat -> CBool
(<=:) = undefined
infix 4 <=:
(>=:) :: CNat -> CNat -> CBool
(>=:) = \m n -> n <=: m
infix 4 >=:
(<:) :: CNat -> CNat -> CBool
(<:) = \m n -> cNot (m >=: n)
infix 4 <:
(>:) :: CNat -> CNat -> CBool
(>:) = \m n -> n <: m
infix 4 >:
(==:) :: CNat -> CNat -> CBool
(==:) = undefined
cFactorial :: CNat -> CNat
cFactorial = \n -> cSnd $ cFor n (\p -> cPair (cFst p) (cFst p * cSnd p)) (cPair 1 1)
churchFibonacci :: Term
churchFibonacci = lam "n" (churchFst $$
(v "n"
$$ lam "p"
(churchPair
$$ (churchSnd $$ v "p")
$$ (churchPlus $$ (churchFst $$ v "p") $$ (churchSnd $$ v "p"))
)
$$ (churchPair $$ church0 $$ church1)
))
cFibonacci :: CNat -> CNat
cFibonacci = \n -> cFst $ cFor n (\p -> cPair (cSnd p) (cFst p + cSnd p)) (cPair 0 1)
churchDivMod :: Term
churchDivMod =
lams ["m", "n"]
(v "m"
$$ lam "pair"
(churchIf
$$ (churchLte $$ v "n" $$ (churchSnd $$ v "pair"))
$$ (churchPair
$$ (churchS $$ (churchFst $$ v "pair"))
$$ (churchSub
$$ (churchSnd $$ v "pair")
$$ v "n"
)
)
$$ v "pair"
)
$$ (churchPair $$ church0 $$ v "m")
)
cDivMod :: CNat -> CNat -> CPair CNat CNat
cDivMod = \m n -> cFor m (\p -> cIf (n <=: cSnd p) (cPair (cS (cFst p)) (cSnd p - n)) p) (cPair 0 m)
|
b69f3d8150d66364c83e9e45a5bf2a73018359c1eaf4b3c3c2a0c5c9a8f605f9 | kompendium-ano/factom-haskell-client | FactoidBalance.hs | # LANGUAGE DeriveGeneric #
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
{-# LANGUAGE TypeOperators #-}
module Factom.RPC.Types.FactoidBalance where
import Control.Applicative
import Control.Monad (forM_, join, mzero)
import Data.Aeson (FromJSON (..), ToJSON (..),
Value (..), decode, object,
pairs, (.:), (.:?), (.=))
import Data.Aeson.AutoType.Alternative
import qualified Data.ByteString.Lazy.Char8 as BSL
import Data.Monoid
import Data.Text (Text)
import qualified GHC.Generics
import System.Environment (getArgs)
import System.Exit (exitFailure, exitSuccess)
import System.IO (hPutStrLn, stderr)
--------------------------------------------------------------------------------
| Workaround for .
o .:?? val = fmap join (o .:? val)
data TopLevel =
TopLevel
{ topLevelBalance :: Double
}
deriving (Show, Eq, GHC.Generics.Generic)
instance FromJSON TopLevel where
parseJSON (Object v) = TopLevel <$> v .: "balance"
parseJSON _ = mzero
instance ToJSON TopLevel where
toJSON (TopLevel {..}) = object ["balance" .= topLevelBalance]
toEncoding (TopLevel {..}) = pairs ("balance" .= topLevelBalance)
| null | https://raw.githubusercontent.com/kompendium-ano/factom-haskell-client/87a73bb9079859f6223f8259da0dc9da568d1233/src/Factom/RPC/Types/FactoidBalance.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE RecordWildCards #
# LANGUAGE TypeOperators #
------------------------------------------------------------------------------ | # LANGUAGE DeriveGeneric #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
module Factom.RPC.Types.FactoidBalance where
import Control.Applicative
import Control.Monad (forM_, join, mzero)
import Data.Aeson (FromJSON (..), ToJSON (..),
Value (..), decode, object,
pairs, (.:), (.:?), (.=))
import Data.Aeson.AutoType.Alternative
import qualified Data.ByteString.Lazy.Char8 as BSL
import Data.Monoid
import Data.Text (Text)
import qualified GHC.Generics
import System.Environment (getArgs)
import System.Exit (exitFailure, exitSuccess)
import System.IO (hPutStrLn, stderr)
| Workaround for .
o .:?? val = fmap join (o .:? val)
data TopLevel =
TopLevel
{ topLevelBalance :: Double
}
deriving (Show, Eq, GHC.Generics.Generic)
instance FromJSON TopLevel where
parseJSON (Object v) = TopLevel <$> v .: "balance"
parseJSON _ = mzero
instance ToJSON TopLevel where
toJSON (TopLevel {..}) = object ["balance" .= topLevelBalance]
toEncoding (TopLevel {..}) = pairs ("balance" .= topLevelBalance)
|
4fbc8d5a8a78b897c27962f793b74e7e94ee97cc9f7ef79266d1c61c79e11514 | FranklinChen/learn-you-some-erlang | ppool_serv.erl | -module(ppool_serv).
-behaviour(gen_server).
-export([start/4, start_link/4, run/2, sync_queue/2, async_queue/2, stop/1]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
code_change/3, terminate/2]).
%% The friendly supervisor is started dynamically!
-define(SPEC(MFA),
{worker_sup,
{ppool_worker_sup, start_link, [MFA]},
temporary,
10000,
supervisor,
[ppool_worker_sup]}).
-record(state, {limit=0,
sup,
refs,
queue=queue:new()}).
start(Name, Limit, Sup, MFA) when is_atom(Name), is_integer(Limit) ->
gen_server:start({local, Name}, ?MODULE, {Limit, MFA, Sup}, []).
start_link(Name, Limit, Sup, MFA) when is_atom(Name), is_integer(Limit) ->
gen_server:start_link({local, Name}, ?MODULE, {Limit, MFA, Sup}, []).
run(Name, Args) ->
gen_server:call(Name, {run, Args}).
sync_queue(Name, Args) ->
gen_server:call(Name, {sync, Args}, infinity).
async_queue(Name, Args) ->
gen_server:cast(Name, {async, Args}).
stop(Name) ->
gen_server:call(Name, stop).
%% Gen server
init({Limit, MFA, Sup}) ->
We need to find the Pid of the worker supervisor from here ,
%% but alas, this would be calling the supervisor while it waits for us!
self() ! {start_worker_supervisor, Sup, MFA},
{ok, #state{limit=Limit, refs=gb_sets:empty()}}.
handle_call({run, Args}, _From, S = #state{limit=N, sup=Sup, refs=R}) when N > 0 ->
{ok, Pid} = supervisor:start_child(Sup, Args),
Ref = erlang:monitor(process, Pid),
{reply, {ok,Pid}, S#state{limit=N-1, refs=gb_sets:add(Ref,R)}};
handle_call({run, _Args}, _From, S=#state{limit=N}) when N =< 0 ->
{reply, noalloc, S};
handle_call({sync, Args}, _From, S = #state{limit=N, sup=Sup, refs=R}) when N > 0 ->
{ok, Pid} = supervisor:start_child(Sup, Args),
Ref = erlang:monitor(process, Pid),
{reply, {ok,Pid}, S#state{limit=N-1, refs=gb_sets:add(Ref,R)}};
handle_call({sync, Args}, From, S = #state{queue=Q}) ->
{noreply, S#state{queue=queue:in({From, Args}, Q)}};
handle_call(stop, _From, State) ->
{stop, normal, ok, State};
handle_call(_Msg, _From, State) ->
{noreply, State}.
handle_cast({async, Args}, S=#state{limit=N, sup=Sup, refs=R}) when N > 0 ->
{ok, Pid} = supervisor:start_child(Sup, Args),
Ref = erlang:monitor(process, Pid),
{noreply, S#state{limit=N-1, refs=gb_sets:add(Ref,R)}};
handle_cast({async, Args}, S=#state{limit=N, queue=Q}) when N =< 0 ->
{noreply, S#state{queue=queue:in(Args,Q)}};
handle_cast(_Msg, State) ->
{noreply, State}.
handle_info({'DOWN', Ref, process, _Pid, _}, S = #state{refs=Refs}) ->
case gb_sets:is_element(Ref, Refs) of
true ->
handle_down_worker(Ref, S);
false -> %% Not our responsibility
{noreply, S}
end;
handle_info({start_worker_supervisor, Sup, MFA}, S = #state{}) ->
{ok, Pid} = supervisor:start_child(Sup, ?SPEC(MFA)),
link(Pid),
{noreply, S#state{sup=Pid}};
handle_info(Msg, State) ->
io:format("Unknown msg: ~p~n", [Msg]),
{noreply, State}.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
terminate(_Reason, _State) ->
ok.
handle_down_worker(Ref, S = #state{limit=L, sup=Sup, refs=Refs}) ->
case queue:out(S#state.queue) of
{{value, {From, Args}}, Q} ->
{ok, Pid} = supervisor:start_child(Sup, Args),
NewRef = erlang:monitor(process, Pid),
NewRefs = gb_sets:insert(NewRef, gb_sets:delete(Ref,Refs)),
gen_server:reply(From, {ok, Pid}),
{noreply, S#state{refs=NewRefs, queue=Q}};
{{value, Args}, Q} ->
{ok, Pid} = supervisor:start_child(Sup, Args),
NewRef = erlang:monitor(process, Pid),
NewRefs = gb_sets:insert(NewRef, gb_sets:delete(Ref,Refs)),
{noreply, S#state{refs=NewRefs, queue=Q}};
{empty, _} ->
{noreply, S#state{limit=L+1, refs=gb_sets:delete(Ref,Refs)}}
end.
| null | https://raw.githubusercontent.com/FranklinChen/learn-you-some-erlang/878c8bc2011a12862fe72dd7fdc6c921348c79d6/ppool-1.0/src/ppool_serv.erl | erlang | The friendly supervisor is started dynamically!
Gen server
but alas, this would be calling the supervisor while it waits for us!
Not our responsibility | -module(ppool_serv).
-behaviour(gen_server).
-export([start/4, start_link/4, run/2, sync_queue/2, async_queue/2, stop/1]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
code_change/3, terminate/2]).
-define(SPEC(MFA),
{worker_sup,
{ppool_worker_sup, start_link, [MFA]},
temporary,
10000,
supervisor,
[ppool_worker_sup]}).
-record(state, {limit=0,
sup,
refs,
queue=queue:new()}).
start(Name, Limit, Sup, MFA) when is_atom(Name), is_integer(Limit) ->
gen_server:start({local, Name}, ?MODULE, {Limit, MFA, Sup}, []).
start_link(Name, Limit, Sup, MFA) when is_atom(Name), is_integer(Limit) ->
gen_server:start_link({local, Name}, ?MODULE, {Limit, MFA, Sup}, []).
run(Name, Args) ->
gen_server:call(Name, {run, Args}).
sync_queue(Name, Args) ->
gen_server:call(Name, {sync, Args}, infinity).
async_queue(Name, Args) ->
gen_server:cast(Name, {async, Args}).
stop(Name) ->
gen_server:call(Name, stop).
init({Limit, MFA, Sup}) ->
We need to find the Pid of the worker supervisor from here ,
self() ! {start_worker_supervisor, Sup, MFA},
{ok, #state{limit=Limit, refs=gb_sets:empty()}}.
handle_call({run, Args}, _From, S = #state{limit=N, sup=Sup, refs=R}) when N > 0 ->
{ok, Pid} = supervisor:start_child(Sup, Args),
Ref = erlang:monitor(process, Pid),
{reply, {ok,Pid}, S#state{limit=N-1, refs=gb_sets:add(Ref,R)}};
handle_call({run, _Args}, _From, S=#state{limit=N}) when N =< 0 ->
{reply, noalloc, S};
handle_call({sync, Args}, _From, S = #state{limit=N, sup=Sup, refs=R}) when N > 0 ->
{ok, Pid} = supervisor:start_child(Sup, Args),
Ref = erlang:monitor(process, Pid),
{reply, {ok,Pid}, S#state{limit=N-1, refs=gb_sets:add(Ref,R)}};
handle_call({sync, Args}, From, S = #state{queue=Q}) ->
{noreply, S#state{queue=queue:in({From, Args}, Q)}};
handle_call(stop, _From, State) ->
{stop, normal, ok, State};
handle_call(_Msg, _From, State) ->
{noreply, State}.
handle_cast({async, Args}, S=#state{limit=N, sup=Sup, refs=R}) when N > 0 ->
{ok, Pid} = supervisor:start_child(Sup, Args),
Ref = erlang:monitor(process, Pid),
{noreply, S#state{limit=N-1, refs=gb_sets:add(Ref,R)}};
handle_cast({async, Args}, S=#state{limit=N, queue=Q}) when N =< 0 ->
{noreply, S#state{queue=queue:in(Args,Q)}};
handle_cast(_Msg, State) ->
{noreply, State}.
handle_info({'DOWN', Ref, process, _Pid, _}, S = #state{refs=Refs}) ->
case gb_sets:is_element(Ref, Refs) of
true ->
handle_down_worker(Ref, S);
{noreply, S}
end;
handle_info({start_worker_supervisor, Sup, MFA}, S = #state{}) ->
{ok, Pid} = supervisor:start_child(Sup, ?SPEC(MFA)),
link(Pid),
{noreply, S#state{sup=Pid}};
handle_info(Msg, State) ->
io:format("Unknown msg: ~p~n", [Msg]),
{noreply, State}.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
terminate(_Reason, _State) ->
ok.
handle_down_worker(Ref, S = #state{limit=L, sup=Sup, refs=Refs}) ->
case queue:out(S#state.queue) of
{{value, {From, Args}}, Q} ->
{ok, Pid} = supervisor:start_child(Sup, Args),
NewRef = erlang:monitor(process, Pid),
NewRefs = gb_sets:insert(NewRef, gb_sets:delete(Ref,Refs)),
gen_server:reply(From, {ok, Pid}),
{noreply, S#state{refs=NewRefs, queue=Q}};
{{value, Args}, Q} ->
{ok, Pid} = supervisor:start_child(Sup, Args),
NewRef = erlang:monitor(process, Pid),
NewRefs = gb_sets:insert(NewRef, gb_sets:delete(Ref,Refs)),
{noreply, S#state{refs=NewRefs, queue=Q}};
{empty, _} ->
{noreply, S#state{limit=L+1, refs=gb_sets:delete(Ref,Refs)}}
end.
|
aea7308cb7ef66e38535abb61988c9647cc3cc205ccae8eaccd990ee6f5e12cf | gedge-platform/gedge-platform | rabbit_mgmt_reset_handler.erl | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
%%
Copyright ( c ) 2007 - 2021 VMware , Inc. or its affiliates . All rights reserved .
%%
%% When management extensions are enabled and/or disabled at runtime, the
%% management web dispatch mechanism needs to be reset. This event handler
%% deals with responding to 'plugins_changed' events for management
%% extensions, forcing a reset when necessary.
-module(rabbit_mgmt_reset_handler).
-include_lib("rabbit_common/include/rabbit.hrl").
-behaviour(gen_event).
-export([init/1, handle_call/2, handle_event/2, handle_info/2,
terminate/2, code_change/3]).
-rabbit_boot_step({?MODULE,
[{description, "management extension handling"},
{mfa, {gen_event, add_handler,
[rabbit_event, ?MODULE, []]}},
{cleanup, {gen_event, delete_handler,
[rabbit_event, ?MODULE, []]}},
{requires, rabbit_event},
{enables, recovery}]}).
-import(rabbit_misc, [pget/2, pget/3]).
%%----------------------------------------------------------------------------
init([]) ->
{ok, []}.
handle_call(_Request, State) ->
{ok, not_understood, State}.
handle_event(#event{type = plugins_changed, props = Details}, State) ->
Enabled = pget(enabled, Details),
Disabled = pget(disabled, Details),
case extensions_changed(Enabled ++ Disabled) of
true ->
_ = rabbit_mgmt_app:reset_dispatcher(Disabled),
ok;
false -> ok
end,
{ok, State};
handle_event(_Event, State) ->
{ok, State}.
handle_info(_Info, State) ->
{ok, State}.
terminate(_Arg, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%%----------------------------------------------------------------------------
%% We explicitly ignore the case where management has been
%% started/stopped since the dispatcher is either freshly created or
%% about to vanish.
extensions_changed(Apps) ->
not lists:member(rabbitmq_management, Apps) andalso
lists:any(fun is_extension/1, [Mod || App <- Apps, Mod <- mods(App)]).
is_extension(Mod) ->
lists:member(rabbit_mgmt_extension,
pget(behaviour, Mod:module_info(attributes), [])).
mods(App) ->
{ok, Modules} = application:get_key(App, modules),
Modules.
| null | https://raw.githubusercontent.com/gedge-platform/gedge-platform/97c1e87faf28ba2942a77196b6be0a952bff1c3e/gs-broker/broker-server/deps/rabbitmq_management/src/rabbit_mgmt_reset_handler.erl | erlang |
When management extensions are enabled and/or disabled at runtime, the
management web dispatch mechanism needs to be reset. This event handler
deals with responding to 'plugins_changed' events for management
extensions, forcing a reset when necessary.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
We explicitly ignore the case where management has been
started/stopped since the dispatcher is either freshly created or
about to vanish. | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
Copyright ( c ) 2007 - 2021 VMware , Inc. or its affiliates . All rights reserved .
-module(rabbit_mgmt_reset_handler).
-include_lib("rabbit_common/include/rabbit.hrl").
-behaviour(gen_event).
-export([init/1, handle_call/2, handle_event/2, handle_info/2,
terminate/2, code_change/3]).
-rabbit_boot_step({?MODULE,
[{description, "management extension handling"},
{mfa, {gen_event, add_handler,
[rabbit_event, ?MODULE, []]}},
{cleanup, {gen_event, delete_handler,
[rabbit_event, ?MODULE, []]}},
{requires, rabbit_event},
{enables, recovery}]}).
-import(rabbit_misc, [pget/2, pget/3]).
init([]) ->
{ok, []}.
handle_call(_Request, State) ->
{ok, not_understood, State}.
handle_event(#event{type = plugins_changed, props = Details}, State) ->
Enabled = pget(enabled, Details),
Disabled = pget(disabled, Details),
case extensions_changed(Enabled ++ Disabled) of
true ->
_ = rabbit_mgmt_app:reset_dispatcher(Disabled),
ok;
false -> ok
end,
{ok, State};
handle_event(_Event, State) ->
{ok, State}.
handle_info(_Info, State) ->
{ok, State}.
terminate(_Arg, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
extensions_changed(Apps) ->
not lists:member(rabbitmq_management, Apps) andalso
lists:any(fun is_extension/1, [Mod || App <- Apps, Mod <- mods(App)]).
is_extension(Mod) ->
lists:member(rabbit_mgmt_extension,
pget(behaviour, Mod:module_info(attributes), [])).
mods(App) ->
{ok, Modules} = application:get_key(App, modules),
Modules.
|
59b62a126b54dddec82bb7ae893bf50200ed7905d1b9bba83aa752938e5033a0 | weavejester/inquest | core.clj | (ns inquest.core
"Functions to add monitoring to existing vars."
(:require [medley.core :refer [dissoc-in]]))
(def ^:private reporters (atom {}))
(defn- make-report [key map]
(into {:time (System/nanoTime)
:thread (.getId (Thread/currentThread))
:key key}
map))
(defn- dispatch! [reporters report]
(doseq [r reporters] (r report)))
(defn monitor
"Takes a function and a unique key, and returns a new function that will
report on its operation. A report is a map that contains the following
keys:
:time - the system time in nanoseconds
:thread - the thread ID
:target - the target being monitored
:state - one of :enter, :exit or :throw
Additionally there may be the following optional keys:
:args - the arguments passed to the var (only in the :enter state)
:return - the return value from the var (only in the :exit state)
:exception - the thrown exception (only in the :throw state)
Reports are sent to reporters that can be registered with the monitor key
using add-reporter."
[func key]
(with-meta
(fn [& args]
(if-let [rs (vals (@reporters key))]
(do (dispatch! rs (make-report key {:state :enter, :args args}))
(try
(let [ret (apply func args)]
(dispatch! rs (make-report key {:state :exit, :return ret}))
ret)
(catch Throwable th
(dispatch! rs (make-report key {:state :throw, :exception th}))
(throw th))))
(apply func args)))
{::original func
::key key}))
(defn unmonitor
"Remove monitoring from a function."
[func]
(-> func meta ::original (or func)))
(defn add-reporter
"Add a reporter function to the function associated with monitor-key. The
reporter-key should be unique to the reporter."
[monitor-key reporter-key reporter]
(swap! reporters assoc-in [monitor-key reporter-key] reporter))
(defn remove-reporter
"Remove a reporter function identified by reporter-key, from the function
associated with monitor-key."
[monitor-key reporter-key]
(swap! reporters dissoc-in [monitor-key reporter-key]))
(defn inquest
"A convenience function for monitoring many vars with the same reporter
function. The return value is a zero-argument function that, when called,
will remove all of the monitoring added for the inquest.
See the monitor function for an explanation of the reporter function."
[vars reporter]
(let [key (gensym "inquest-")]
(doseq [v vars]
(alter-var-root v monitor v)
(add-reporter v key reporter))
(fn []
(swap! reporters dissoc key)
(doseq [v vars]
(alter-var-root v unmonitor)))))
| null | https://raw.githubusercontent.com/weavejester/inquest/74955b7213dccdb5cf99390f80bbd5879cb770c1/src/inquest/core.clj | clojure | (ns inquest.core
"Functions to add monitoring to existing vars."
(:require [medley.core :refer [dissoc-in]]))
(def ^:private reporters (atom {}))
(defn- make-report [key map]
(into {:time (System/nanoTime)
:thread (.getId (Thread/currentThread))
:key key}
map))
(defn- dispatch! [reporters report]
(doseq [r reporters] (r report)))
(defn monitor
"Takes a function and a unique key, and returns a new function that will
report on its operation. A report is a map that contains the following
keys:
:time - the system time in nanoseconds
:thread - the thread ID
:target - the target being monitored
:state - one of :enter, :exit or :throw
Additionally there may be the following optional keys:
:args - the arguments passed to the var (only in the :enter state)
:return - the return value from the var (only in the :exit state)
:exception - the thrown exception (only in the :throw state)
Reports are sent to reporters that can be registered with the monitor key
using add-reporter."
[func key]
(with-meta
(fn [& args]
(if-let [rs (vals (@reporters key))]
(do (dispatch! rs (make-report key {:state :enter, :args args}))
(try
(let [ret (apply func args)]
(dispatch! rs (make-report key {:state :exit, :return ret}))
ret)
(catch Throwable th
(dispatch! rs (make-report key {:state :throw, :exception th}))
(throw th))))
(apply func args)))
{::original func
::key key}))
(defn unmonitor
"Remove monitoring from a function."
[func]
(-> func meta ::original (or func)))
(defn add-reporter
"Add a reporter function to the function associated with monitor-key. The
reporter-key should be unique to the reporter."
[monitor-key reporter-key reporter]
(swap! reporters assoc-in [monitor-key reporter-key] reporter))
(defn remove-reporter
"Remove a reporter function identified by reporter-key, from the function
associated with monitor-key."
[monitor-key reporter-key]
(swap! reporters dissoc-in [monitor-key reporter-key]))
(defn inquest
"A convenience function for monitoring many vars with the same reporter
function. The return value is a zero-argument function that, when called,
will remove all of the monitoring added for the inquest.
See the monitor function for an explanation of the reporter function."
[vars reporter]
(let [key (gensym "inquest-")]
(doseq [v vars]
(alter-var-root v monitor v)
(add-reporter v key reporter))
(fn []
(swap! reporters dissoc key)
(doseq [v vars]
(alter-var-root v unmonitor)))))
| |
9b93c8f6a01ef508cbd210781d310ca62424a188ae8b286d1e0edb61c8efa0a0 | typedclojure/typedclojure | hset_utils.clj | Copyright ( c ) , contributors .
;; The use and distribution terms for this software are covered by the
;; Eclipse Public License 1.0 (-1.0.php)
;; which can be found in the file epl-v10.html at the root of this distribution.
;; By using this software in any fashion, you are agreeing to be bound by
;; the terms of this license.
;; You must not remove this notice, or any other, from this software.
(ns typed.cljc.checker.hset-utils)
(def valid-fixed? (some-fn string? symbol? keyword? nil? number?
char? boolean?))
| null | https://raw.githubusercontent.com/typedclojure/typedclojure/45556897356f3c9cbc7b1b6b4df263086a9d5803/typed/clj.checker/src/typed/cljc/checker/hset_utils.clj | clojure | The use and distribution terms for this software are covered by the
Eclipse Public License 1.0 (-1.0.php)
which can be found in the file epl-v10.html at the root of this distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software. | Copyright ( c ) , contributors .
(ns typed.cljc.checker.hset-utils)
(def valid-fixed? (some-fn string? symbol? keyword? nil? number?
char? boolean?))
|
61ad73bdb1dcecc93f6502c1ed1930c9f7ae9a10675bde0fde15cf49226dcf89 | grin-compiler/ghc-wpc-sample-programs | Ops.hs | |
Module : . . Ops
Description : Parser for operators and fixity declarations .
License : : The Idris Community .
Module : Idris.Parser.Ops
Description : Parser for operators and fixity declarations.
License : BSD3
Maintainer : The Idris Community.
-}
# LANGUAGE ConstraintKinds , FlexibleContexts , GeneralizedNewtypeDeriving ,
MultiParamTypeClasses , PatternGuards #
MultiParamTypeClasses, PatternGuards #-}
module Idris.Parser.Ops where
import Idris.AbsSyntax
import Idris.Core.TT
import Idris.Parser.Helpers
import Prelude hiding (pi)
import Control.Applicative
import Control.Monad
import qualified Control.Monad.Combinators.Expr as P
import Control.Monad.State.Strict
import Data.Char (isAlpha)
import Data.List
import Data.List.NonEmpty (fromList)
import Text.Megaparsec ((<?>))
import qualified Text.Megaparsec as P
-- | Creates table for fixity declarations to build expression parser
-- using pre-build and user-defined operator/fixity declarations
table :: [FixDecl] -> [[P.Operator IdrisParser PTerm]]
table fixes
= [[prefix "-" negateExpr]] ++
toTable (reverse fixes) ++
[[noFixityBacktickOperator],
[binary "$" P.InfixR $ \fc _ x y -> flatten $ PApp fc x [pexp y]],
[binary "=" P.InfixL $ \fc _ x y -> PApp fc (PRef fc [fc] eqTy) [pexp x, pexp y]],
[noFixityOperator]]
where
negateExpr :: FC -> PTerm -> PTerm
negateExpr _ (PConstant fc (I int)) = PConstant fc $ I $ negate int
negateExpr _ (PConstant fc (BI bigInt)) = PConstant fc $ BI $ negate bigInt
negateExpr _ (PConstant fc (Fl dbl)) = PConstant fc $ Fl $ negate dbl
negateExpr _ (PConstSugar fc term) = negateExpr fc term
negateExpr fc (PAlternative ns tp terms) = PAlternative ns tp $ map (negateExpr fc) terms
negateExpr fc x = PApp fc (PRef fc [fc] (sUN "negate")) [pexp x]
flatten :: PTerm -> PTerm -- flatten application
flatten (PApp fc (PApp _ f as) bs) = flatten (PApp fc f (as ++ bs))
flatten t = t
noFixityBacktickOperator :: P.Operator IdrisParser PTerm
noFixityBacktickOperator = P.InfixN $ do
(n, fc) <- withExtent backtickOperator
return $ \x y -> PApp fc (PRef fc [fc] n) [pexp x, pexp y]
-- | Operator without fixity (throws an error)
noFixityOperator :: P.Operator IdrisParser PTerm
noFixityOperator = P.InfixN $ do
indentGt
op <- P.try symbolicOperator
P.unexpected . P.Label . fromList $ "Operator without known fixity: " ++ op
-- | Calculates table for fixity declarations
toTable :: [FixDecl] -> [[P.Operator IdrisParser PTerm]]
toTable fs = map (map toBin) (groupBy (\ (Fix x _) (Fix y _) -> prec x == prec y) fs)
toBin (Fix (PrefixN _) op) = prefix op $ \fc x ->
PApp fc (PRef fc [] (sUN op)) [pexp x]
toBin (Fix f op) = binary op (assoc f) $ \fc n x y ->
PApp fc (PRef fc [] n) [pexp x,pexp y]
assoc (Infixl _) = P.InfixL
assoc (Infixr _) = P.InfixR
assoc (InfixN _) = P.InfixN
isBacktick :: String -> Bool
isBacktick (c : _) = c == '_' || isAlpha c
isBacktick _ = False
binary :: String -> (IdrisParser (PTerm -> PTerm -> PTerm) -> P.Operator IdrisParser PTerm) -> (FC -> Name -> PTerm -> PTerm -> PTerm) -> P.Operator IdrisParser PTerm
binary name ctor f
| isBacktick name = ctor $ P.try $ do
(n, fc) <- withExtent backtickOperator
guard $ show (nsroot n) == name
return $ f fc n
| otherwise = ctor $ do
indentGt
fc <- extent $ reservedOp name
indentGt
return $ f fc (sUN name)
prefix :: String -> (FC -> PTerm -> PTerm) -> P.Operator IdrisParser PTerm
prefix name f = P.Prefix $ do
fc <- extent $ reservedOp name
indentGt
return (f fc)
{- | Parses a function used as an operator -- enclosed in backticks
@
BacktickOperator ::=
'`' Name '`'
;
@
-}
backtickOperator :: (Parsing m, MonadState IState m) => m Name
backtickOperator = P.between (indentGt *> lchar '`') (indentGt *> lchar '`') name
| Parses an operator name ( either a symbolic name or a backtick - quoted name )
@
OperatorName : : =
SymbolicOperator
| BacktickOperator
;
@
@
OperatorName ::=
SymbolicOperator
| BacktickOperator
;
@
-}
operatorName :: (Parsing m, MonadState IState m) => m Name
operatorName = sUN <$> symbolicOperator
<|> backtickOperator
{- | Parses an operator in function position i.e. enclosed by `()', with an
optional namespace
@
OperatorFront ::=
'(' '=' ')'
| (Identifier_t '.')? '(' Operator_t ')'
;
@
-}
operatorFront :: Parsing m => m Name
operatorFront = do P.try $ lchar '(' *> (eqTy <$ reservedOp "=") <* lchar ')'
<|> maybeWithNS (lchar '(' *> symbolicOperator <* lchar ')') []
| Parses a function ( either normal name or operator )
@
FnName : : = Name | OperatorFront ;
@
@
FnName ::= Name | OperatorFront;
@
-}
fnName :: (Parsing m, MonadState IState m) => m Name
fnName = P.try operatorFront <|> name <?> "function name"
| Parses a fixity declaration
@
Fixity : : =
FixityType Natural_t OperatorList ;
@
@
Fixity ::=
FixityType Natural_t OperatorList Terminator
;
@
-}
fixity :: IdrisParser PDecl
fixity = do ((f, i, ops), fc) <- withExtent $ do
pushIndent
f <- fixityType; i <- natural
ops <- P.sepBy1 (show . nsroot <$> operatorName) (lchar ',')
terminator
return (f, i, ops)
let prec = fromInteger i
istate <- get
let infixes = idris_infixes istate
let fs = map (Fix (f prec)) ops
let redecls = map (alreadyDeclared infixes) fs
let ill = filter (not . checkValidity) redecls
if null ill
then do put (istate { idris_infixes = nub $ sort (fs ++ infixes)
, ibc_write = map IBCFix fs ++ ibc_write istate
})
return (PFix fc (f prec) ops)
else fail $ concatMap (\(f, (x:xs)) -> "Illegal redeclaration of fixity:\n\t\""
++ show f ++ "\" overrides \"" ++ show x ++ "\"") ill
<?> "fixity declaration"
where
alreadyDeclared :: [FixDecl] -> FixDecl -> (FixDecl, [FixDecl])
alreadyDeclared fs f = (f, filter ((extractName f ==) . extractName) fs)
checkValidity :: (FixDecl, [FixDecl]) -> Bool
checkValidity (f, fs) = all (== f) fs
extractName :: FixDecl -> String
extractName (Fix _ n) = n
-- | Check that a declaration of an operator also has fixity declared
checkDeclFixity :: IdrisParser PDecl -> IdrisParser PDecl
checkDeclFixity p = do decl <- p
case getDeclName decl of
Nothing -> return decl
Just n -> do checkNameFixity n
return decl
where getDeclName (PTy _ _ _ _ _ n _ _ ) = Just n
getDeclName (PData _ _ _ _ _ (PDatadecl n _ _ _)) = Just n
getDeclName _ = Nothing
-- | Checks that an operator name also has a fixity declaration
checkNameFixity :: Name -> IdrisParser ()
checkNameFixity n = do fOk <- fixityOk n
unless fOk . fail $
"Missing fixity declaration for " ++ show n
where fixityOk (NS n' _) = fixityOk n'
fixityOk (UN n') | all (flip elem opChars) (str n') =
do fixities <- fmap idris_infixes get
return . elem (str n') . map (\ (Fix _ op) -> op) $ fixities
| otherwise = return True
fixityOk _ = return True
| Parses a fixity declaration type ( i.e. infix or prefix , associtavity )
@
FixityType : : =
' infixl '
| ' infixr '
| ' infix '
| ' prefix '
;
@
@
FixityType ::=
'infixl'
| 'infixr'
| 'infix'
| 'prefix'
;
@
-}
fixityType :: IdrisParser (Int -> Fixity)
fixityType = do reserved "infixl"; return Infixl
<|> do reserved "infixr"; return Infixr
<|> do reserved "infix"; return InfixN
<|> do reserved "prefix"; return PrefixN
<?> "fixity type"
opChars :: String
opChars = ":!#$%&*+./<=>?@\\^|-~"
operatorLetter :: Parsing m => m Char
operatorLetter = P.oneOf opChars
commentMarkers :: [String]
commentMarkers = [ "--", "|||" ]
invalidOperators :: [String]
invalidOperators = [":", "=>", "->", "<-", "=", "?=", "|", "**", "==>", "\\", "%", "~", "?", "!", "@"]
-- | Parses an operator
symbolicOperator :: Parsing m => m String
symbolicOperator = do op <- token . some $ operatorLetter
when (op `elem` (invalidOperators ++ commentMarkers)) $
fail $ op ++ " is not a valid operator"
return op
Taken from Parsec ( c ) 1999 - 2001 , ( c ) 2007
-- | Parses a reserved operator
reservedOp :: Parsing m => String -> m ()
reservedOp name = token $ P.try $
do string name
P.notFollowedBy operatorLetter <?> ("end of " ++ show name)
| null | https://raw.githubusercontent.com/grin-compiler/ghc-wpc-sample-programs/0e3a9b8b7cc3fa0da7c77fb7588dd4830fb087f7/idris-1.3.3/src/Idris/Parser/Ops.hs | haskell | | Creates table for fixity declarations to build expression parser
using pre-build and user-defined operator/fixity declarations
flatten application
| Operator without fixity (throws an error)
| Calculates table for fixity declarations
| Parses a function used as an operator -- enclosed in backticks
@
BacktickOperator ::=
'`' Name '`'
;
@
| Parses an operator in function position i.e. enclosed by `()', with an
optional namespace
@
OperatorFront ::=
'(' '=' ')'
| (Identifier_t '.')? '(' Operator_t ')'
;
@
| Check that a declaration of an operator also has fixity declared
| Checks that an operator name also has a fixity declaration
| Parses an operator
| Parses a reserved operator | |
Module : . . Ops
Description : Parser for operators and fixity declarations .
License : : The Idris Community .
Module : Idris.Parser.Ops
Description : Parser for operators and fixity declarations.
License : BSD3
Maintainer : The Idris Community.
-}
# LANGUAGE ConstraintKinds , FlexibleContexts , GeneralizedNewtypeDeriving ,
MultiParamTypeClasses , PatternGuards #
MultiParamTypeClasses, PatternGuards #-}
module Idris.Parser.Ops where
import Idris.AbsSyntax
import Idris.Core.TT
import Idris.Parser.Helpers
import Prelude hiding (pi)
import Control.Applicative
import Control.Monad
import qualified Control.Monad.Combinators.Expr as P
import Control.Monad.State.Strict
import Data.Char (isAlpha)
import Data.List
import Data.List.NonEmpty (fromList)
import Text.Megaparsec ((<?>))
import qualified Text.Megaparsec as P
table :: [FixDecl] -> [[P.Operator IdrisParser PTerm]]
table fixes
= [[prefix "-" negateExpr]] ++
toTable (reverse fixes) ++
[[noFixityBacktickOperator],
[binary "$" P.InfixR $ \fc _ x y -> flatten $ PApp fc x [pexp y]],
[binary "=" P.InfixL $ \fc _ x y -> PApp fc (PRef fc [fc] eqTy) [pexp x, pexp y]],
[noFixityOperator]]
where
negateExpr :: FC -> PTerm -> PTerm
negateExpr _ (PConstant fc (I int)) = PConstant fc $ I $ negate int
negateExpr _ (PConstant fc (BI bigInt)) = PConstant fc $ BI $ negate bigInt
negateExpr _ (PConstant fc (Fl dbl)) = PConstant fc $ Fl $ negate dbl
negateExpr _ (PConstSugar fc term) = negateExpr fc term
negateExpr fc (PAlternative ns tp terms) = PAlternative ns tp $ map (negateExpr fc) terms
negateExpr fc x = PApp fc (PRef fc [fc] (sUN "negate")) [pexp x]
flatten (PApp fc (PApp _ f as) bs) = flatten (PApp fc f (as ++ bs))
flatten t = t
noFixityBacktickOperator :: P.Operator IdrisParser PTerm
noFixityBacktickOperator = P.InfixN $ do
(n, fc) <- withExtent backtickOperator
return $ \x y -> PApp fc (PRef fc [fc] n) [pexp x, pexp y]
noFixityOperator :: P.Operator IdrisParser PTerm
noFixityOperator = P.InfixN $ do
indentGt
op <- P.try symbolicOperator
P.unexpected . P.Label . fromList $ "Operator without known fixity: " ++ op
toTable :: [FixDecl] -> [[P.Operator IdrisParser PTerm]]
toTable fs = map (map toBin) (groupBy (\ (Fix x _) (Fix y _) -> prec x == prec y) fs)
toBin (Fix (PrefixN _) op) = prefix op $ \fc x ->
PApp fc (PRef fc [] (sUN op)) [pexp x]
toBin (Fix f op) = binary op (assoc f) $ \fc n x y ->
PApp fc (PRef fc [] n) [pexp x,pexp y]
assoc (Infixl _) = P.InfixL
assoc (Infixr _) = P.InfixR
assoc (InfixN _) = P.InfixN
isBacktick :: String -> Bool
isBacktick (c : _) = c == '_' || isAlpha c
isBacktick _ = False
binary :: String -> (IdrisParser (PTerm -> PTerm -> PTerm) -> P.Operator IdrisParser PTerm) -> (FC -> Name -> PTerm -> PTerm -> PTerm) -> P.Operator IdrisParser PTerm
binary name ctor f
| isBacktick name = ctor $ P.try $ do
(n, fc) <- withExtent backtickOperator
guard $ show (nsroot n) == name
return $ f fc n
| otherwise = ctor $ do
indentGt
fc <- extent $ reservedOp name
indentGt
return $ f fc (sUN name)
prefix :: String -> (FC -> PTerm -> PTerm) -> P.Operator IdrisParser PTerm
prefix name f = P.Prefix $ do
fc <- extent $ reservedOp name
indentGt
return (f fc)
backtickOperator :: (Parsing m, MonadState IState m) => m Name
backtickOperator = P.between (indentGt *> lchar '`') (indentGt *> lchar '`') name
| Parses an operator name ( either a symbolic name or a backtick - quoted name )
@
OperatorName : : =
SymbolicOperator
| BacktickOperator
;
@
@
OperatorName ::=
SymbolicOperator
| BacktickOperator
;
@
-}
operatorName :: (Parsing m, MonadState IState m) => m Name
operatorName = sUN <$> symbolicOperator
<|> backtickOperator
operatorFront :: Parsing m => m Name
operatorFront = do P.try $ lchar '(' *> (eqTy <$ reservedOp "=") <* lchar ')'
<|> maybeWithNS (lchar '(' *> symbolicOperator <* lchar ')') []
| Parses a function ( either normal name or operator )
@
FnName : : = Name | OperatorFront ;
@
@
FnName ::= Name | OperatorFront;
@
-}
fnName :: (Parsing m, MonadState IState m) => m Name
fnName = P.try operatorFront <|> name <?> "function name"
| Parses a fixity declaration
@
Fixity : : =
FixityType Natural_t OperatorList ;
@
@
Fixity ::=
FixityType Natural_t OperatorList Terminator
;
@
-}
fixity :: IdrisParser PDecl
fixity = do ((f, i, ops), fc) <- withExtent $ do
pushIndent
f <- fixityType; i <- natural
ops <- P.sepBy1 (show . nsroot <$> operatorName) (lchar ',')
terminator
return (f, i, ops)
let prec = fromInteger i
istate <- get
let infixes = idris_infixes istate
let fs = map (Fix (f prec)) ops
let redecls = map (alreadyDeclared infixes) fs
let ill = filter (not . checkValidity) redecls
if null ill
then do put (istate { idris_infixes = nub $ sort (fs ++ infixes)
, ibc_write = map IBCFix fs ++ ibc_write istate
})
return (PFix fc (f prec) ops)
else fail $ concatMap (\(f, (x:xs)) -> "Illegal redeclaration of fixity:\n\t\""
++ show f ++ "\" overrides \"" ++ show x ++ "\"") ill
<?> "fixity declaration"
where
alreadyDeclared :: [FixDecl] -> FixDecl -> (FixDecl, [FixDecl])
alreadyDeclared fs f = (f, filter ((extractName f ==) . extractName) fs)
checkValidity :: (FixDecl, [FixDecl]) -> Bool
checkValidity (f, fs) = all (== f) fs
extractName :: FixDecl -> String
extractName (Fix _ n) = n
checkDeclFixity :: IdrisParser PDecl -> IdrisParser PDecl
checkDeclFixity p = do decl <- p
case getDeclName decl of
Nothing -> return decl
Just n -> do checkNameFixity n
return decl
where getDeclName (PTy _ _ _ _ _ n _ _ ) = Just n
getDeclName (PData _ _ _ _ _ (PDatadecl n _ _ _)) = Just n
getDeclName _ = Nothing
checkNameFixity :: Name -> IdrisParser ()
checkNameFixity n = do fOk <- fixityOk n
unless fOk . fail $
"Missing fixity declaration for " ++ show n
where fixityOk (NS n' _) = fixityOk n'
fixityOk (UN n') | all (flip elem opChars) (str n') =
do fixities <- fmap idris_infixes get
return . elem (str n') . map (\ (Fix _ op) -> op) $ fixities
| otherwise = return True
fixityOk _ = return True
| Parses a fixity declaration type ( i.e. infix or prefix , associtavity )
@
FixityType : : =
' infixl '
| ' infixr '
| ' infix '
| ' prefix '
;
@
@
FixityType ::=
'infixl'
| 'infixr'
| 'infix'
| 'prefix'
;
@
-}
fixityType :: IdrisParser (Int -> Fixity)
fixityType = do reserved "infixl"; return Infixl
<|> do reserved "infixr"; return Infixr
<|> do reserved "infix"; return InfixN
<|> do reserved "prefix"; return PrefixN
<?> "fixity type"
opChars :: String
opChars = ":!#$%&*+./<=>?@\\^|-~"
operatorLetter :: Parsing m => m Char
operatorLetter = P.oneOf opChars
commentMarkers :: [String]
commentMarkers = [ "--", "|||" ]
invalidOperators :: [String]
invalidOperators = [":", "=>", "->", "<-", "=", "?=", "|", "**", "==>", "\\", "%", "~", "?", "!", "@"]
symbolicOperator :: Parsing m => m String
symbolicOperator = do op <- token . some $ operatorLetter
when (op `elem` (invalidOperators ++ commentMarkers)) $
fail $ op ++ " is not a valid operator"
return op
Taken from Parsec ( c ) 1999 - 2001 , ( c ) 2007
reservedOp :: Parsing m => String -> m ()
reservedOp name = token $ P.try $
do string name
P.notFollowedBy operatorLetter <?> ("end of " ++ show name)
|
3f71ac56ad037e5380421673986996ba1233f4883855c016bdc20123a447c314 | Factual/sosueme | txt.clj | (ns sosueme.txt
(:import [java.io StringWriter])
(:require [clojure.pprint :as pprint]))
(defn pretty
"Uses Clojure's pprint to return a prettily formatted String representation of o,
including line breaks for readability."
[o]
(let [w (StringWriter.)] (pprint/pprint o w)(.toString w)))
| null | https://raw.githubusercontent.com/Factual/sosueme/1c2e9b7eb4df8ae67012dc2a398b4ec63c9bd6cd/src/sosueme/txt.clj | clojure | (ns sosueme.txt
(:import [java.io StringWriter])
(:require [clojure.pprint :as pprint]))
(defn pretty
"Uses Clojure's pprint to return a prettily formatted String representation of o,
including line breaks for readability."
[o]
(let [w (StringWriter.)] (pprint/pprint o w)(.toString w)))
| |
d07b0e1f16addc1d4f5b15201ef8e2c8e2c08d6f7fa29ec9e7b5ec92f05a004a | 4clojure/4clojure | api.clj | (ns foreclojure.api
(:require [cheshire.core :as json])
(:use [foreclojure.ring :only [wrap-json wrap-debug]]
[foreclojure.utils :only [as-int]]
[compojure.core :only [routes GET]]
[somnium.congomongo :only [fetch-one]]
[useful.map :only [update-each]]))
(def api-routes
(-> (routes
(GET "/api/problem/:id" [id]
(when-let [problem (fetch-one :problems :where {:_id (as-int id)
:approved true})]
{:body (-> problem
(dissoc :_id :approved)
(update-each [:restricted :tags]
#(or % ())))})))
(wrap-json)))
| null | https://raw.githubusercontent.com/4clojure/4clojure/25dec057d9d6871ce52aee9e2c3de7efdab14373/src/foreclojure/api.clj | clojure | (ns foreclojure.api
(:require [cheshire.core :as json])
(:use [foreclojure.ring :only [wrap-json wrap-debug]]
[foreclojure.utils :only [as-int]]
[compojure.core :only [routes GET]]
[somnium.congomongo :only [fetch-one]]
[useful.map :only [update-each]]))
(def api-routes
(-> (routes
(GET "/api/problem/:id" [id]
(when-let [problem (fetch-one :problems :where {:_id (as-int id)
:approved true})]
{:body (-> problem
(dissoc :_id :approved)
(update-each [:restricted :tags]
#(or % ())))})))
(wrap-json)))
| |
01410d1ca3cd48381e6e49114a9121cb824ff98cd87718b661faa25701d47a36 | amnh/poy5 | dictionary.ml | POY 5.1.1 . A phylogenetic analysis program using Dynamic Homologies .
Copyright ( C ) 2011 , , , Ward Wheeler
and the American Museum of Natural History .
(* *)
(* This program is free software; you can redistribute it and/or modify *)
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
(* (at your option) any later version. *)
(* *)
(* This program is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU General Public License for more details. *)
(* *)
You should have received a copy of the GNU General Public License
along with this program ; if not , write to the Free Software
Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston ,
USA
let gen_of_channel adder ch =
let input_handler = FileStream.stream_reader ch in
let rec reader counter =
try let line = input_handler#read_line in
match Str.split (Str.regexp "[\t ]+") line with
| [] | [_] ->
let msg = ("Line " ^ string_of_int counter ^ ": " ^ line) in
raise (E.Illegal_dictionary msg)
| hd :: tl ->
List.iter (fun x -> adder x hd) tl;
reader (counter + 1)
with | End_of_file -> ()
in
reader 1
let of_channel ch =
let table = Hashtbl.create 1667 in
gen_of_channel (Hashtbl.add table) ch;
table
let of_channel_assoc ch =
let table = ref [] in
gen_of_channel (fun a b -> table := (a, b) :: !table) ch;
List.rev !table
| null | https://raw.githubusercontent.com/amnh/poy5/da563a2339d3fa9c0110ae86cc35fad576f728ab/src/parser/dictionary.ml | ocaml |
This program is free software; you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
| POY 5.1.1 . A phylogenetic analysis program using Dynamic Homologies .
Copyright ( C ) 2011 , , , Ward Wheeler
and the American Museum of Natural History .
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
You should have received a copy of the GNU General Public License
along with this program ; if not , write to the Free Software
Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston ,
USA
let gen_of_channel adder ch =
let input_handler = FileStream.stream_reader ch in
let rec reader counter =
try let line = input_handler#read_line in
match Str.split (Str.regexp "[\t ]+") line with
| [] | [_] ->
let msg = ("Line " ^ string_of_int counter ^ ": " ^ line) in
raise (E.Illegal_dictionary msg)
| hd :: tl ->
List.iter (fun x -> adder x hd) tl;
reader (counter + 1)
with | End_of_file -> ()
in
reader 1
let of_channel ch =
let table = Hashtbl.create 1667 in
gen_of_channel (Hashtbl.add table) ch;
table
let of_channel_assoc ch =
let table = ref [] in
gen_of_channel (fun a b -> table := (a, b) :: !table) ch;
List.rev !table
|
2a04dd5781c99989d62796770c1b93a219cedab939c735b1cadede4266ca5958 | shentufoundation/deepsea | StmCompile.ml | open AST
open Ascii
open BinInt
open BinNums
open Compiled
open Datatypes
open EVM
open ExprCompile
open Integers
open List0
open LowValues
open Maps0
open MemoryModel
open Monad
open Nat0
open OptErrMonad
open PeanoNat
open StmtExpressionless
open String0
(** val assign_stack_compiled : nat -> compiled **)
let assign_stack_compiled required_index =
match Nat.leb required_index (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S
(S O)))))))))))))))) with
| Coq_true -> command_compiled (Coq_evm_swap required_index)
| Coq_false ->
error_compiled (String ((Ascii (Coq_true, Coq_true, Coq_false, Coq_false,
Coq_false, Coq_true, Coq_true, Coq_false)), (String ((Ascii (Coq_true,
Coq_false, Coq_false, Coq_false, Coq_false, Coq_true, Coq_true,
Coq_false)), (String ((Ascii (Coq_false, Coq_true, Coq_true, Coq_true,
Coq_false, Coq_true, Coq_true, Coq_false)), (String ((Ascii (Coq_true,
Coq_true, Coq_true, Coq_false, Coq_false, Coq_true, Coq_false,
Coq_false)), (String ((Ascii (Coq_false, Coq_false, Coq_true,
Coq_false, Coq_true, Coq_true, Coq_true, Coq_false)), (String ((Ascii
(Coq_false, Coq_false, Coq_false, Coq_false, Coq_false, Coq_true,
Coq_false, Coq_false)), (String ((Ascii (Coq_true, Coq_true, Coq_false,
Coq_false, Coq_true, Coq_true, Coq_true, Coq_false)), (String ((Ascii
(Coq_true, Coq_true, Coq_true, Coq_false, Coq_true, Coq_true, Coq_true,
Coq_false)), (String ((Ascii (Coq_true, Coq_false, Coq_false,
Coq_false, Coq_false, Coq_true, Coq_true, Coq_false)), (String ((Ascii
(Coq_false, Coq_false, Coq_false, Coq_false, Coq_true, Coq_true,
Coq_true, Coq_false)), (String ((Ascii (Coq_false, Coq_false,
Coq_false, Coq_false, Coq_false, Coq_true, Coq_false, Coq_false)),
(String ((Ascii (Coq_false, Coq_false, Coq_true, Coq_false, Coq_true,
Coq_true, Coq_true, Coq_false)), (String ((Ascii (Coq_true, Coq_true,
Coq_true, Coq_true, Coq_false, Coq_true, Coq_true, Coq_false)), (String
((Ascii (Coq_false, Coq_false, Coq_false, Coq_false, Coq_false,
Coq_true, Coq_false, Coq_false)), (String ((Ascii (Coq_true, Coq_true,
Coq_false, Coq_false, Coq_true, Coq_true, Coq_true, Coq_false)),
(String ((Ascii (Coq_false, Coq_false, Coq_true, Coq_false, Coq_true,
Coq_true, Coq_true, Coq_false)), (String ((Ascii (Coq_true, Coq_true,
Coq_true, Coq_true, Coq_false, Coq_true, Coq_true, Coq_false)), (String
((Ascii (Coq_false, Coq_true, Coq_false, Coq_false, Coq_true, Coq_true,
Coq_true, Coq_false)), (String ((Ascii (Coq_true, Coq_false, Coq_true,
Coq_false, Coq_false, Coq_true, Coq_true, Coq_false)), (String ((Ascii
(Coq_false, Coq_false, Coq_false, Coq_false, Coq_false, Coq_true,
Coq_false, Coq_false)), (String ((Ascii (Coq_false, Coq_false,
Coq_true, Coq_true, Coq_false, Coq_true, Coq_true, Coq_false)), (String
((Ascii (Coq_true, Coq_true, Coq_true, Coq_true, Coq_false, Coq_true,
Coq_true, Coq_false)), (String ((Ascii (Coq_true, Coq_true, Coq_false,
Coq_false, Coq_false, Coq_true, Coq_true, Coq_false)), (String ((Ascii
(Coq_true, Coq_false, Coq_false, Coq_false, Coq_false, Coq_true,
Coq_true, Coq_false)), (String ((Ascii (Coq_false, Coq_false, Coq_true,
Coq_true, Coq_false, Coq_true, Coq_true, Coq_false)), (String ((Ascii
(Coq_true, Coq_true, Coq_true, Coq_true, Coq_false, Coq_true,
Coq_false, Coq_false)), (String ((Ascii (Coq_false, Coq_false,
Coq_true, Coq_false, Coq_true, Coq_true, Coq_true, Coq_false)), (String
((Ascii (Coq_true, Coq_false, Coq_true, Coq_false, Coq_false, Coq_true,
Coq_true, Coq_false)), (String ((Ascii (Coq_true, Coq_false, Coq_true,
Coq_true, Coq_false, Coq_true, Coq_true, Coq_false)), (String ((Ascii
(Coq_false, Coq_false, Coq_false, Coq_false, Coq_true, Coq_true,
Coq_true, Coq_false)),
EmptyString))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))
* val push_public_args : - > nat - > nat - > Int.int - > compiled *
let rec push_public_args args first_arg_index retval_count funsig =
match args with
| O ->
append_compiled Coq_evm_mstore
(append_compiled (Coq_evm_push
(Int256.repr (public_funsig_pos retval_count)))
(command_compiled (Coq_evm_push (funsig_aligned funsig))))
| S n ->
let rest_compiled =
push_public_args n (add first_arg_index (S O)) retval_count funsig
in
let arg_pos = Coq_evm_push
(Int256.repr (public_arg_pos first_arg_index retval_count))
in
append_compiled Coq_evm_mstore (append_compiled arg_pos rest_compiled)
(** val code_return : label -> compiled **)
let code_return code_label =
append_compiled Coq_evm_return
(append_compiled (Coq_evm_push Int256.zero)
(append_compiled Coq_evm_codesize
(append_compiled Coq_evm_codecopy
(append_compiled (Coq_evm_push Int256.zero)
(append_compiled (Coq_evm_push_label code_label)
(command_compiled Coq_evm_codesize))))))
(** val cleanup : ret_type -> label -> compiled **)
let cleanup rv code_label =
match rv with
| Tvoid_method ->
append_compiled Coq_evm_return
(append_compiled (Coq_evm_push Int256.zero)
(command_compiled (Coq_evm_push Int256.zero)))
| Tconstructor -> code_return code_label
| Tfun ->
append_compiled Coq_evm_jump (command_compiled (Coq_evm_swap (S O)))
| Tsome_method ->
append_compiled Coq_evm_return
(append_compiled (Coq_evm_push Int256.zero)
(append_compiled (Coq_evm_push
(Int256.repr (Zpos (Coq_xO (Coq_xO (Coq_xO (Coq_xO (Coq_xO
Coq_xH))))))))
(append_compiled Coq_evm_mstore
(command_compiled (Coq_evm_push Int256.zero)))))
(** val push_event_args : nat -> compiled **)
let rec push_event_args = function
| O -> empty_compiled
| S n ->
append_compiled Coq_evm_mstore
(append_compiled (Coq_evm_push
(Int256.repr
(Z.mul (Zpos (Coq_xO (Coq_xO (Coq_xO (Coq_xO (Coq_xO Coq_xH))))))
(Z.of_nat n)))) (push_event_args n))
* constructor_data_load : - > compiled *
let constructor_data_load index =
ret (Obj.magic coq_Monad_optErr)
(rev (Coq_cons ((Coq_evm_push
(Int256.repr (Zpos (Coq_xO (Coq_xO (Coq_xO (Coq_xO (Coq_xO Coq_xH)))))))),
(Coq_cons ((Coq_evm_totallength index), (Coq_cons ((Coq_evm_push
(Int256.repr (Zpos (Coq_xO (Coq_xO (Coq_xO (Coq_xO (Coq_xO (Coq_xO
(Coq_xO Coq_xH)))))))))), (Coq_cons (Coq_evm_codecopy, (Coq_cons
((Coq_evm_push
(Int256.repr (Zpos (Coq_xO (Coq_xO (Coq_xO (Coq_xO (Coq_xO (Coq_xO
(Coq_xO Coq_xH)))))))))), (Coq_cons (Coq_evm_mload,
Coq_nil)))))))))))))
* stm_compiled : statement - > coq_Z PTree.t - > label - > compiled *
let stm_compiled stm _ code_label =
match stm with
| Spush s ->
(match s with
| Coq_inl v ->
(match v with
| Vunit -> command_compiled (Coq_evm_push Int256.zero)
| Vint i -> command_compiled (Coq_evm_push i)
| _ ->
error_compiled (String ((Ascii (Coq_false, Coq_false, Coq_false,
Coq_false, Coq_true, Coq_true, Coq_true, Coq_false)), (String
((Ascii (Coq_true, Coq_false, Coq_true, Coq_false, Coq_true,
Coq_true, Coq_true, Coq_false)), (String ((Ascii (Coq_true,
Coq_true, Coq_false, Coq_false, Coq_true, Coq_true, Coq_true,
Coq_false)), (String ((Ascii (Coq_false, Coq_false, Coq_false,
Coq_true, Coq_false, Coq_true, Coq_true, Coq_false)), (String
((Ascii (Coq_false, Coq_false, Coq_false, Coq_false, Coq_false,
Coq_true, Coq_false, Coq_false)), (String ((Ascii (Coq_true,
Coq_true, Coq_true, Coq_true, Coq_false, Coq_true, Coq_true,
Coq_false)), (String ((Ascii (Coq_false, Coq_true, Coq_true,
Coq_false, Coq_false, Coq_true, Coq_true, Coq_false)), (String
((Ascii (Coq_false, Coq_false, Coq_false, Coq_false, Coq_false,
Coq_true, Coq_false, Coq_false)), (String ((Ascii (Coq_true,
Coq_false, Coq_true, Coq_true, Coq_false, Coq_true, Coq_true,
Coq_false)), (String ((Ascii (Coq_true, Coq_false, Coq_false,
Coq_false, Coq_false, Coq_true, Coq_true, Coq_false)), (String
((Ascii (Coq_false, Coq_false, Coq_true, Coq_true, Coq_false,
Coq_true, Coq_true, Coq_false)), (String ((Ascii (Coq_false,
Coq_true, Coq_true, Coq_false, Coq_false, Coq_true, Coq_true,
Coq_false)), (String ((Ascii (Coq_true, Coq_true, Coq_true,
Coq_true, Coq_false, Coq_true, Coq_true, Coq_false)), (String
((Ascii (Coq_false, Coq_true, Coq_false, Coq_false, Coq_true,
Coq_true, Coq_true, Coq_false)), (String ((Ascii (Coq_true,
Coq_false, Coq_true, Coq_true, Coq_false, Coq_true, Coq_true,
Coq_false)), (String ((Ascii (Coq_true, Coq_false, Coq_true,
Coq_false, Coq_false, Coq_true, Coq_true, Coq_false)), (String
((Ascii (Coq_false, Coq_false, Coq_true, Coq_false, Coq_false,
Coq_true, Coq_true, Coq_false)), (String ((Ascii (Coq_false,
Coq_false, Coq_false, Coq_false, Coq_false, Coq_true, Coq_false,
Coq_false)), (String ((Ascii (Coq_false, Coq_true, Coq_true,
Coq_false, Coq_true, Coq_true, Coq_true, Coq_false)), (String
((Ascii (Coq_true, Coq_false, Coq_false, Coq_false, Coq_false,
Coq_true, Coq_true, Coq_false)), (String ((Ascii (Coq_false,
Coq_false, Coq_true, Coq_true, Coq_false, Coq_true, Coq_true,
Coq_false)), (String ((Ascii (Coq_true, Coq_false, Coq_true,
Coq_false, Coq_true, Coq_true, Coq_true, Coq_false)), (String
((Ascii (Coq_true, Coq_false, Coq_true, Coq_false, Coq_false,
Coq_true, Coq_true, Coq_false)),
EmptyString)))))))))))))))))))))))))))))))))))))))))))))))
| Coq_inr l -> command_compiled (Coq_evm_push_label l))
| Sdup id -> dup_ident id
| Ssload -> command_compiled Coq_evm_sload
| Smload -> command_compiled Coq_evm_mload
| Sunop op -> unop_compiled op
| Sbinop (op, sgn) -> binop_compiled op sgn
| Scall0 b -> command_compiled (builtin0_compiled b)
| Scall1 b -> command_compiled (builtin1_compiled b)
| Sskip -> empty_compiled
| Spop -> command_compiled Coq_evm_pop
| Ssstore -> command_compiled Coq_evm_sstore
| Smstore -> command_compiled Coq_evm_mstore
| Sswap lv -> assign_stack_compiled (S lv)
| Sdone rv -> cleanup rv code_label
| Slabel l -> command_compiled (Coq_evm_label l)
| Sjump -> command_compiled Coq_evm_jump
| Sjumpi -> command_compiled Coq_evm_jumpi
| Shash -> command_compiled Coq_evm_sha3
| Stransfer -> command_compiled Coq_evm_call
| Scallargs (sg, args, rvcount) -> push_public_args args O rvcount sg
| Scallmethod b ->
(match b with
| Coq_true -> command_compiled Coq_evm_call
| Coq_false ->
append_compiled Coq_evm_call (command_compiled Coq_evm_gas))
| Slog (ntopics, nargs) ->
(match Nat.ltb nargs (S (S (S (S (S O))))) with
| Coq_true ->
append_compiled (Coq_evm_log ntopics)
(append_compiled (Coq_evm_push (Int256.repr Z0))
(append_compiled (Coq_evm_push
(Int256.repr
(Z.mul (Zpos (Coq_xO (Coq_xO (Coq_xO (Coq_xO (Coq_xO
Coq_xH)))))) (Z.of_nat nargs)))) (push_event_args nargs)))
| Coq_false ->
Error (String ((Ascii (Coq_false, Coq_false, Coq_true, Coq_false,
Coq_true, Coq_true, Coq_true, Coq_false)), (String ((Ascii
(Coq_true, Coq_true, Coq_true, Coq_true, Coq_false, Coq_true,
Coq_true, Coq_false)), (String ((Ascii (Coq_true, Coq_true,
Coq_true, Coq_true, Coq_false, Coq_true, Coq_true, Coq_false)),
(String ((Ascii (Coq_false, Coq_false, Coq_false, Coq_false,
Coq_false, Coq_true, Coq_false, Coq_false)), (String ((Ascii
(Coq_true, Coq_false, Coq_true, Coq_true, Coq_false, Coq_true,
Coq_true, Coq_false)), (String ((Ascii (Coq_true, Coq_false,
Coq_false, Coq_false, Coq_false, Coq_true, Coq_true, Coq_false)),
(String ((Ascii (Coq_false, Coq_true, Coq_true, Coq_true, Coq_false,
Coq_true, Coq_true, Coq_false)), (String ((Ascii (Coq_true,
Coq_false, Coq_false, Coq_true, Coq_true, Coq_true, Coq_true,
Coq_false)), (String ((Ascii (Coq_false, Coq_false, Coq_false,
Coq_false, Coq_false, Coq_true, Coq_false, Coq_false)), (String
((Ascii (Coq_true, Coq_false, Coq_false, Coq_true, Coq_false,
Coq_true, Coq_true, Coq_false)), (String ((Ascii (Coq_false,
Coq_true, Coq_true, Coq_true, Coq_false, Coq_true, Coq_true,
Coq_false)), (String ((Ascii (Coq_false, Coq_false, Coq_true,
Coq_false, Coq_false, Coq_true, Coq_true, Coq_false)), (String
((Ascii (Coq_true, Coq_false, Coq_true, Coq_false, Coq_false,
Coq_true, Coq_true, Coq_false)), (String ((Ascii (Coq_false,
Coq_false, Coq_false, Coq_true, Coq_true, Coq_true, Coq_true,
Coq_false)), (String ((Ascii (Coq_true, Coq_false, Coq_true,
Coq_false, Coq_false, Coq_true, Coq_true, Coq_false)), (String
((Ascii (Coq_false, Coq_false, Coq_true, Coq_false, Coq_false,
Coq_true, Coq_true, Coq_false)), (String ((Ascii (Coq_false,
Coq_false, Coq_false, Coq_false, Coq_false, Coq_true, Coq_false,
Coq_false)), (String ((Ascii (Coq_true, Coq_false, Coq_false,
Coq_false, Coq_false, Coq_true, Coq_true, Coq_false)), (String
((Ascii (Coq_false, Coq_true, Coq_false, Coq_false, Coq_true,
Coq_true, Coq_true, Coq_false)), (String ((Ascii (Coq_true,
Coq_true, Coq_true, Coq_false, Coq_false, Coq_true, Coq_true,
Coq_false)), (String ((Ascii (Coq_true, Coq_false, Coq_true,
Coq_false, Coq_true, Coq_true, Coq_true, Coq_false)), (String
((Ascii (Coq_true, Coq_false, Coq_true, Coq_true, Coq_false,
Coq_true, Coq_true, Coq_false)), (String ((Ascii (Coq_true,
Coq_false, Coq_true, Coq_false, Coq_false, Coq_true, Coq_true,
Coq_false)), (String ((Ascii (Coq_false, Coq_true, Coq_true,
Coq_true, Coq_false, Coq_true, Coq_true, Coq_false)), (String
((Ascii (Coq_false, Coq_false, Coq_true, Coq_false, Coq_true,
Coq_true, Coq_true, Coq_false)), (String ((Ascii (Coq_false,
Coq_false, Coq_false, Coq_false, Coq_false, Coq_true, Coq_false,
Coq_false)), (String ((Ascii (Coq_true, Coq_false, Coq_false,
Coq_true, Coq_false, Coq_true, Coq_true, Coq_false)), (String
((Ascii (Coq_false, Coq_true, Coq_true, Coq_true, Coq_false,
Coq_true, Coq_true, Coq_false)), (String ((Ascii (Coq_false,
Coq_false, Coq_false, Coq_false, Coq_false, Coq_true, Coq_false,
Coq_false)), (String ((Ascii (Coq_false, Coq_false, Coq_true,
Coq_true, Coq_false, Coq_true, Coq_true, Coq_false)), (String
((Ascii (Coq_true, Coq_true, Coq_true, Coq_true, Coq_false,
Coq_true, Coq_true, Coq_false)), (String ((Ascii (Coq_true,
Coq_true, Coq_true, Coq_false, Coq_false, Coq_true, Coq_true,
Coq_false)), (String ((Ascii (Coq_false, Coq_false, Coq_false,
Coq_false, Coq_false, Coq_true, Coq_false, Coq_false)), (String
((Ascii (Coq_true, Coq_true, Coq_false, Coq_false, Coq_true,
Coq_true, Coq_true, Coq_false)), (String ((Ascii (Coq_false,
Coq_false, Coq_true, Coq_false, Coq_true, Coq_true, Coq_true,
Coq_false)), (String ((Ascii (Coq_true, Coq_false, Coq_false,
Coq_false, Coq_false, Coq_true, Coq_true, Coq_false)), (String
((Ascii (Coq_false, Coq_false, Coq_true, Coq_false, Coq_true,
Coq_true, Coq_true, Coq_false)), (String ((Ascii (Coq_true,
Coq_false, Coq_true, Coq_false, Coq_false, Coq_true, Coq_true,
Coq_false)), (String ((Ascii (Coq_true, Coq_false, Coq_true,
Coq_true, Coq_false, Coq_true, Coq_true, Coq_false)), (String
((Ascii (Coq_true, Coq_false, Coq_true, Coq_false, Coq_false,
Coq_true, Coq_true, Coq_false)), (String ((Ascii (Coq_false,
Coq_true, Coq_true, Coq_true, Coq_false, Coq_true, Coq_true,
Coq_false)), (String ((Ascii (Coq_false, Coq_false, Coq_true,
Coq_false, Coq_true, Coq_true, Coq_true, Coq_false)),
EmptyString)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))
| Srevert ->
append_compiled Coq_evm_revert
(append_compiled (Coq_evm_push Int256.zero)
(command_compiled (Coq_evm_push Int256.zero)))
| Scalldataload -> command_compiled Coq_evm_calldataload
| Sconstructordataload i -> constructor_data_load i
* code_compiled : code - > coq_Z PTree.t - > label - > compiled *
let rec code_compiled c ge code_label =
match c with
| Coq_nil -> empty_compiled
| Coq_cons (stm, rest) ->
let sc = stm_compiled stm ge code_label in
let rest0 = code_compiled rest ge code_label in
concatenate_compiled sc rest0
| null | https://raw.githubusercontent.com/shentufoundation/deepsea/970576a97c8992655ed2f173f576502d73b827e1/src/backend/extraction/StmCompile.ml | ocaml | * val assign_stack_compiled : nat -> compiled *
* val code_return : label -> compiled *
* val cleanup : ret_type -> label -> compiled *
* val push_event_args : nat -> compiled * | open AST
open Ascii
open BinInt
open BinNums
open Compiled
open Datatypes
open EVM
open ExprCompile
open Integers
open List0
open LowValues
open Maps0
open MemoryModel
open Monad
open Nat0
open OptErrMonad
open PeanoNat
open StmtExpressionless
open String0
let assign_stack_compiled required_index =
match Nat.leb required_index (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S
(S O)))))))))))))))) with
| Coq_true -> command_compiled (Coq_evm_swap required_index)
| Coq_false ->
error_compiled (String ((Ascii (Coq_true, Coq_true, Coq_false, Coq_false,
Coq_false, Coq_true, Coq_true, Coq_false)), (String ((Ascii (Coq_true,
Coq_false, Coq_false, Coq_false, Coq_false, Coq_true, Coq_true,
Coq_false)), (String ((Ascii (Coq_false, Coq_true, Coq_true, Coq_true,
Coq_false, Coq_true, Coq_true, Coq_false)), (String ((Ascii (Coq_true,
Coq_true, Coq_true, Coq_false, Coq_false, Coq_true, Coq_false,
Coq_false)), (String ((Ascii (Coq_false, Coq_false, Coq_true,
Coq_false, Coq_true, Coq_true, Coq_true, Coq_false)), (String ((Ascii
(Coq_false, Coq_false, Coq_false, Coq_false, Coq_false, Coq_true,
Coq_false, Coq_false)), (String ((Ascii (Coq_true, Coq_true, Coq_false,
Coq_false, Coq_true, Coq_true, Coq_true, Coq_false)), (String ((Ascii
(Coq_true, Coq_true, Coq_true, Coq_false, Coq_true, Coq_true, Coq_true,
Coq_false)), (String ((Ascii (Coq_true, Coq_false, Coq_false,
Coq_false, Coq_false, Coq_true, Coq_true, Coq_false)), (String ((Ascii
(Coq_false, Coq_false, Coq_false, Coq_false, Coq_true, Coq_true,
Coq_true, Coq_false)), (String ((Ascii (Coq_false, Coq_false,
Coq_false, Coq_false, Coq_false, Coq_true, Coq_false, Coq_false)),
(String ((Ascii (Coq_false, Coq_false, Coq_true, Coq_false, Coq_true,
Coq_true, Coq_true, Coq_false)), (String ((Ascii (Coq_true, Coq_true,
Coq_true, Coq_true, Coq_false, Coq_true, Coq_true, Coq_false)), (String
((Ascii (Coq_false, Coq_false, Coq_false, Coq_false, Coq_false,
Coq_true, Coq_false, Coq_false)), (String ((Ascii (Coq_true, Coq_true,
Coq_false, Coq_false, Coq_true, Coq_true, Coq_true, Coq_false)),
(String ((Ascii (Coq_false, Coq_false, Coq_true, Coq_false, Coq_true,
Coq_true, Coq_true, Coq_false)), (String ((Ascii (Coq_true, Coq_true,
Coq_true, Coq_true, Coq_false, Coq_true, Coq_true, Coq_false)), (String
((Ascii (Coq_false, Coq_true, Coq_false, Coq_false, Coq_true, Coq_true,
Coq_true, Coq_false)), (String ((Ascii (Coq_true, Coq_false, Coq_true,
Coq_false, Coq_false, Coq_true, Coq_true, Coq_false)), (String ((Ascii
(Coq_false, Coq_false, Coq_false, Coq_false, Coq_false, Coq_true,
Coq_false, Coq_false)), (String ((Ascii (Coq_false, Coq_false,
Coq_true, Coq_true, Coq_false, Coq_true, Coq_true, Coq_false)), (String
((Ascii (Coq_true, Coq_true, Coq_true, Coq_true, Coq_false, Coq_true,
Coq_true, Coq_false)), (String ((Ascii (Coq_true, Coq_true, Coq_false,
Coq_false, Coq_false, Coq_true, Coq_true, Coq_false)), (String ((Ascii
(Coq_true, Coq_false, Coq_false, Coq_false, Coq_false, Coq_true,
Coq_true, Coq_false)), (String ((Ascii (Coq_false, Coq_false, Coq_true,
Coq_true, Coq_false, Coq_true, Coq_true, Coq_false)), (String ((Ascii
(Coq_true, Coq_true, Coq_true, Coq_true, Coq_false, Coq_true,
Coq_false, Coq_false)), (String ((Ascii (Coq_false, Coq_false,
Coq_true, Coq_false, Coq_true, Coq_true, Coq_true, Coq_false)), (String
((Ascii (Coq_true, Coq_false, Coq_true, Coq_false, Coq_false, Coq_true,
Coq_true, Coq_false)), (String ((Ascii (Coq_true, Coq_false, Coq_true,
Coq_true, Coq_false, Coq_true, Coq_true, Coq_false)), (String ((Ascii
(Coq_false, Coq_false, Coq_false, Coq_false, Coq_true, Coq_true,
Coq_true, Coq_false)),
EmptyString))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))
* val push_public_args : - > nat - > nat - > Int.int - > compiled *
let rec push_public_args args first_arg_index retval_count funsig =
match args with
| O ->
append_compiled Coq_evm_mstore
(append_compiled (Coq_evm_push
(Int256.repr (public_funsig_pos retval_count)))
(command_compiled (Coq_evm_push (funsig_aligned funsig))))
| S n ->
let rest_compiled =
push_public_args n (add first_arg_index (S O)) retval_count funsig
in
let arg_pos = Coq_evm_push
(Int256.repr (public_arg_pos first_arg_index retval_count))
in
append_compiled Coq_evm_mstore (append_compiled arg_pos rest_compiled)
let code_return code_label =
append_compiled Coq_evm_return
(append_compiled (Coq_evm_push Int256.zero)
(append_compiled Coq_evm_codesize
(append_compiled Coq_evm_codecopy
(append_compiled (Coq_evm_push Int256.zero)
(append_compiled (Coq_evm_push_label code_label)
(command_compiled Coq_evm_codesize))))))
let cleanup rv code_label =
match rv with
| Tvoid_method ->
append_compiled Coq_evm_return
(append_compiled (Coq_evm_push Int256.zero)
(command_compiled (Coq_evm_push Int256.zero)))
| Tconstructor -> code_return code_label
| Tfun ->
append_compiled Coq_evm_jump (command_compiled (Coq_evm_swap (S O)))
| Tsome_method ->
append_compiled Coq_evm_return
(append_compiled (Coq_evm_push Int256.zero)
(append_compiled (Coq_evm_push
(Int256.repr (Zpos (Coq_xO (Coq_xO (Coq_xO (Coq_xO (Coq_xO
Coq_xH))))))))
(append_compiled Coq_evm_mstore
(command_compiled (Coq_evm_push Int256.zero)))))
let rec push_event_args = function
| O -> empty_compiled
| S n ->
append_compiled Coq_evm_mstore
(append_compiled (Coq_evm_push
(Int256.repr
(Z.mul (Zpos (Coq_xO (Coq_xO (Coq_xO (Coq_xO (Coq_xO Coq_xH))))))
(Z.of_nat n)))) (push_event_args n))
* constructor_data_load : - > compiled *
let constructor_data_load index =
ret (Obj.magic coq_Monad_optErr)
(rev (Coq_cons ((Coq_evm_push
(Int256.repr (Zpos (Coq_xO (Coq_xO (Coq_xO (Coq_xO (Coq_xO Coq_xH)))))))),
(Coq_cons ((Coq_evm_totallength index), (Coq_cons ((Coq_evm_push
(Int256.repr (Zpos (Coq_xO (Coq_xO (Coq_xO (Coq_xO (Coq_xO (Coq_xO
(Coq_xO Coq_xH)))))))))), (Coq_cons (Coq_evm_codecopy, (Coq_cons
((Coq_evm_push
(Int256.repr (Zpos (Coq_xO (Coq_xO (Coq_xO (Coq_xO (Coq_xO (Coq_xO
(Coq_xO Coq_xH)))))))))), (Coq_cons (Coq_evm_mload,
Coq_nil)))))))))))))
* stm_compiled : statement - > coq_Z PTree.t - > label - > compiled *
let stm_compiled stm _ code_label =
match stm with
| Spush s ->
(match s with
| Coq_inl v ->
(match v with
| Vunit -> command_compiled (Coq_evm_push Int256.zero)
| Vint i -> command_compiled (Coq_evm_push i)
| _ ->
error_compiled (String ((Ascii (Coq_false, Coq_false, Coq_false,
Coq_false, Coq_true, Coq_true, Coq_true, Coq_false)), (String
((Ascii (Coq_true, Coq_false, Coq_true, Coq_false, Coq_true,
Coq_true, Coq_true, Coq_false)), (String ((Ascii (Coq_true,
Coq_true, Coq_false, Coq_false, Coq_true, Coq_true, Coq_true,
Coq_false)), (String ((Ascii (Coq_false, Coq_false, Coq_false,
Coq_true, Coq_false, Coq_true, Coq_true, Coq_false)), (String
((Ascii (Coq_false, Coq_false, Coq_false, Coq_false, Coq_false,
Coq_true, Coq_false, Coq_false)), (String ((Ascii (Coq_true,
Coq_true, Coq_true, Coq_true, Coq_false, Coq_true, Coq_true,
Coq_false)), (String ((Ascii (Coq_false, Coq_true, Coq_true,
Coq_false, Coq_false, Coq_true, Coq_true, Coq_false)), (String
((Ascii (Coq_false, Coq_false, Coq_false, Coq_false, Coq_false,
Coq_true, Coq_false, Coq_false)), (String ((Ascii (Coq_true,
Coq_false, Coq_true, Coq_true, Coq_false, Coq_true, Coq_true,
Coq_false)), (String ((Ascii (Coq_true, Coq_false, Coq_false,
Coq_false, Coq_false, Coq_true, Coq_true, Coq_false)), (String
((Ascii (Coq_false, Coq_false, Coq_true, Coq_true, Coq_false,
Coq_true, Coq_true, Coq_false)), (String ((Ascii (Coq_false,
Coq_true, Coq_true, Coq_false, Coq_false, Coq_true, Coq_true,
Coq_false)), (String ((Ascii (Coq_true, Coq_true, Coq_true,
Coq_true, Coq_false, Coq_true, Coq_true, Coq_false)), (String
((Ascii (Coq_false, Coq_true, Coq_false, Coq_false, Coq_true,
Coq_true, Coq_true, Coq_false)), (String ((Ascii (Coq_true,
Coq_false, Coq_true, Coq_true, Coq_false, Coq_true, Coq_true,
Coq_false)), (String ((Ascii (Coq_true, Coq_false, Coq_true,
Coq_false, Coq_false, Coq_true, Coq_true, Coq_false)), (String
((Ascii (Coq_false, Coq_false, Coq_true, Coq_false, Coq_false,
Coq_true, Coq_true, Coq_false)), (String ((Ascii (Coq_false,
Coq_false, Coq_false, Coq_false, Coq_false, Coq_true, Coq_false,
Coq_false)), (String ((Ascii (Coq_false, Coq_true, Coq_true,
Coq_false, Coq_true, Coq_true, Coq_true, Coq_false)), (String
((Ascii (Coq_true, Coq_false, Coq_false, Coq_false, Coq_false,
Coq_true, Coq_true, Coq_false)), (String ((Ascii (Coq_false,
Coq_false, Coq_true, Coq_true, Coq_false, Coq_true, Coq_true,
Coq_false)), (String ((Ascii (Coq_true, Coq_false, Coq_true,
Coq_false, Coq_true, Coq_true, Coq_true, Coq_false)), (String
((Ascii (Coq_true, Coq_false, Coq_true, Coq_false, Coq_false,
Coq_true, Coq_true, Coq_false)),
EmptyString)))))))))))))))))))))))))))))))))))))))))))))))
| Coq_inr l -> command_compiled (Coq_evm_push_label l))
| Sdup id -> dup_ident id
| Ssload -> command_compiled Coq_evm_sload
| Smload -> command_compiled Coq_evm_mload
| Sunop op -> unop_compiled op
| Sbinop (op, sgn) -> binop_compiled op sgn
| Scall0 b -> command_compiled (builtin0_compiled b)
| Scall1 b -> command_compiled (builtin1_compiled b)
| Sskip -> empty_compiled
| Spop -> command_compiled Coq_evm_pop
| Ssstore -> command_compiled Coq_evm_sstore
| Smstore -> command_compiled Coq_evm_mstore
| Sswap lv -> assign_stack_compiled (S lv)
| Sdone rv -> cleanup rv code_label
| Slabel l -> command_compiled (Coq_evm_label l)
| Sjump -> command_compiled Coq_evm_jump
| Sjumpi -> command_compiled Coq_evm_jumpi
| Shash -> command_compiled Coq_evm_sha3
| Stransfer -> command_compiled Coq_evm_call
| Scallargs (sg, args, rvcount) -> push_public_args args O rvcount sg
| Scallmethod b ->
(match b with
| Coq_true -> command_compiled Coq_evm_call
| Coq_false ->
append_compiled Coq_evm_call (command_compiled Coq_evm_gas))
| Slog (ntopics, nargs) ->
(match Nat.ltb nargs (S (S (S (S (S O))))) with
| Coq_true ->
append_compiled (Coq_evm_log ntopics)
(append_compiled (Coq_evm_push (Int256.repr Z0))
(append_compiled (Coq_evm_push
(Int256.repr
(Z.mul (Zpos (Coq_xO (Coq_xO (Coq_xO (Coq_xO (Coq_xO
Coq_xH)))))) (Z.of_nat nargs)))) (push_event_args nargs)))
| Coq_false ->
Error (String ((Ascii (Coq_false, Coq_false, Coq_true, Coq_false,
Coq_true, Coq_true, Coq_true, Coq_false)), (String ((Ascii
(Coq_true, Coq_true, Coq_true, Coq_true, Coq_false, Coq_true,
Coq_true, Coq_false)), (String ((Ascii (Coq_true, Coq_true,
Coq_true, Coq_true, Coq_false, Coq_true, Coq_true, Coq_false)),
(String ((Ascii (Coq_false, Coq_false, Coq_false, Coq_false,
Coq_false, Coq_true, Coq_false, Coq_false)), (String ((Ascii
(Coq_true, Coq_false, Coq_true, Coq_true, Coq_false, Coq_true,
Coq_true, Coq_false)), (String ((Ascii (Coq_true, Coq_false,
Coq_false, Coq_false, Coq_false, Coq_true, Coq_true, Coq_false)),
(String ((Ascii (Coq_false, Coq_true, Coq_true, Coq_true, Coq_false,
Coq_true, Coq_true, Coq_false)), (String ((Ascii (Coq_true,
Coq_false, Coq_false, Coq_true, Coq_true, Coq_true, Coq_true,
Coq_false)), (String ((Ascii (Coq_false, Coq_false, Coq_false,
Coq_false, Coq_false, Coq_true, Coq_false, Coq_false)), (String
((Ascii (Coq_true, Coq_false, Coq_false, Coq_true, Coq_false,
Coq_true, Coq_true, Coq_false)), (String ((Ascii (Coq_false,
Coq_true, Coq_true, Coq_true, Coq_false, Coq_true, Coq_true,
Coq_false)), (String ((Ascii (Coq_false, Coq_false, Coq_true,
Coq_false, Coq_false, Coq_true, Coq_true, Coq_false)), (String
((Ascii (Coq_true, Coq_false, Coq_true, Coq_false, Coq_false,
Coq_true, Coq_true, Coq_false)), (String ((Ascii (Coq_false,
Coq_false, Coq_false, Coq_true, Coq_true, Coq_true, Coq_true,
Coq_false)), (String ((Ascii (Coq_true, Coq_false, Coq_true,
Coq_false, Coq_false, Coq_true, Coq_true, Coq_false)), (String
((Ascii (Coq_false, Coq_false, Coq_true, Coq_false, Coq_false,
Coq_true, Coq_true, Coq_false)), (String ((Ascii (Coq_false,
Coq_false, Coq_false, Coq_false, Coq_false, Coq_true, Coq_false,
Coq_false)), (String ((Ascii (Coq_true, Coq_false, Coq_false,
Coq_false, Coq_false, Coq_true, Coq_true, Coq_false)), (String
((Ascii (Coq_false, Coq_true, Coq_false, Coq_false, Coq_true,
Coq_true, Coq_true, Coq_false)), (String ((Ascii (Coq_true,
Coq_true, Coq_true, Coq_false, Coq_false, Coq_true, Coq_true,
Coq_false)), (String ((Ascii (Coq_true, Coq_false, Coq_true,
Coq_false, Coq_true, Coq_true, Coq_true, Coq_false)), (String
((Ascii (Coq_true, Coq_false, Coq_true, Coq_true, Coq_false,
Coq_true, Coq_true, Coq_false)), (String ((Ascii (Coq_true,
Coq_false, Coq_true, Coq_false, Coq_false, Coq_true, Coq_true,
Coq_false)), (String ((Ascii (Coq_false, Coq_true, Coq_true,
Coq_true, Coq_false, Coq_true, Coq_true, Coq_false)), (String
((Ascii (Coq_false, Coq_false, Coq_true, Coq_false, Coq_true,
Coq_true, Coq_true, Coq_false)), (String ((Ascii (Coq_false,
Coq_false, Coq_false, Coq_false, Coq_false, Coq_true, Coq_false,
Coq_false)), (String ((Ascii (Coq_true, Coq_false, Coq_false,
Coq_true, Coq_false, Coq_true, Coq_true, Coq_false)), (String
((Ascii (Coq_false, Coq_true, Coq_true, Coq_true, Coq_false,
Coq_true, Coq_true, Coq_false)), (String ((Ascii (Coq_false,
Coq_false, Coq_false, Coq_false, Coq_false, Coq_true, Coq_false,
Coq_false)), (String ((Ascii (Coq_false, Coq_false, Coq_true,
Coq_true, Coq_false, Coq_true, Coq_true, Coq_false)), (String
((Ascii (Coq_true, Coq_true, Coq_true, Coq_true, Coq_false,
Coq_true, Coq_true, Coq_false)), (String ((Ascii (Coq_true,
Coq_true, Coq_true, Coq_false, Coq_false, Coq_true, Coq_true,
Coq_false)), (String ((Ascii (Coq_false, Coq_false, Coq_false,
Coq_false, Coq_false, Coq_true, Coq_false, Coq_false)), (String
((Ascii (Coq_true, Coq_true, Coq_false, Coq_false, Coq_true,
Coq_true, Coq_true, Coq_false)), (String ((Ascii (Coq_false,
Coq_false, Coq_true, Coq_false, Coq_true, Coq_true, Coq_true,
Coq_false)), (String ((Ascii (Coq_true, Coq_false, Coq_false,
Coq_false, Coq_false, Coq_true, Coq_true, Coq_false)), (String
((Ascii (Coq_false, Coq_false, Coq_true, Coq_false, Coq_true,
Coq_true, Coq_true, Coq_false)), (String ((Ascii (Coq_true,
Coq_false, Coq_true, Coq_false, Coq_false, Coq_true, Coq_true,
Coq_false)), (String ((Ascii (Coq_true, Coq_false, Coq_true,
Coq_true, Coq_false, Coq_true, Coq_true, Coq_false)), (String
((Ascii (Coq_true, Coq_false, Coq_true, Coq_false, Coq_false,
Coq_true, Coq_true, Coq_false)), (String ((Ascii (Coq_false,
Coq_true, Coq_true, Coq_true, Coq_false, Coq_true, Coq_true,
Coq_false)), (String ((Ascii (Coq_false, Coq_false, Coq_true,
Coq_false, Coq_true, Coq_true, Coq_true, Coq_false)),
EmptyString)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))
| Srevert ->
append_compiled Coq_evm_revert
(append_compiled (Coq_evm_push Int256.zero)
(command_compiled (Coq_evm_push Int256.zero)))
| Scalldataload -> command_compiled Coq_evm_calldataload
| Sconstructordataload i -> constructor_data_load i
* code_compiled : code - > coq_Z PTree.t - > label - > compiled *
let rec code_compiled c ge code_label =
match c with
| Coq_nil -> empty_compiled
| Coq_cons (stm, rest) ->
let sc = stm_compiled stm ge code_label in
let rest0 = code_compiled rest ge code_label in
concatenate_compiled sc rest0
|
b12b9959bf9954b08e0fd88a7995814d7fbc434570e7695ae9e84025a2cce6cb | softwarelanguageslab/maf | R5RS_scp1_all-but-interval-3.scm | ; Changes:
* removed : 0
* added : 1
* swaps : 1
; * negated predicates: 0
* swapped branches : 1
; * calls to id fun: 0
(letrec ((all-but-interval (lambda (lst min max)
(letrec ((aux (lambda (last-smaller-cons aux-lst)
(if (null? aux-lst)
(set-cdr! last-smaller-cons ())
(if (< (car aux-lst) min)
(aux aux-lst (cdr aux-lst))
(if (> (car aux-lst) max)
(<change>
(set-cdr! last-smaller-cons aux-lst)
(aux last-smaller-cons (cdr aux-lst)))
(<change>
(aux last-smaller-cons (cdr aux-lst))
(set-cdr! last-smaller-cons aux-lst))))))))
(<change>
(aux lst lst)
lst)
(<change>
lst
(aux lst lst))))))
(<change>
()
(display
(__toplevel_cons
2
(__toplevel_cons 3 (__toplevel_cons 4 (__toplevel_cons 5 (__toplevel_cons 6 ())))))))
(if (equal? (all-but-interval (__toplevel_cons 1 (__toplevel_cons 2 (__toplevel_cons 3 (__toplevel_cons 4 (__toplevel_cons 5 (__toplevel_cons 6 ())))))) 2 4) (__toplevel_cons 1 (__toplevel_cons 5 (__toplevel_cons 6 ()))))
(if (equal? (all-but-interval (__toplevel_cons 1 (__toplevel_cons 2 (__toplevel_cons 3 (__toplevel_cons 4 (__toplevel_cons 5 ()))))) 2 2) (__toplevel_cons 1 (__toplevel_cons 3 (__toplevel_cons 4 (__toplevel_cons 5 ())))))
(equal?
(all-but-interval
(__toplevel_cons
1
(__toplevel_cons 2 (__toplevel_cons 5 (__toplevel_cons 6 (__toplevel_cons 7 ())))))
3
9)
(__toplevel_cons 1 (__toplevel_cons 2 ())))
#f)
#f)) | null | https://raw.githubusercontent.com/softwarelanguageslab/maf/11acedf56b9bf0c8e55ddb6aea754b6766d8bb40/test/changes/scheme/generated/R5RS_scp1_all-but-interval-3.scm | scheme | Changes:
* negated predicates: 0
* calls to id fun: 0 | * removed : 0
* added : 1
* swaps : 1
* swapped branches : 1
(letrec ((all-but-interval (lambda (lst min max)
(letrec ((aux (lambda (last-smaller-cons aux-lst)
(if (null? aux-lst)
(set-cdr! last-smaller-cons ())
(if (< (car aux-lst) min)
(aux aux-lst (cdr aux-lst))
(if (> (car aux-lst) max)
(<change>
(set-cdr! last-smaller-cons aux-lst)
(aux last-smaller-cons (cdr aux-lst)))
(<change>
(aux last-smaller-cons (cdr aux-lst))
(set-cdr! last-smaller-cons aux-lst))))))))
(<change>
(aux lst lst)
lst)
(<change>
lst
(aux lst lst))))))
(<change>
()
(display
(__toplevel_cons
2
(__toplevel_cons 3 (__toplevel_cons 4 (__toplevel_cons 5 (__toplevel_cons 6 ())))))))
(if (equal? (all-but-interval (__toplevel_cons 1 (__toplevel_cons 2 (__toplevel_cons 3 (__toplevel_cons 4 (__toplevel_cons 5 (__toplevel_cons 6 ())))))) 2 4) (__toplevel_cons 1 (__toplevel_cons 5 (__toplevel_cons 6 ()))))
(if (equal? (all-but-interval (__toplevel_cons 1 (__toplevel_cons 2 (__toplevel_cons 3 (__toplevel_cons 4 (__toplevel_cons 5 ()))))) 2 2) (__toplevel_cons 1 (__toplevel_cons 3 (__toplevel_cons 4 (__toplevel_cons 5 ())))))
(equal?
(all-but-interval
(__toplevel_cons
1
(__toplevel_cons 2 (__toplevel_cons 5 (__toplevel_cons 6 (__toplevel_cons 7 ())))))
3
9)
(__toplevel_cons 1 (__toplevel_cons 2 ())))
#f)
#f)) |
24ebf265308a8c32bf0e8cec2a95a572cb68b48e1de844d6006c6adf0df50a33 | metosin/tilakone | schema_test.clj | (ns tilakone.schema-test
(:require [clojure.test :refer :all]
[testit.core :refer :all]
[tilakone.core :as tk :refer [_]]
[tilakone.schema :as s]))
;;
;; Tests:
;;
(deftest validate-states-test
(fact "valid states data"
(s/validate-states [{::tk/name :a
::tk/enter {::tk/guards [:->a], ::tk/actions [:->a]}
::tk/stay {::tk/guards [:a], ::tk/actions [:a]}
::tk/leave {::tk/guards [:a->], ::tk/actions [:a->]}
::tk/transitions [{::tk/on \a, ::tk/to :a, ::tk/guards [:a->a], ::tk/actions [:a->a]}
{::tk/on \b, ::tk/to :b, ::tk/guards [:a->b], ::tk/actions [:a->b]}
{::tk/on _,, ::tk/to :c, ::tk/guards [:a->c], ::tk/actions [:a->c]}]}
{::tk/name :b
::tk/enter {::tk/guards [:->b], ::tk/actions [:->b]}
::tk/stay {::tk/guards [:b], ::tk/actions [:b]}
::tk/leave {::tk/guards [:b->], ::tk/actions [:b->]}
::tk/transitions [{::tk/on \a, ::tk/to :a, ::tk/guards [:b->a], ::tk/actions [:b->a]}
{::tk/on \b, ::tk/to :b, ::tk/guards [:b->b], ::tk/actions [:b->b]}]}
{::tk/name :c
::tk/enter {::tk/guards [:->c], ::tk/actions [:->c]}}])
=> truthy)
(fact "unknown target states"
(s/validate-states [{::tk/name :start
::tk/transitions [{::tk/to :found-a
::tk/on \a}]}
{::tk/name :found-a
::tk/transitions [{::tk/to :found-x}]}])
=throws=> (throws-ex-info "unknown target states: state [:found-a] has transition [anonymous] to unknown state [:found-x]"
{:type :tilakone.core/error
:errors [{::tk/state {::tk/name :found-a}
::tk/transition {::tk/to :found-x}}]})))
| null | https://raw.githubusercontent.com/metosin/tilakone/a6dd133557dbb5d64d9f4ef87e2ab073b3d86761/modules/schema/test/tilakone/schema_test.clj | clojure |
Tests:
| (ns tilakone.schema-test
(:require [clojure.test :refer :all]
[testit.core :refer :all]
[tilakone.core :as tk :refer [_]]
[tilakone.schema :as s]))
(deftest validate-states-test
(fact "valid states data"
(s/validate-states [{::tk/name :a
::tk/enter {::tk/guards [:->a], ::tk/actions [:->a]}
::tk/stay {::tk/guards [:a], ::tk/actions [:a]}
::tk/leave {::tk/guards [:a->], ::tk/actions [:a->]}
::tk/transitions [{::tk/on \a, ::tk/to :a, ::tk/guards [:a->a], ::tk/actions [:a->a]}
{::tk/on \b, ::tk/to :b, ::tk/guards [:a->b], ::tk/actions [:a->b]}
{::tk/on _,, ::tk/to :c, ::tk/guards [:a->c], ::tk/actions [:a->c]}]}
{::tk/name :b
::tk/enter {::tk/guards [:->b], ::tk/actions [:->b]}
::tk/stay {::tk/guards [:b], ::tk/actions [:b]}
::tk/leave {::tk/guards [:b->], ::tk/actions [:b->]}
::tk/transitions [{::tk/on \a, ::tk/to :a, ::tk/guards [:b->a], ::tk/actions [:b->a]}
{::tk/on \b, ::tk/to :b, ::tk/guards [:b->b], ::tk/actions [:b->b]}]}
{::tk/name :c
::tk/enter {::tk/guards [:->c], ::tk/actions [:->c]}}])
=> truthy)
(fact "unknown target states"
(s/validate-states [{::tk/name :start
::tk/transitions [{::tk/to :found-a
::tk/on \a}]}
{::tk/name :found-a
::tk/transitions [{::tk/to :found-x}]}])
=throws=> (throws-ex-info "unknown target states: state [:found-a] has transition [anonymous] to unknown state [:found-x]"
{:type :tilakone.core/error
:errors [{::tk/state {::tk/name :found-a}
::tk/transition {::tk/to :found-x}}]})))
|
f83917fec750b76ea1bf3d3aaf61447cfd7a1f021187d53139bf77367fd7d227 | haskell-suite/haskell-src-exts | OptionsPragma.hs | {-# OPTIONS -fno-warn-orphans #-}
| null | https://raw.githubusercontent.com/haskell-suite/haskell-src-exts/84a4930e0e5c051b7d9efd20ef7c822d5fc1c33b/tests/examples/OptionsPragma.hs | haskell | # OPTIONS -fno-warn-orphans # | |
f059560dd69313ba39400f95af8370bd70ece197dc986bbb7ebf0a5a2092a02b | openweb-nl/open-bank-mark | transaction_service.clj | (ns nl.openweb.graphql-endpoint.transaction-service
(:require [com.stuartsierra.component :as component]
[clojurewerkz.money.amounts :as ma]
[clojurewerkz.money.currencies :as cu]
[clojurewerkz.money.format :as fo]
[next.jdbc :as j]
[next.jdbc.sql :as sql]
[nl.openweb.topology.clients :as clients])
(:import (nl.openweb.data BalanceChanged)
(java.util Locale)))
(def bc-topic (or (System/getenv "KAFKA_BC_TOPIC") "balance_changed"))
(def client-id (or (System/getenv "KAFKA_CLIENT_ID") "graphql-endpoint-transactions"))
(def euro-c (cu/for-code "EUR"))
(def dutch-locale (Locale. "nl" "NL"))
(defn bc->sql-transaction
"id needs to be gotten from db and not class"
[^BalanceChanged bc]
(let [^long changed-by (.getChangedBy bc)]
{:iban (.getIban bc)
:new_balance (fo/format (ma/amount-of euro-c (/ (.getNewBalance bc) 100)) dutch-locale)
:changed_by (fo/format (ma/amount-of euro-c (/ (Math/abs changed-by) 100)) dutch-locale)
:from_to (.getFromTo bc)
:direction (if (< changed-by 0) "DEBIT" "CREDIT")
:descr (.getDescription bc)}))
(defn sql-transaction->graphql-transaction
([sql-map]
{:id (:transaction/id sql-map)
:iban (:transaction/iban sql-map)
:new_balance (:transaction/new_balance sql-map)
:changed_by (:transaction/changed_by sql-map)
:from_to (:transaction/from_to sql-map)
:direction (:transaction/direction sql-map)
:descr (:transaction/descr sql-map)})
([sql-map changed-by-long]
(assoc (sql-transaction->graphql-transaction sql-map) :cbl changed-by-long)))
(defn insert-transaction!
[datasource transaction]
(with-open [conn (j/get-connection datasource)]
(sql/insert! conn :transaction transaction)))
(defn add-bc
[cr datasource subscriptions]
(let [^BalanceChanged bc (.value cr)
sql-transaction (bc->sql-transaction bc)
sql-map (insert-transaction! datasource sql-transaction)
graphql-transaction (sql-transaction->graphql-transaction sql-map (.getChangedBy bc))]
(doseq [[filter-f source-stream] (vals (:map @subscriptions))]
(if (filter-f graphql-transaction)
(source-stream graphql-transaction)))))
(defrecord TransactionService []
component/Lifecycle
(start [this]
(let [subscriptions (atom {:id 0 :map {}})
stop-consume-f (clients/consume client-id client-id bc-topic #(add-bc % (get-in this [:db :datasource]) subscriptions))]
(-> this
(assoc :subscriptions subscriptions)
(assoc :stop-consume stop-consume-f))))
(stop [this]
((:stop-consume this))
(doseq [[_ source-stream] (vals (:map @(:subscriptions this)))]
(source-stream nil))
(-> this
(assoc :subscriptions nil)
(assoc :stop-consume nil))))
(defn new-service
[]
{:transaction-service (-> {}
map->TransactionService
(component/using [:db]))})
(defn find-transaction-by-id
[db id]
(if-let [sql-transaction (with-open [conn (j/get-connection (get-in db [:db :datasource]))]
(j/execute-one! conn ["SELECT * FROM transaction WHERE id = ?" id]))]
(sql-transaction->graphql-transaction sql-transaction)))
(defn find-transactions-by-iban
[db iban max-msg]
(if-let [sql-transactions (with-open [conn (j/get-connection (get-in db [:db :datasource]))]
(j/execute! conn ["SELECT * FROM transaction WHERE iban = ? ORDER BY id DESC LIMIT ?" iban max-msg]))]
(map sql-transaction->graphql-transaction sql-transactions)))
(defn find-all-last-transactions
[db]
(if-let [sql-transactions (with-open [conn (j/get-connection (get-in db [:db :datasource]))]
(j/execute! conn ["SELECT * FROM transaction WHERE id IN (SELECT MAX(id) FROM transaction GROUP BY iban) ORDER BY iban"]))]
(map sql-transaction->graphql-transaction sql-transactions)))
(defn add-stream
[subscriptions filter-f source-stream]
(let [new-id (inc (:id subscriptions))]
(-> subscriptions
(assoc :id new-id)
(assoc-in [:map new-id] [filter-f source-stream]))))
(defn create-transaction-subscription
[db source-stream iban min_amount direction]
(let [filter-f (fn [bc-map]
(cond
(and iban (not= iban (:iban bc-map))) false
(and min_amount (< (:cbl bc-map) min_amount)) false
(and direction (not= direction (:direction bc-map))) false
:else true))
subscriptions (swap! (:subscriptions db) add-stream filter-f source-stream)]
(:id subscriptions)))
(defn stop-transaction-subscription
[db id]
(let [source-stream (second (get (:map @(:subscriptions db)) id))]
(when source-stream
(source-stream nil)
(swap! (:subscriptions db) #(update % :map dissoc id))))) | null | https://raw.githubusercontent.com/openweb-nl/open-bank-mark/786c940dafb39c36fdbcae736fe893af9c00ef17/graphql-endpoint/src/nl/openweb/graphql_endpoint/transaction_service.clj | clojure | (ns nl.openweb.graphql-endpoint.transaction-service
(:require [com.stuartsierra.component :as component]
[clojurewerkz.money.amounts :as ma]
[clojurewerkz.money.currencies :as cu]
[clojurewerkz.money.format :as fo]
[next.jdbc :as j]
[next.jdbc.sql :as sql]
[nl.openweb.topology.clients :as clients])
(:import (nl.openweb.data BalanceChanged)
(java.util Locale)))
(def bc-topic (or (System/getenv "KAFKA_BC_TOPIC") "balance_changed"))
(def client-id (or (System/getenv "KAFKA_CLIENT_ID") "graphql-endpoint-transactions"))
(def euro-c (cu/for-code "EUR"))
(def dutch-locale (Locale. "nl" "NL"))
(defn bc->sql-transaction
"id needs to be gotten from db and not class"
[^BalanceChanged bc]
(let [^long changed-by (.getChangedBy bc)]
{:iban (.getIban bc)
:new_balance (fo/format (ma/amount-of euro-c (/ (.getNewBalance bc) 100)) dutch-locale)
:changed_by (fo/format (ma/amount-of euro-c (/ (Math/abs changed-by) 100)) dutch-locale)
:from_to (.getFromTo bc)
:direction (if (< changed-by 0) "DEBIT" "CREDIT")
:descr (.getDescription bc)}))
(defn sql-transaction->graphql-transaction
([sql-map]
{:id (:transaction/id sql-map)
:iban (:transaction/iban sql-map)
:new_balance (:transaction/new_balance sql-map)
:changed_by (:transaction/changed_by sql-map)
:from_to (:transaction/from_to sql-map)
:direction (:transaction/direction sql-map)
:descr (:transaction/descr sql-map)})
([sql-map changed-by-long]
(assoc (sql-transaction->graphql-transaction sql-map) :cbl changed-by-long)))
(defn insert-transaction!
[datasource transaction]
(with-open [conn (j/get-connection datasource)]
(sql/insert! conn :transaction transaction)))
(defn add-bc
[cr datasource subscriptions]
(let [^BalanceChanged bc (.value cr)
sql-transaction (bc->sql-transaction bc)
sql-map (insert-transaction! datasource sql-transaction)
graphql-transaction (sql-transaction->graphql-transaction sql-map (.getChangedBy bc))]
(doseq [[filter-f source-stream] (vals (:map @subscriptions))]
(if (filter-f graphql-transaction)
(source-stream graphql-transaction)))))
(defrecord TransactionService []
component/Lifecycle
(start [this]
(let [subscriptions (atom {:id 0 :map {}})
stop-consume-f (clients/consume client-id client-id bc-topic #(add-bc % (get-in this [:db :datasource]) subscriptions))]
(-> this
(assoc :subscriptions subscriptions)
(assoc :stop-consume stop-consume-f))))
(stop [this]
((:stop-consume this))
(doseq [[_ source-stream] (vals (:map @(:subscriptions this)))]
(source-stream nil))
(-> this
(assoc :subscriptions nil)
(assoc :stop-consume nil))))
(defn new-service
[]
{:transaction-service (-> {}
map->TransactionService
(component/using [:db]))})
(defn find-transaction-by-id
[db id]
(if-let [sql-transaction (with-open [conn (j/get-connection (get-in db [:db :datasource]))]
(j/execute-one! conn ["SELECT * FROM transaction WHERE id = ?" id]))]
(sql-transaction->graphql-transaction sql-transaction)))
(defn find-transactions-by-iban
[db iban max-msg]
(if-let [sql-transactions (with-open [conn (j/get-connection (get-in db [:db :datasource]))]
(j/execute! conn ["SELECT * FROM transaction WHERE iban = ? ORDER BY id DESC LIMIT ?" iban max-msg]))]
(map sql-transaction->graphql-transaction sql-transactions)))
(defn find-all-last-transactions
[db]
(if-let [sql-transactions (with-open [conn (j/get-connection (get-in db [:db :datasource]))]
(j/execute! conn ["SELECT * FROM transaction WHERE id IN (SELECT MAX(id) FROM transaction GROUP BY iban) ORDER BY iban"]))]
(map sql-transaction->graphql-transaction sql-transactions)))
(defn add-stream
[subscriptions filter-f source-stream]
(let [new-id (inc (:id subscriptions))]
(-> subscriptions
(assoc :id new-id)
(assoc-in [:map new-id] [filter-f source-stream]))))
(defn create-transaction-subscription
[db source-stream iban min_amount direction]
(let [filter-f (fn [bc-map]
(cond
(and iban (not= iban (:iban bc-map))) false
(and min_amount (< (:cbl bc-map) min_amount)) false
(and direction (not= direction (:direction bc-map))) false
:else true))
subscriptions (swap! (:subscriptions db) add-stream filter-f source-stream)]
(:id subscriptions)))
(defn stop-transaction-subscription
[db id]
(let [source-stream (second (get (:map @(:subscriptions db)) id))]
(when source-stream
(source-stream nil)
(swap! (:subscriptions db) #(update % :map dissoc id))))) | |
8dd01e5059e0cd35a9809911f41a18e3cad9991fed218ee091b2da0ebf6e1f9c | adzerk-oss/boot-test | test.clj | (ns adzerk.boot-test.test
(:use clojure.test))
(deftest have-you-tried
(is (= 1 1)))
| null | https://raw.githubusercontent.com/adzerk-oss/boot-test/a74ea6b7d3f26209cdc820f9f9dcfd951292aff3/src/adzerk/boot_test/test.clj | clojure | (ns adzerk.boot-test.test
(:use clojure.test))
(deftest have-you-tried
(is (= 1 1)))
| |
620c48fecb05d5190e859f0bf00529d5afce37f0f96973180135d58ff53649ab | clojure-interop/google-cloud-clients | TenantServiceStubSettings.clj | (ns com.google.cloud.talent.v4beta1.stub.TenantServiceStubSettings
"Settings class to configure an instance of TenantServiceStub.
The default instance has everything set to sensible defaults:
The default service address (jobs.googleapis.com) and default port (443) are used.
Credentials are acquired automatically through Application Default Credentials.
Retries are configured for idempotent methods but not for non-idempotent methods.
The builder of this class is recursive, so contained classes are themselves builders. When
build() is called, the tree of builders is called to create the complete settings object. For
example, to set the total timeout of createTenant to 30 seconds:
TenantServiceStubSettings.Builder tenantServiceSettingsBuilder =
TenantServiceStubSettings.newBuilder();
tenantServiceSettingsBuilder.createTenantSettings().getRetrySettings().toBuilder()
.setTotalTimeout(Duration.ofSeconds(30));
TenantServiceStubSettings tenantServiceSettings = tenantServiceSettingsBuilder.build();"
(:refer-clojure :only [require comment defn ->])
(:import [com.google.cloud.talent.v4beta1.stub TenantServiceStubSettings]))
(defn *default-executor-provider-builder
"Returns a builder for the default ExecutorProvider for this service.
returns: `com.google.api.gax.core.InstantiatingExecutorProvider.Builder`"
(^com.google.api.gax.core.InstantiatingExecutorProvider.Builder []
(TenantServiceStubSettings/defaultExecutorProviderBuilder )))
(defn *get-default-endpoint
"Returns the default service endpoint.
returns: `java.lang.String`"
(^java.lang.String []
(TenantServiceStubSettings/getDefaultEndpoint )))
(defn *get-default-service-scopes
"Returns the default service scopes.
returns: `java.util.List<java.lang.String>`"
(^java.util.List []
(TenantServiceStubSettings/getDefaultServiceScopes )))
(defn *default-credentials-provider-builder
"Returns a builder for the default credentials for this service.
returns: `com.google.api.gax.core.GoogleCredentialsProvider.Builder`"
(^com.google.api.gax.core.GoogleCredentialsProvider.Builder []
(TenantServiceStubSettings/defaultCredentialsProviderBuilder )))
(defn *default-grpc-transport-provider-builder
"Returns a builder for the default ChannelProvider for this service.
returns: `com.google.api.gax.grpc.InstantiatingGrpcChannelProvider.Builder`"
(^com.google.api.gax.grpc.InstantiatingGrpcChannelProvider.Builder []
(TenantServiceStubSettings/defaultGrpcTransportProviderBuilder )))
(defn *default-transport-channel-provider
"returns: `com.google.api.gax.rpc.TransportChannelProvider`"
(^com.google.api.gax.rpc.TransportChannelProvider []
(TenantServiceStubSettings/defaultTransportChannelProvider )))
(defn *default-api-client-header-provider-builder
"returns: `(value="The surface for customizing headers is not stable yet and may change in the future.") com.google.api.gax.rpc.ApiClientHeaderProvider.Builder`"
([]
(TenantServiceStubSettings/defaultApiClientHeaderProviderBuilder )))
(defn *new-builder
"Returns a new builder for this class.
client-context - `com.google.api.gax.rpc.ClientContext`
returns: `com.google.cloud.talent.v4beta1.stub.TenantServiceStubSettings$Builder`"
(^com.google.cloud.talent.v4beta1.stub.TenantServiceStubSettings$Builder [^com.google.api.gax.rpc.ClientContext client-context]
(TenantServiceStubSettings/newBuilder client-context))
(^com.google.cloud.talent.v4beta1.stub.TenantServiceStubSettings$Builder []
(TenantServiceStubSettings/newBuilder )))
(defn create-tenant-settings
"Returns the object with the settings used for calls to createTenant.
returns: `com.google.api.gax.rpc.UnaryCallSettings<com.google.cloud.talent.v4beta1.CreateTenantRequest,com.google.cloud.talent.v4beta1.Tenant>`"
(^com.google.api.gax.rpc.UnaryCallSettings [^TenantServiceStubSettings this]
(-> this (.createTenantSettings))))
(defn get-tenant-settings
"Returns the object with the settings used for calls to getTenant.
returns: `com.google.api.gax.rpc.UnaryCallSettings<com.google.cloud.talent.v4beta1.GetTenantRequest,com.google.cloud.talent.v4beta1.Tenant>`"
(^com.google.api.gax.rpc.UnaryCallSettings [^TenantServiceStubSettings this]
(-> this (.getTenantSettings))))
(defn update-tenant-settings
"Returns the object with the settings used for calls to updateTenant.
returns: `com.google.api.gax.rpc.UnaryCallSettings<com.google.cloud.talent.v4beta1.UpdateTenantRequest,com.google.cloud.talent.v4beta1.Tenant>`"
(^com.google.api.gax.rpc.UnaryCallSettings [^TenantServiceStubSettings this]
(-> this (.updateTenantSettings))))
(defn delete-tenant-settings
"Returns the object with the settings used for calls to deleteTenant.
returns: `com.google.api.gax.rpc.UnaryCallSettings<com.google.cloud.talent.v4beta1.DeleteTenantRequest,com.google.protobuf.Empty>`"
(^com.google.api.gax.rpc.UnaryCallSettings [^TenantServiceStubSettings this]
(-> this (.deleteTenantSettings))))
(defn list-tenants-settings
"Returns the object with the settings used for calls to listTenants.
returns: `com.google.api.gax.rpc.PagedCallSettings<com.google.cloud.talent.v4beta1.ListTenantsRequest,com.google.cloud.talent.v4beta1.ListTenantsResponse,com.google.cloud.talent.v4beta1.TenantServiceClient$ListTenantsPagedResponse>`"
(^com.google.api.gax.rpc.PagedCallSettings [^TenantServiceStubSettings this]
(-> this (.listTenantsSettings))))
(defn create-stub
"returns: `(value="A restructuring of stub classes is planned, so this may break in the future") com.google.cloud.talent.v4beta1.stub.TenantServiceStub`
throws: java.io.IOException"
([^TenantServiceStubSettings this]
(-> this (.createStub))))
(defn to-builder
"Returns a builder containing all the values of this settings class.
returns: `com.google.cloud.talent.v4beta1.stub.TenantServiceStubSettings$Builder`"
(^com.google.cloud.talent.v4beta1.stub.TenantServiceStubSettings$Builder [^TenantServiceStubSettings this]
(-> this (.toBuilder))))
| null | https://raw.githubusercontent.com/clojure-interop/google-cloud-clients/80852d0496057c22f9cdc86d6f9ffc0fa3cd7904/com.google.cloud.talent/src/com/google/cloud/talent/v4beta1/stub/TenantServiceStubSettings.clj | clojure |
" | (ns com.google.cloud.talent.v4beta1.stub.TenantServiceStubSettings
"Settings class to configure an instance of TenantServiceStub.
The default instance has everything set to sensible defaults:
The default service address (jobs.googleapis.com) and default port (443) are used.
Credentials are acquired automatically through Application Default Credentials.
Retries are configured for idempotent methods but not for non-idempotent methods.
The builder of this class is recursive, so contained classes are themselves builders. When
build() is called, the tree of builders is called to create the complete settings object. For
example, to set the total timeout of createTenant to 30 seconds:
TenantServiceStubSettings.Builder tenantServiceSettingsBuilder =
tenantServiceSettingsBuilder.createTenantSettings().getRetrySettings().toBuilder()
(:refer-clojure :only [require comment defn ->])
(:import [com.google.cloud.talent.v4beta1.stub TenantServiceStubSettings]))
(defn *default-executor-provider-builder
"Returns a builder for the default ExecutorProvider for this service.
returns: `com.google.api.gax.core.InstantiatingExecutorProvider.Builder`"
(^com.google.api.gax.core.InstantiatingExecutorProvider.Builder []
(TenantServiceStubSettings/defaultExecutorProviderBuilder )))
(defn *get-default-endpoint
"Returns the default service endpoint.
returns: `java.lang.String`"
(^java.lang.String []
(TenantServiceStubSettings/getDefaultEndpoint )))
(defn *get-default-service-scopes
"Returns the default service scopes.
returns: `java.util.List<java.lang.String>`"
(^java.util.List []
(TenantServiceStubSettings/getDefaultServiceScopes )))
(defn *default-credentials-provider-builder
"Returns a builder for the default credentials for this service.
returns: `com.google.api.gax.core.GoogleCredentialsProvider.Builder`"
(^com.google.api.gax.core.GoogleCredentialsProvider.Builder []
(TenantServiceStubSettings/defaultCredentialsProviderBuilder )))
(defn *default-grpc-transport-provider-builder
"Returns a builder for the default ChannelProvider for this service.
returns: `com.google.api.gax.grpc.InstantiatingGrpcChannelProvider.Builder`"
(^com.google.api.gax.grpc.InstantiatingGrpcChannelProvider.Builder []
(TenantServiceStubSettings/defaultGrpcTransportProviderBuilder )))
(defn *default-transport-channel-provider
"returns: `com.google.api.gax.rpc.TransportChannelProvider`"
(^com.google.api.gax.rpc.TransportChannelProvider []
(TenantServiceStubSettings/defaultTransportChannelProvider )))
(defn *default-api-client-header-provider-builder
"returns: `(value="The surface for customizing headers is not stable yet and may change in the future.") com.google.api.gax.rpc.ApiClientHeaderProvider.Builder`"
([]
(TenantServiceStubSettings/defaultApiClientHeaderProviderBuilder )))
(defn *new-builder
"Returns a new builder for this class.
client-context - `com.google.api.gax.rpc.ClientContext`
returns: `com.google.cloud.talent.v4beta1.stub.TenantServiceStubSettings$Builder`"
(^com.google.cloud.talent.v4beta1.stub.TenantServiceStubSettings$Builder [^com.google.api.gax.rpc.ClientContext client-context]
(TenantServiceStubSettings/newBuilder client-context))
(^com.google.cloud.talent.v4beta1.stub.TenantServiceStubSettings$Builder []
(TenantServiceStubSettings/newBuilder )))
(defn create-tenant-settings
"Returns the object with the settings used for calls to createTenant.
returns: `com.google.api.gax.rpc.UnaryCallSettings<com.google.cloud.talent.v4beta1.CreateTenantRequest,com.google.cloud.talent.v4beta1.Tenant>`"
(^com.google.api.gax.rpc.UnaryCallSettings [^TenantServiceStubSettings this]
(-> this (.createTenantSettings))))
(defn get-tenant-settings
"Returns the object with the settings used for calls to getTenant.
returns: `com.google.api.gax.rpc.UnaryCallSettings<com.google.cloud.talent.v4beta1.GetTenantRequest,com.google.cloud.talent.v4beta1.Tenant>`"
(^com.google.api.gax.rpc.UnaryCallSettings [^TenantServiceStubSettings this]
(-> this (.getTenantSettings))))
(defn update-tenant-settings
"Returns the object with the settings used for calls to updateTenant.
returns: `com.google.api.gax.rpc.UnaryCallSettings<com.google.cloud.talent.v4beta1.UpdateTenantRequest,com.google.cloud.talent.v4beta1.Tenant>`"
(^com.google.api.gax.rpc.UnaryCallSettings [^TenantServiceStubSettings this]
(-> this (.updateTenantSettings))))
(defn delete-tenant-settings
"Returns the object with the settings used for calls to deleteTenant.
returns: `com.google.api.gax.rpc.UnaryCallSettings<com.google.cloud.talent.v4beta1.DeleteTenantRequest,com.google.protobuf.Empty>`"
(^com.google.api.gax.rpc.UnaryCallSettings [^TenantServiceStubSettings this]
(-> this (.deleteTenantSettings))))
(defn list-tenants-settings
"Returns the object with the settings used for calls to listTenants.
returns: `com.google.api.gax.rpc.PagedCallSettings<com.google.cloud.talent.v4beta1.ListTenantsRequest,com.google.cloud.talent.v4beta1.ListTenantsResponse,com.google.cloud.talent.v4beta1.TenantServiceClient$ListTenantsPagedResponse>`"
(^com.google.api.gax.rpc.PagedCallSettings [^TenantServiceStubSettings this]
(-> this (.listTenantsSettings))))
(defn create-stub
"returns: `(value="A restructuring of stub classes is planned, so this may break in the future") com.google.cloud.talent.v4beta1.stub.TenantServiceStub`
throws: java.io.IOException"
([^TenantServiceStubSettings this]
(-> this (.createStub))))
(defn to-builder
"Returns a builder containing all the values of this settings class.
returns: `com.google.cloud.talent.v4beta1.stub.TenantServiceStubSettings$Builder`"
(^com.google.cloud.talent.v4beta1.stub.TenantServiceStubSettings$Builder [^TenantServiceStubSettings this]
(-> this (.toBuilder))))
|
c3f2e6fd8e9982f4901f13938b01ddf0049fafaaa0bfa2d6396abc12c9e06f65 | xh4/web-toolkit | header-field.lisp | (in-package :http)
(defgeneric header-field-name-match-p (header-field name))
(defclass header-field (field)
((name
:initarg :name
:initform nil
:accessor header-field-name)
(value
:initarg :value
:initform nil
:accessor header-field-value)))
(defmethod print-object ((header-field header-field) stream)
(print-unreadable-object (header-field stream :type t)
(format stream "~A: ~A"
(header-field-name header-field)
(header-field-value header-field))))
(defmethod initialize-instance :after ((header-field header-field) &key)
(setf (header-field-name header-field) (slot-value header-field 'name)
(header-field-value header-field) (slot-value header-field 'value)))
(defmethod (setf header-field-name) (name (header-field header-field))
(let ((name (typecase name
(string name)
(t (header-case (format nil "~A" name))))))
(setf (slot-value header-field 'name) name)))
(defmethod header-field-name ((header-field null))
nil)
(defmethod (setf header-field-value) (value (header-field header-field))
(let ((value (typecase value
(string value)
(t (format nil "~A" value)))))
(setf (slot-value header-field 'value) value)))
(defmethod header-field-value ((header-field null))
nil)
(defmethod header-field-name-match-p (header-field name)
(let ((name (typecase name
(string name)
(t (format nil "~A" name)))))
(string-equal name (header-field-name header-field))))
(defmacro header-field (name value)
`(make-instance 'header-field :name ,name :value ,value))
(defun read-header-field (stream &key (parse t))
(let ((line (read-line stream)))
(unless (emptyp line)
(if parse
(parse-header-field line)
line))))
(defun parse-header-field (line)
(let ((list (cl-ppcre:split ":" line :limit 2)))
(if (= 2 (length list))
(let ((name (first list))
(value (second list)))
(setf value (trim-whitespace value))
(make-instance 'header-field :name name :value value))
(error "Malformed header field"))))
(defgeneric write-header-field (stream header-field)
(:method (stream (header-field header-field))
(with-slots (name value) header-field
(let ((line (format nil "~A: ~A" name value)))
(write-sequence (babel:string-to-octets line) stream)
(write-sequence +crlf+ stream)
(+ (length line) (length +crlf+))))))
| null | https://raw.githubusercontent.com/xh4/web-toolkit/e510d44a25b36ca8acd66734ed1ee9f5fe6ecd09/http/header-field.lisp | lisp | (in-package :http)
(defgeneric header-field-name-match-p (header-field name))
(defclass header-field (field)
((name
:initarg :name
:initform nil
:accessor header-field-name)
(value
:initarg :value
:initform nil
:accessor header-field-value)))
(defmethod print-object ((header-field header-field) stream)
(print-unreadable-object (header-field stream :type t)
(format stream "~A: ~A"
(header-field-name header-field)
(header-field-value header-field))))
(defmethod initialize-instance :after ((header-field header-field) &key)
(setf (header-field-name header-field) (slot-value header-field 'name)
(header-field-value header-field) (slot-value header-field 'value)))
(defmethod (setf header-field-name) (name (header-field header-field))
(let ((name (typecase name
(string name)
(t (header-case (format nil "~A" name))))))
(setf (slot-value header-field 'name) name)))
(defmethod header-field-name ((header-field null))
nil)
(defmethod (setf header-field-value) (value (header-field header-field))
(let ((value (typecase value
(string value)
(t (format nil "~A" value)))))
(setf (slot-value header-field 'value) value)))
(defmethod header-field-value ((header-field null))
nil)
(defmethod header-field-name-match-p (header-field name)
(let ((name (typecase name
(string name)
(t (format nil "~A" name)))))
(string-equal name (header-field-name header-field))))
(defmacro header-field (name value)
`(make-instance 'header-field :name ,name :value ,value))
(defun read-header-field (stream &key (parse t))
(let ((line (read-line stream)))
(unless (emptyp line)
(if parse
(parse-header-field line)
line))))
(defun parse-header-field (line)
(let ((list (cl-ppcre:split ":" line :limit 2)))
(if (= 2 (length list))
(let ((name (first list))
(value (second list)))
(setf value (trim-whitespace value))
(make-instance 'header-field :name name :value value))
(error "Malformed header field"))))
(defgeneric write-header-field (stream header-field)
(:method (stream (header-field header-field))
(with-slots (name value) header-field
(let ((line (format nil "~A: ~A" name value)))
(write-sequence (babel:string-to-octets line) stream)
(write-sequence +crlf+ stream)
(+ (length line) (length +crlf+))))))
| |
2329b8a376cf7ea8b338030527d009597affb2b43baeccbd7d91c9a088f1b11b | craigl64/clim-ccl | cloe-implementation.lisp | -*- Mode : Lisp ; Syntax : ANSI - Common - Lisp ; Package : CLIM - INTERNALS ; Base : 10 ; Lowercase : Yes -*-
;;; Support for the shared class DC.
(defclass cloe-window-stream
(window-stream)
((window :initarg :window)
(move-pending :initform nil)
(event-width) (event-height)
(event-left) (event-top)
(margin-width) (margin-height)
(h-scroll-pos :initform nil)
(v-scroll-pos :initform nil)
(pending-scrolls :initform (make-queue))
(background-dc-image)
(foreground-dc-image)
(modifier-state :initform 0 :reader window-modifier-state)))
(defmethod initialize-instance :before ((stream cloe-window-stream) &key parent)
(setf (slot-value stream 'display-device-type)
(slot-value parent 'display-device-type)))
(defmethod initialize-instance :after ((stream cloe-window-stream) &key parent
label (scroll-bars :both) (borders t) save-under)
(with-slots (window left top right bottom margin-width margin-height
event-left event-top event-width event-height
foreground-dc-image background-dc-image)
stream
(let ((top-level (not (slot-exists-p parent 'window))))
(setf window (win::create-window
"Vanilla" (or label "CLIM")
(logior win::ws_clipchildren ;new, helps refresh
(if top-level
(if save-under
(logior win::ws_popup
win::ws_border)
(logior win::ws_overlapped
win::ws_caption
win::ws_thickframe
win::ws_sysmenu
win::ws_minimizebox
win::ws_maximizebox))
(logior win::ws_child
win::ws_clipsiblings
(if borders win::ws_border 0)))
(if (member scroll-bars '(:horizontal :both))
(progn (setf h-scroll-pos 0)
win::ws_hscroll)
0)
(if (member scroll-bars '(:vertical :both))
(progn (setf v-scroll-pos 0)
win::ws_vscroll)
0)
)
left top (- right left) (- bottom top)
(if top-level 0 (slot-value parent 'window)) 0 0 "arg")))
(associate-clim-window-with-host-window window stream)
(setf foreground-dc-image (dc-image-for-ink stream (medium-foreground stream)))
(setf background-dc-image (dc-image-for-ink stream (medium-background stream)))
(multiple-value-bind (cleft ctop cright cbottom)
(win::get-client-rectangle window)
(multiple-value-bind (wleft wtop wright wbottom)
(win::get-window-rectangle window)
(setf margin-width (- (- wright wleft) (- cright cleft)))
(setf margin-height (- (- wbottom wtop) (- cbottom ctop))))
(setf event-left (+ left cleft))
(setf event-top (+ top ctop))
(setf event-width (- cright cleft))
(setf event-height (- cbottom ctop))
(setf right (+ left event-width margin-width))
(setf bottom (+ top event-height margin-height)))
nil))
(defmethod implementation-pixels-per-point ((stream cloe-window-stream))
1)
(defmethod close ((stream cloe-window-stream) &key abort)
(declare (ignore abort))
(with-slots (window) stream
(win::destroy-window window)))
(defmethod (setf window-visibility) :after (visibility (stream cloe-window-stream))
(labels ((window-set-visibility-1 (stream visibility)
(win::show-window (slot-value stream 'window)
:type (if visibility :show-no-activate :hide))
(dolist (child (window-children stream))
(when (window-visibility child)
(window-set-visibility-1 child visibility)))))
(window-set-visibility-1 stream visibility))
(handle-generated-paints)
visibility)
(defmethod wait-for-window-exposed ((window cloe-window-stream))
(loop
(when (window-visibility window)
(return))
(process-yield)))
(defmethod window-stack-on-top ((stream cloe-window-stream))
(with-slots (window) stream
(win::set-window-position window 0 0 0 0 0
(logior win::swp_noactivate
win::swp_nomove
win::swp_nosize)))
(handle-generated-paints))
(defmethod window-stack-on-bottom ((stream cloe-window-stream))
(with-slots (window) stream
(win::set-window-position window 1 0 0 0 0
(logior win::swp_noactivate
win::swp_nomove
win::swp_nosize)))
(handle-generated-paints))
(defmethod bounding-rectangle-set-edges :after
((stream cloe-window-stream) left top right bottom)
(with-slots (window) stream
(win::move-window window left top (- right left) (- bottom top) t))
(handle-generated-paints))
(defmethod bounding-rectangle-set-position* :after
((stream cloe-window-stream) new-left new-top)
(multiple-value-bind (width height) (bounding-rectangle-size stream)
(with-slots (window) stream
(win::move-window window new-left new-top width height t)))
(handle-generated-paints))
(defmethod bounding-rectangle-set-size :after
((stream cloe-window-stream) width height)
(multiple-value-bind (left top) (bounding-rectangle-position* stream)
(with-slots (window) stream
(win::move-window window left top width height t)))
(handle-generated-paints))
;;;changed to fix the scrolling problem
(defmethod window-process-update-region ((stream cloe-window-stream))
(with-slots (window update-region background-dc-image) stream
(when update-region
(set-dc-for-filling background-dc-image)
(multiple-value-bind (dx dy)
(window-viewport-position* stream)
(declare (type coordinate dx dy))
(dolist (region update-region)
(with-bounding-rectangle* (left top right bottom) region
(win::rectangle window (- left dx) (- top dy)
(- right dx) (- bottom dy))))))))
Postpone better update region stuff .
(defmethod window-shift-visible-region :after ((stream cloe-window-stream)
old-left old-top old-right old-bottom
new-left new-top new-right new-bottom)
(setf (slot-value stream 'update-region)
(ltrb-difference new-left new-top new-right new-bottom
old-left old-top old-right old-bottom)))
;; Does this want to be an :after method? Will the primary method on
;; window-stream ever want to do anything else?
(defmethod stream-set-input-focus ((stream cloe-window-stream))
(with-slots (window) stream
(win::set-focus window)))
(defmethod stream-restore-input-focus ((stream cloe-window-stream) old-focus)
(declare (ignore stream))
(win::set-focus old-focus))
(defmethod stream-has-input-focus ((stream cloe-window-stream))
(with-slots (window) stream
(= window (win::get-focus))))
(defmethod notify-user-1 ((stream cloe-window-stream) frame format-string &rest format-args)
(declare (ignore frame) (dynamic-extent format-args))
(let ((formatted-string (apply #'format nil format-string format-args)))
(clos:with-slots (window) stream
(win::notify-user window formatted-string))))
;;; Scrolling support.
(defmethod cloe-recompute-scroll-bars ((stream cloe-window-stream))
;; don't update the scroll bars if they didn't change.
(multiple-value-bind (new-h-pos new-v-pos)
(let ((history (and (output-recording-stream-p stream)
(stream-output-history stream))))
(when history
(multiple-value-bind (width height) (bounding-rectangle-size history)
(with-bounding-rectangle* (vleft vtop vright vbottom) (window-viewport stream)
(values (and (< (- vright vleft) width)
(round (* vleft 100)
(- width (- vright vleft))))
(and (< (- vbottom vtop) height)
(round (* vtop 100)
(- height (- vbottom vtop)))))))))
(with-slots (window h-scroll-pos v-scroll-pos) stream
(unless (eql new-h-pos h-scroll-pos)
(cond ((null new-h-pos)
;;(win::show-scroll-bar window win::sb_horz nil)
(win::set-scroll-position window win::sb_horz new-h-pos))
(t
(win::set-scroll-position window win::sb_horz new-h-pos)
#||(when (null h-scroll-pos)
(win::show-scroll-bar window win::sb_horz t))||#))
(setf h-scroll-pos new-h-pos))
(unless (eql new-v-pos v-scroll-pos)
(cond ((null new-v-pos)
;;(win::show-scroll-bar window win::sb_vert nil)
(win::set-scroll-position window win::sb_vert new-v-pos))
(t
(win::set-scroll-position window win::sb_vert new-v-pos)
#||(when (null v-scroll-pos)
(win::show-scroll-bar window win::sb_vert t))||#))
(setf v-scroll-pos new-v-pos)))))
(defmethod window-set-viewport-position* :after ((stream cloe-window-stream) new-x new-y)
(cloe-recompute-scroll-bars stream))
| null | https://raw.githubusercontent.com/craigl64/clim-ccl/301efbd770745b429f2b00b4e8ca6624de9d9ea9/cloe/cloe-implementation.lisp | lisp | Syntax : ANSI - Common - Lisp ; Package : CLIM - INTERNALS ; Base : 10 ; Lowercase : Yes -*-
Support for the shared class DC.
new, helps refresh
changed to fix the scrolling problem
Does this want to be an :after method? Will the primary method on
window-stream ever want to do anything else?
Scrolling support.
don't update the scroll bars if they didn't change.
(win::show-scroll-bar window win::sb_horz nil)
(when (null h-scroll-pos)
(win::show-scroll-bar window win::sb_horz t))
(win::show-scroll-bar window win::sb_vert nil)
(when (null v-scroll-pos)
(win::show-scroll-bar window win::sb_vert t)) |
(defclass cloe-window-stream
(window-stream)
((window :initarg :window)
(move-pending :initform nil)
(event-width) (event-height)
(event-left) (event-top)
(margin-width) (margin-height)
(h-scroll-pos :initform nil)
(v-scroll-pos :initform nil)
(pending-scrolls :initform (make-queue))
(background-dc-image)
(foreground-dc-image)
(modifier-state :initform 0 :reader window-modifier-state)))
(defmethod initialize-instance :before ((stream cloe-window-stream) &key parent)
(setf (slot-value stream 'display-device-type)
(slot-value parent 'display-device-type)))
(defmethod initialize-instance :after ((stream cloe-window-stream) &key parent
label (scroll-bars :both) (borders t) save-under)
(with-slots (window left top right bottom margin-width margin-height
event-left event-top event-width event-height
foreground-dc-image background-dc-image)
stream
(let ((top-level (not (slot-exists-p parent 'window))))
(setf window (win::create-window
"Vanilla" (or label "CLIM")
(if top-level
(if save-under
(logior win::ws_popup
win::ws_border)
(logior win::ws_overlapped
win::ws_caption
win::ws_thickframe
win::ws_sysmenu
win::ws_minimizebox
win::ws_maximizebox))
(logior win::ws_child
win::ws_clipsiblings
(if borders win::ws_border 0)))
(if (member scroll-bars '(:horizontal :both))
(progn (setf h-scroll-pos 0)
win::ws_hscroll)
0)
(if (member scroll-bars '(:vertical :both))
(progn (setf v-scroll-pos 0)
win::ws_vscroll)
0)
)
left top (- right left) (- bottom top)
(if top-level 0 (slot-value parent 'window)) 0 0 "arg")))
(associate-clim-window-with-host-window window stream)
(setf foreground-dc-image (dc-image-for-ink stream (medium-foreground stream)))
(setf background-dc-image (dc-image-for-ink stream (medium-background stream)))
(multiple-value-bind (cleft ctop cright cbottom)
(win::get-client-rectangle window)
(multiple-value-bind (wleft wtop wright wbottom)
(win::get-window-rectangle window)
(setf margin-width (- (- wright wleft) (- cright cleft)))
(setf margin-height (- (- wbottom wtop) (- cbottom ctop))))
(setf event-left (+ left cleft))
(setf event-top (+ top ctop))
(setf event-width (- cright cleft))
(setf event-height (- cbottom ctop))
(setf right (+ left event-width margin-width))
(setf bottom (+ top event-height margin-height)))
nil))
(defmethod implementation-pixels-per-point ((stream cloe-window-stream))
1)
(defmethod close ((stream cloe-window-stream) &key abort)
(declare (ignore abort))
(with-slots (window) stream
(win::destroy-window window)))
(defmethod (setf window-visibility) :after (visibility (stream cloe-window-stream))
(labels ((window-set-visibility-1 (stream visibility)
(win::show-window (slot-value stream 'window)
:type (if visibility :show-no-activate :hide))
(dolist (child (window-children stream))
(when (window-visibility child)
(window-set-visibility-1 child visibility)))))
(window-set-visibility-1 stream visibility))
(handle-generated-paints)
visibility)
(defmethod wait-for-window-exposed ((window cloe-window-stream))
(loop
(when (window-visibility window)
(return))
(process-yield)))
(defmethod window-stack-on-top ((stream cloe-window-stream))
(with-slots (window) stream
(win::set-window-position window 0 0 0 0 0
(logior win::swp_noactivate
win::swp_nomove
win::swp_nosize)))
(handle-generated-paints))
(defmethod window-stack-on-bottom ((stream cloe-window-stream))
(with-slots (window) stream
(win::set-window-position window 1 0 0 0 0
(logior win::swp_noactivate
win::swp_nomove
win::swp_nosize)))
(handle-generated-paints))
(defmethod bounding-rectangle-set-edges :after
((stream cloe-window-stream) left top right bottom)
(with-slots (window) stream
(win::move-window window left top (- right left) (- bottom top) t))
(handle-generated-paints))
(defmethod bounding-rectangle-set-position* :after
((stream cloe-window-stream) new-left new-top)
(multiple-value-bind (width height) (bounding-rectangle-size stream)
(with-slots (window) stream
(win::move-window window new-left new-top width height t)))
(handle-generated-paints))
(defmethod bounding-rectangle-set-size :after
((stream cloe-window-stream) width height)
(multiple-value-bind (left top) (bounding-rectangle-position* stream)
(with-slots (window) stream
(win::move-window window left top width height t)))
(handle-generated-paints))
(defmethod window-process-update-region ((stream cloe-window-stream))
(with-slots (window update-region background-dc-image) stream
(when update-region
(set-dc-for-filling background-dc-image)
(multiple-value-bind (dx dy)
(window-viewport-position* stream)
(declare (type coordinate dx dy))
(dolist (region update-region)
(with-bounding-rectangle* (left top right bottom) region
(win::rectangle window (- left dx) (- top dy)
(- right dx) (- bottom dy))))))))
Postpone better update region stuff .
(defmethod window-shift-visible-region :after ((stream cloe-window-stream)
old-left old-top old-right old-bottom
new-left new-top new-right new-bottom)
(setf (slot-value stream 'update-region)
(ltrb-difference new-left new-top new-right new-bottom
old-left old-top old-right old-bottom)))
(defmethod stream-set-input-focus ((stream cloe-window-stream))
(with-slots (window) stream
(win::set-focus window)))
(defmethod stream-restore-input-focus ((stream cloe-window-stream) old-focus)
(declare (ignore stream))
(win::set-focus old-focus))
(defmethod stream-has-input-focus ((stream cloe-window-stream))
(with-slots (window) stream
(= window (win::get-focus))))
(defmethod notify-user-1 ((stream cloe-window-stream) frame format-string &rest format-args)
(declare (ignore frame) (dynamic-extent format-args))
(let ((formatted-string (apply #'format nil format-string format-args)))
(clos:with-slots (window) stream
(win::notify-user window formatted-string))))
(defmethod cloe-recompute-scroll-bars ((stream cloe-window-stream))
(multiple-value-bind (new-h-pos new-v-pos)
(let ((history (and (output-recording-stream-p stream)
(stream-output-history stream))))
(when history
(multiple-value-bind (width height) (bounding-rectangle-size history)
(with-bounding-rectangle* (vleft vtop vright vbottom) (window-viewport stream)
(values (and (< (- vright vleft) width)
(round (* vleft 100)
(- width (- vright vleft))))
(and (< (- vbottom vtop) height)
(round (* vtop 100)
(- height (- vbottom vtop)))))))))
(with-slots (window h-scroll-pos v-scroll-pos) stream
(unless (eql new-h-pos h-scroll-pos)
(cond ((null new-h-pos)
(win::set-scroll-position window win::sb_horz new-h-pos))
(t
(win::set-scroll-position window win::sb_horz new-h-pos)
(setf h-scroll-pos new-h-pos))
(unless (eql new-v-pos v-scroll-pos)
(cond ((null new-v-pos)
(win::set-scroll-position window win::sb_vert new-v-pos))
(t
(win::set-scroll-position window win::sb_vert new-v-pos)
(setf v-scroll-pos new-v-pos)))))
(defmethod window-set-viewport-position* :after ((stream cloe-window-stream) new-x new-y)
(cloe-recompute-scroll-bars stream))
|
bc0ecfccff4bd3d7e14d4da27c0a11b05087186c02e3ba96133234440c8d718e | lassik/upscheme | perf.scm | (load "test.scm")
(display "colorgraph: ")
(load "tcolor.scm")
(display "fib(34): ")
(assert (equal? (time (fib 34)) 5702887))
(display "yfib(32): ")
(assert (equal? (time (yfib 32)) 2178309))
(display "sort: ")
(set! r (map-int (lambda (x) (mod (+ (* x 9421) 12345) 1024)) 1000))
(time (simple-sort r))
(display "expand: ")
(time (dotimes (n 5000) (expand '(dotimes (i 100) body1 body2))))
(define (my-append . lsts)
(cond ((null? lsts) ())
((null? (cdr lsts)) (car lsts))
(else (letrec ((append2 (lambda (l d)
(if (null? l) d
(cons (car l)
(append2 (cdr l) d))))))
(append2 (car lsts) (apply my-append (cdr lsts)))))))
(display "append: ")
(set! L (map-int (lambda (x) (map-int identity 20)) 20))
(time (dotimes (n 1000) (apply my-append L)))
(path.cwd "ast")
(display "p-lambda: ")
(load "rpasses.scm")
(define *input* (load "datetimeR.scm"))
(time (set! *output* (compile-ish *input*)))
(assert (equal? *output* (load "rpasses-out.scm")))
(path.cwd "..")
| null | https://raw.githubusercontent.com/lassik/upscheme/61935bd866acb18902199bc4bc4cdd1760aa1ffc/scheme-tests/perf.scm | scheme | (load "test.scm")
(display "colorgraph: ")
(load "tcolor.scm")
(display "fib(34): ")
(assert (equal? (time (fib 34)) 5702887))
(display "yfib(32): ")
(assert (equal? (time (yfib 32)) 2178309))
(display "sort: ")
(set! r (map-int (lambda (x) (mod (+ (* x 9421) 12345) 1024)) 1000))
(time (simple-sort r))
(display "expand: ")
(time (dotimes (n 5000) (expand '(dotimes (i 100) body1 body2))))
(define (my-append . lsts)
(cond ((null? lsts) ())
((null? (cdr lsts)) (car lsts))
(else (letrec ((append2 (lambda (l d)
(if (null? l) d
(cons (car l)
(append2 (cdr l) d))))))
(append2 (car lsts) (apply my-append (cdr lsts)))))))
(display "append: ")
(set! L (map-int (lambda (x) (map-int identity 20)) 20))
(time (dotimes (n 1000) (apply my-append L)))
(path.cwd "ast")
(display "p-lambda: ")
(load "rpasses.scm")
(define *input* (load "datetimeR.scm"))
(time (set! *output* (compile-ish *input*)))
(assert (equal? *output* (load "rpasses-out.scm")))
(path.cwd "..")
| |
02e6fa776ac3e20c814d87677458b01930df2e8162fddcab06e72b3020ac9f5a | fujita-y/ypsilon | graphs.scm | GRAPHS -- Obtained from .
;;; ==== util.ss ====
Fold over list elements , associating to the left .
(define fold
(lambda (lst folder state)
( assert ( list ? lst )
; lst)
; (assert (procedure? folder)
; folder)
(do ((lst lst
(cdr lst))
(state state
(folder (car lst)
state)))
((null? lst)
state))))
; Given the size of a vector and a procedure which
sends indicies to desired vector elements , create
; and return the vector.
(define proc->vector
(lambda (size f)
; (assert (and (integer? size)
; (exact? size)
; (>= size 0))
; size)
; (assert (procedure? f)
; f)
(if (zero? size)
(vector)
(let ((x (make-vector size (f 0))))
(let loop ((i 1))
(if (< i size)
(begin
(vector-set! x i (f i))
(loop (+ i 1)))))
x))))
(define vector-fold
(lambda (vec folder state)
( assert ( vector ? )
)
; (assert (procedure? folder)
; folder)
(let ((len
(vector-length vec)))
(do ((i 0
(+ i 1))
(state state
(folder (vector-ref vec i)
state)))
((= i len)
state)))))
(define vector-map
(lambda (vec proc)
(proc->vector (vector-length vec)
(lambda (i)
(proc (vector-ref vec i))))))
Given limit , return the list 0 , 1 , ... , limit-1 .
(define giota
(lambda (limit)
; (assert (and (integer? limit)
; (exact? limit)
; (>= limit 0))
; limit)
(let -*-
((limit
limit)
(res
'()))
(if (zero? limit)
res
(let ((limit
(- limit 1)))
(-*- limit
(cons limit res)))))))
Fold over the integers [ 0 , limit ) .
(define gnatural-fold
(lambda (limit folder state)
; (assert (and (integer? limit)
; (exact? limit)
; (>= limit 0))
; limit)
; (assert (procedure? folder)
; folder)
(do ((i 0
(+ i 1))
(state state
(folder i state)))
((= i limit)
state))))
; Iterate over the integers [0, limit).
(define gnatural-for-each
(lambda (limit proc!)
; (assert (and (integer? limit)
; (exact? limit)
; (>= limit 0))
; limit)
; (assert (procedure? proc!)
; proc!)
(do ((i 0
(+ i 1)))
((= i limit))
(proc! i))))
(define natural-for-all?
(lambda (limit ok?)
; (assert (and (integer? limit)
; (exact? limit)
; (>= limit 0))
; limit)
; (assert (procedure? ok?)
; ok?)
(let -*-
((i 0))
(or (= i limit)
(and (ok? i)
(-*- (+ i 1)))))))
(define natural-there-exists?
(lambda (limit ok?)
; (assert (and (integer? limit)
; (exact? limit)
; (>= limit 0))
; limit)
; (assert (procedure? ok?)
; ok?)
(let -*-
((i 0))
(and (not (= i limit))
(or (ok? i)
(-*- (+ i 1)))))))
(define there-exists?
(lambda (lst ok?)
( assert ( list ? lst )
; lst)
; (assert (procedure? ok?)
; ok?)
(let -*-
((lst lst))
(and (not (null? lst))
(or (ok? (car lst))
(-*- (cdr lst)))))))
;;; ==== ptfold.ss ====
Fold over the tree of permutations of a universe .
; Each branch (from the root) is a permutation of universe.
; Each node at depth d corresponds to all permutations which pick the
; elements spelled out on the branch from the root to that node as
the first d elements .
Their are two components to the state :
; The b-state is only a function of the branch from the root.
; The t-state is a function of all nodes seen so far.
; At each node, b-folder is called via
; (b-folder elem b-state t-state deeper accross)
; where elem is the next element of the universe picked.
; If b-folder can determine the result of the total tree fold at this stage,
; it should simply return the result.
; If b-folder can determine the result of folding over the sub-tree
; rooted at the resulting node, it should call accross via
; (accross new-t-state)
; where new-t-state is that result.
; Otherwise, b-folder should call deeper via
; (deeper new-b-state new-t-state)
; where new-b-state is the b-state for the new node and new-t-state is
; the new folded t-state.
; At the leaves of the tree, t-folder is called via
; (t-folder b-state t-state accross)
; If t-folder can determine the result of the total tree fold at this stage,
; it should simply return that result.
; If not, it should call accross via
; (accross new-t-state)
Note , fold - over - perm - tree always calls b - folder in depth - first order .
; I.e., when b-folder is called at depth d, the branch leading to that
node is the most recent calls to b - folder at all the depths less than d.
; This is a gross efficiency hack so that b-folder can use mutation to
; keep the current branch.
(define fold-over-perm-tree
(lambda (universe b-folder b-state t-folder t-state)
; (assert (list? universe)
; universe)
; (assert (procedure? b-folder)
; b-folder)
; (assert (procedure? t-folder)
; t-folder)
(let -*-
((universe
universe)
(b-state
b-state)
(t-state
t-state)
(accross
(lambda (final-t-state)
final-t-state)))
(if (null? universe)
(t-folder b-state t-state accross)
(let -**-
((in
universe)
(out
'())
(t-state
t-state))
(let* ((first
(car in))
(rest
(cdr in))
(accross
(if (null? rest)
accross
(lambda (new-t-state)
(-**- rest
(cons first out)
new-t-state)))))
(b-folder first
b-state
t-state
(lambda (new-b-state new-t-state)
(-*- (fold out cons rest)
new-b-state
new-t-state
accross))
accross)))))))
;;; ==== minimal.ss ====
; A directed graph is stored as a connection matrix (vector-of-vectors)
where the first index is the ` from ' vertex and the second is the ` to '
; vertex. Each entry is a bool indicating if the edge exists.
; The diagonal of the matrix is never examined.
; Make-minimal? returns a procedure which tests if a labelling
; of the verticies is such that the matrix is minimal.
; If it is, then the procedure returns the result of folding over
the elements of the automoriphism group . If not , it returns # f.
; The folding is done by calling folder via
; (folder perm state accross)
; If the folder wants to continue, it should call accross via
; (accross new-state)
; If it just wants the entire minimal? procedure to return something,
; it should return that.
; The ordering used is lexicographic (with #t > #f) and entries
; are examined in the following order:
1->0 , 0->1
;
; 2->0, 0->2
2->1 , 1->2
;
; 3->0, 0->3
3->1 , 1->3
3->2 , 2->3
; ...
(define make-minimal?
(lambda (max-size)
; (assert (and (integer? max-size)
; (exact? max-size)
; (>= max-size 0))
; max-size)
(let ((iotas
(proc->vector (+ max-size 1)
giota))
(perm
(make-vector max-size 0)))
(lambda (size graph folder state)
; (assert (and (integer? size)
; (exact? size)
; (<= 0 size max-size))
; size
; max-size)
; (assert (vector? graph)
; graph)
; (assert (procedure? folder)
; folder)
(fold-over-perm-tree (vector-ref iotas size)
(lambda (perm-x x state deeper accross)
(case (cmp-next-vertex graph perm x perm-x)
((less)
#f)
((equal)
(vector-set! perm x perm-x)
(deeper (+ x 1)
state))
((more)
(accross state))
(else
; (assert #f)
(fatal-error "???"))))
0
(lambda (leaf-depth state accross)
; (assert (eqv? leaf-depth size)
; leaf-depth
; size)
(folder perm state accross))
state)))))
; Given a graph, a partial permutation vector, the next input and the next
; output, return 'less, 'equal or 'more depending on the lexicographic
comparison between the permuted and un - permuted graph .
(define cmp-next-vertex
(lambda (graph perm x perm-x)
(let ((from-x
(vector-ref graph x))
(from-perm-x
(vector-ref graph perm-x)))
(let -*-
((y
0))
(if (= x y)
'equal
(let ((x->y?
(vector-ref from-x y))
(perm-y
(vector-ref perm y)))
(cond ((eq? x->y?
(vector-ref from-perm-x perm-y))
(let ((y->x?
(vector-ref (vector-ref graph y)
x)))
(cond ((eq? y->x?
(vector-ref (vector-ref graph perm-y)
perm-x))
(-*- (+ y 1)))
(y->x?
'less)
(else
'more))))
(x->y?
'less)
(else
'more))))))))
;;; ==== rdg.ss ====
Fold over rooted directed graphs with bounded out - degree .
Size is the number of verticies ( including the root ) . - out is the
; maximum out-degree for any vertex. Folder is called via
; (folder edges state)
; where edges is a list of length size. The ith element of the list is
; a list of the verticies j for which there is an edge from i to j.
; The last vertex is the root.
(define fold-over-rdg
(lambda (size max-out folder state)
; (assert (and (exact? size)
; (integer? size)
; (> size 0))
; size)
; (assert (and (exact? max-out)
; (integer? max-out)
; (>= max-out 0))
- out )
; (assert (procedure? folder)
; folder)
(let* ((root
(- size 1))
(edge?
(proc->vector size
(lambda (from)
(make-vector size #f))))
(edges
(make-vector size '()))
(out-degrees
(make-vector size 0))
(minimal-folder
(make-minimal? root))
(non-root-minimal?
(let ((cont
(lambda (perm state accross)
; (assert (eq? state #t)
; state)
(accross #t))))
(lambda (size)
(minimal-folder size
edge?
cont
#t))))
(root-minimal?
(let ((cont
(lambda (perm state accross)
; (assert (eq? state #t)
; state)
(case (cmp-next-vertex edge? perm root root)
((less)
#f)
((equal more)
(accross #t))
(else
; (assert #f)
(fatal-error "???"))))))
(lambda ()
(minimal-folder root
edge?
cont
#t)))))
(let -*-
((vertex
0)
(state
state))
(cond ((not (non-root-minimal? vertex))
state)
((= vertex root)
; (assert
; (begin
; (gnatural-for-each root
; (lambda (v)
; (assert (= (vector-ref out-degrees v)
; (length (vector-ref edges v)))
; v
; (vector-ref out-degrees v)
; (vector-ref edges v))))
; #t))
(let ((reach?
(make-reach? root edges))
(from-root
(vector-ref edge? root)))
(let -*-
((v
0)
(outs
0)
(efr
'())
(efrr
'())
(state
state))
(cond ((not (or (= v root)
(= outs max-out)))
(vector-set! from-root v #t)
(let ((state
(-*- (+ v 1)
(+ outs 1)
(cons v efr)
(cons (vector-ref reach? v)
efrr)
state)))
(vector-set! from-root v #f)
(-*- (+ v 1)
outs
efr
efrr
state)))
((and (natural-for-all? root
(lambda (v)
(there-exists? efrr
(lambda (r)
(vector-ref r v)))))
(root-minimal?))
(vector-set! edges root efr)
(folder
(proc->vector size
(lambda (i)
(vector-ref edges i)))
state))
(else
state)))))
(else
(let ((from-vertex
(vector-ref edge? vertex)))
(let -**-
((sv
0)
(outs
0)
(state
state))
(if (= sv vertex)
(begin
(vector-set! out-degrees vertex outs)
(-*- (+ vertex 1)
state))
(let* ((state
; no sv->vertex, no vertex->sv
(-**- (+ sv 1)
outs
state))
(from-sv
(vector-ref edge? sv))
(sv-out
(vector-ref out-degrees sv))
(state
(if (= sv-out max-out)
state
(begin
(vector-set! edges
sv
(cons vertex
(vector-ref edges sv)))
(vector-set! from-sv vertex #t)
(vector-set! out-degrees sv (+ sv-out 1))
(let* ((state
; sv->vertex, no vertex->sv
(-**- (+ sv 1)
outs
state))
(state
(if (= outs max-out)
state
(begin
(vector-set! from-vertex sv #t)
(vector-set! edges
vertex
(cons sv
(vector-ref edges vertex)))
(let ((state
; sv->vertex, vertex->sv
(-**- (+ sv 1)
(+ outs 1)
state)))
(vector-set! edges
vertex
(cdr (vector-ref edges vertex)))
(vector-set! from-vertex sv #f)
state)))))
(vector-set! out-degrees sv sv-out)
(vector-set! from-sv vertex #f)
(vector-set! edges
sv
(cdr (vector-ref edges sv)))
state)))))
(if (= outs max-out)
state
(begin
(vector-set! edges
vertex
(cons sv
(vector-ref edges vertex)))
(vector-set! from-vertex sv #t)
(let ((state
; no sv->vertex, vertex->sv
(-**- (+ sv 1)
(+ outs 1)
state)))
(vector-set! from-vertex sv #f)
(vector-set! edges
vertex
(cdr (vector-ref edges vertex)))
state)))))))))))))
; Given a vector which maps vertex to out-going-edge list,
; return a vector which gives reachability.
(define make-reach?
(lambda (size vertex->out)
(let ((res
(proc->vector size
(lambda (v)
(let ((from-v
(make-vector size #f)))
(vector-set! from-v v #t)
(for-each
(lambda (x)
(vector-set! from-v x #t))
(vector-ref vertex->out v))
from-v)))))
(gnatural-for-each size
(lambda (m)
(let ((from-m
(vector-ref res m)))
(gnatural-for-each size
(lambda (f)
(let ((from-f
(vector-ref res f)))
(if (vector-ref from-f m)
(gnatural-for-each size
(lambda (t)
(if (vector-ref from-m t)
(vector-set! from-f t #t)))))))))))
res)))
;;; ==== test input ====
; Produces all directed graphs with N verticies, distinguished root,
and out - degree bounded by 2 , upto isomorphism .
(define (run n)
(fold-over-rdg n
2
cons
'()))
(define (main)
(run-benchmark
"graphs"
graphs-iters
(lambda (result) (equal? (length result) 596))
(lambda (n) (lambda () (run n)))
5))
| null | https://raw.githubusercontent.com/fujita-y/ypsilon/820aa1b0258eb1854172c7909aef7462bb0e2adb/bench/gambit-benchmarks/graphs.scm | scheme | ==== util.ss ====
lst)
(assert (procedure? folder)
folder)
Given the size of a vector and a procedure which
and return the vector.
(assert (and (integer? size)
(exact? size)
(>= size 0))
size)
(assert (procedure? f)
f)
(assert (procedure? folder)
folder)
(assert (and (integer? limit)
(exact? limit)
(>= limit 0))
limit)
(assert (and (integer? limit)
(exact? limit)
(>= limit 0))
limit)
(assert (procedure? folder)
folder)
Iterate over the integers [0, limit).
(assert (and (integer? limit)
(exact? limit)
(>= limit 0))
limit)
(assert (procedure? proc!)
proc!)
(assert (and (integer? limit)
(exact? limit)
(>= limit 0))
limit)
(assert (procedure? ok?)
ok?)
(assert (and (integer? limit)
(exact? limit)
(>= limit 0))
limit)
(assert (procedure? ok?)
ok?)
lst)
(assert (procedure? ok?)
ok?)
==== ptfold.ss ====
Each branch (from the root) is a permutation of universe.
Each node at depth d corresponds to all permutations which pick the
elements spelled out on the branch from the root to that node as
The b-state is only a function of the branch from the root.
The t-state is a function of all nodes seen so far.
At each node, b-folder is called via
(b-folder elem b-state t-state deeper accross)
where elem is the next element of the universe picked.
If b-folder can determine the result of the total tree fold at this stage,
it should simply return the result.
If b-folder can determine the result of folding over the sub-tree
rooted at the resulting node, it should call accross via
(accross new-t-state)
where new-t-state is that result.
Otherwise, b-folder should call deeper via
(deeper new-b-state new-t-state)
where new-b-state is the b-state for the new node and new-t-state is
the new folded t-state.
At the leaves of the tree, t-folder is called via
(t-folder b-state t-state accross)
If t-folder can determine the result of the total tree fold at this stage,
it should simply return that result.
If not, it should call accross via
(accross new-t-state)
I.e., when b-folder is called at depth d, the branch leading to that
This is a gross efficiency hack so that b-folder can use mutation to
keep the current branch.
(assert (list? universe)
universe)
(assert (procedure? b-folder)
b-folder)
(assert (procedure? t-folder)
t-folder)
==== minimal.ss ====
A directed graph is stored as a connection matrix (vector-of-vectors)
vertex. Each entry is a bool indicating if the edge exists.
The diagonal of the matrix is never examined.
Make-minimal? returns a procedure which tests if a labelling
of the verticies is such that the matrix is minimal.
If it is, then the procedure returns the result of folding over
The folding is done by calling folder via
(folder perm state accross)
If the folder wants to continue, it should call accross via
(accross new-state)
If it just wants the entire minimal? procedure to return something,
it should return that.
The ordering used is lexicographic (with #t > #f) and entries
are examined in the following order:
2->0, 0->2
3->0, 0->3
...
(assert (and (integer? max-size)
(exact? max-size)
(>= max-size 0))
max-size)
(assert (and (integer? size)
(exact? size)
(<= 0 size max-size))
size
max-size)
(assert (vector? graph)
graph)
(assert (procedure? folder)
folder)
(assert #f)
(assert (eqv? leaf-depth size)
leaf-depth
size)
Given a graph, a partial permutation vector, the next input and the next
output, return 'less, 'equal or 'more depending on the lexicographic
==== rdg.ss ====
maximum out-degree for any vertex. Folder is called via
(folder edges state)
where edges is a list of length size. The ith element of the list is
a list of the verticies j for which there is an edge from i to j.
The last vertex is the root.
(assert (and (exact? size)
(integer? size)
(> size 0))
size)
(assert (and (exact? max-out)
(integer? max-out)
(>= max-out 0))
(assert (procedure? folder)
folder)
(assert (eq? state #t)
state)
(assert (eq? state #t)
state)
(assert #f)
(assert
(begin
(gnatural-for-each root
(lambda (v)
(assert (= (vector-ref out-degrees v)
(length (vector-ref edges v)))
v
(vector-ref out-degrees v)
(vector-ref edges v))))
#t))
no sv->vertex, no vertex->sv
sv->vertex, no vertex->sv
sv->vertex, vertex->sv
no sv->vertex, vertex->sv
Given a vector which maps vertex to out-going-edge list,
return a vector which gives reachability.
==== test input ====
Produces all directed graphs with N verticies, distinguished root, | GRAPHS -- Obtained from .
Fold over list elements , associating to the left .
(define fold
(lambda (lst folder state)
( assert ( list ? lst )
(do ((lst lst
(cdr lst))
(state state
(folder (car lst)
state)))
((null? lst)
state))))
sends indicies to desired vector elements , create
(define proc->vector
(lambda (size f)
(if (zero? size)
(vector)
(let ((x (make-vector size (f 0))))
(let loop ((i 1))
(if (< i size)
(begin
(vector-set! x i (f i))
(loop (+ i 1)))))
x))))
(define vector-fold
(lambda (vec folder state)
( assert ( vector ? )
)
(let ((len
(vector-length vec)))
(do ((i 0
(+ i 1))
(state state
(folder (vector-ref vec i)
state)))
((= i len)
state)))))
(define vector-map
(lambda (vec proc)
(proc->vector (vector-length vec)
(lambda (i)
(proc (vector-ref vec i))))))
Given limit , return the list 0 , 1 , ... , limit-1 .
(define giota
(lambda (limit)
(let -*-
((limit
limit)
(res
'()))
(if (zero? limit)
res
(let ((limit
(- limit 1)))
(-*- limit
(cons limit res)))))))
Fold over the integers [ 0 , limit ) .
(define gnatural-fold
(lambda (limit folder state)
(do ((i 0
(+ i 1))
(state state
(folder i state)))
((= i limit)
state))))
(define gnatural-for-each
(lambda (limit proc!)
(do ((i 0
(+ i 1)))
((= i limit))
(proc! i))))
(define natural-for-all?
(lambda (limit ok?)
(let -*-
((i 0))
(or (= i limit)
(and (ok? i)
(-*- (+ i 1)))))))
(define natural-there-exists?
(lambda (limit ok?)
(let -*-
((i 0))
(and (not (= i limit))
(or (ok? i)
(-*- (+ i 1)))))))
(define there-exists?
(lambda (lst ok?)
( assert ( list ? lst )
(let -*-
((lst lst))
(and (not (null? lst))
(or (ok? (car lst))
(-*- (cdr lst)))))))
Fold over the tree of permutations of a universe .
the first d elements .
Their are two components to the state :
Note , fold - over - perm - tree always calls b - folder in depth - first order .
node is the most recent calls to b - folder at all the depths less than d.
(define fold-over-perm-tree
(lambda (universe b-folder b-state t-folder t-state)
(let -*-
((universe
universe)
(b-state
b-state)
(t-state
t-state)
(accross
(lambda (final-t-state)
final-t-state)))
(if (null? universe)
(t-folder b-state t-state accross)
(let -**-
((in
universe)
(out
'())
(t-state
t-state))
(let* ((first
(car in))
(rest
(cdr in))
(accross
(if (null? rest)
accross
(lambda (new-t-state)
(-**- rest
(cons first out)
new-t-state)))))
(b-folder first
b-state
t-state
(lambda (new-b-state new-t-state)
(-*- (fold out cons rest)
new-b-state
new-t-state
accross))
accross)))))))
where the first index is the ` from ' vertex and the second is the ` to '
the elements of the automoriphism group . If not , it returns # f.
1->0 , 0->1
2->1 , 1->2
3->1 , 1->3
3->2 , 2->3
(define make-minimal?
(lambda (max-size)
(let ((iotas
(proc->vector (+ max-size 1)
giota))
(perm
(make-vector max-size 0)))
(lambda (size graph folder state)
(fold-over-perm-tree (vector-ref iotas size)
(lambda (perm-x x state deeper accross)
(case (cmp-next-vertex graph perm x perm-x)
((less)
#f)
((equal)
(vector-set! perm x perm-x)
(deeper (+ x 1)
state))
((more)
(accross state))
(else
(fatal-error "???"))))
0
(lambda (leaf-depth state accross)
(folder perm state accross))
state)))))
comparison between the permuted and un - permuted graph .
(define cmp-next-vertex
(lambda (graph perm x perm-x)
(let ((from-x
(vector-ref graph x))
(from-perm-x
(vector-ref graph perm-x)))
(let -*-
((y
0))
(if (= x y)
'equal
(let ((x->y?
(vector-ref from-x y))
(perm-y
(vector-ref perm y)))
(cond ((eq? x->y?
(vector-ref from-perm-x perm-y))
(let ((y->x?
(vector-ref (vector-ref graph y)
x)))
(cond ((eq? y->x?
(vector-ref (vector-ref graph perm-y)
perm-x))
(-*- (+ y 1)))
(y->x?
'less)
(else
'more))))
(x->y?
'less)
(else
'more))))))))
Fold over rooted directed graphs with bounded out - degree .
Size is the number of verticies ( including the root ) . - out is the
(define fold-over-rdg
(lambda (size max-out folder state)
- out )
(let* ((root
(- size 1))
(edge?
(proc->vector size
(lambda (from)
(make-vector size #f))))
(edges
(make-vector size '()))
(out-degrees
(make-vector size 0))
(minimal-folder
(make-minimal? root))
(non-root-minimal?
(let ((cont
(lambda (perm state accross)
(accross #t))))
(lambda (size)
(minimal-folder size
edge?
cont
#t))))
(root-minimal?
(let ((cont
(lambda (perm state accross)
(case (cmp-next-vertex edge? perm root root)
((less)
#f)
((equal more)
(accross #t))
(else
(fatal-error "???"))))))
(lambda ()
(minimal-folder root
edge?
cont
#t)))))
(let -*-
((vertex
0)
(state
state))
(cond ((not (non-root-minimal? vertex))
state)
((= vertex root)
(let ((reach?
(make-reach? root edges))
(from-root
(vector-ref edge? root)))
(let -*-
((v
0)
(outs
0)
(efr
'())
(efrr
'())
(state
state))
(cond ((not (or (= v root)
(= outs max-out)))
(vector-set! from-root v #t)
(let ((state
(-*- (+ v 1)
(+ outs 1)
(cons v efr)
(cons (vector-ref reach? v)
efrr)
state)))
(vector-set! from-root v #f)
(-*- (+ v 1)
outs
efr
efrr
state)))
((and (natural-for-all? root
(lambda (v)
(there-exists? efrr
(lambda (r)
(vector-ref r v)))))
(root-minimal?))
(vector-set! edges root efr)
(folder
(proc->vector size
(lambda (i)
(vector-ref edges i)))
state))
(else
state)))))
(else
(let ((from-vertex
(vector-ref edge? vertex)))
(let -**-
((sv
0)
(outs
0)
(state
state))
(if (= sv vertex)
(begin
(vector-set! out-degrees vertex outs)
(-*- (+ vertex 1)
state))
(let* ((state
(-**- (+ sv 1)
outs
state))
(from-sv
(vector-ref edge? sv))
(sv-out
(vector-ref out-degrees sv))
(state
(if (= sv-out max-out)
state
(begin
(vector-set! edges
sv
(cons vertex
(vector-ref edges sv)))
(vector-set! from-sv vertex #t)
(vector-set! out-degrees sv (+ sv-out 1))
(let* ((state
(-**- (+ sv 1)
outs
state))
(state
(if (= outs max-out)
state
(begin
(vector-set! from-vertex sv #t)
(vector-set! edges
vertex
(cons sv
(vector-ref edges vertex)))
(let ((state
(-**- (+ sv 1)
(+ outs 1)
state)))
(vector-set! edges
vertex
(cdr (vector-ref edges vertex)))
(vector-set! from-vertex sv #f)
state)))))
(vector-set! out-degrees sv sv-out)
(vector-set! from-sv vertex #f)
(vector-set! edges
sv
(cdr (vector-ref edges sv)))
state)))))
(if (= outs max-out)
state
(begin
(vector-set! edges
vertex
(cons sv
(vector-ref edges vertex)))
(vector-set! from-vertex sv #t)
(let ((state
(-**- (+ sv 1)
(+ outs 1)
state)))
(vector-set! from-vertex sv #f)
(vector-set! edges
vertex
(cdr (vector-ref edges vertex)))
state)))))))))))))
(define make-reach?
(lambda (size vertex->out)
(let ((res
(proc->vector size
(lambda (v)
(let ((from-v
(make-vector size #f)))
(vector-set! from-v v #t)
(for-each
(lambda (x)
(vector-set! from-v x #t))
(vector-ref vertex->out v))
from-v)))))
(gnatural-for-each size
(lambda (m)
(let ((from-m
(vector-ref res m)))
(gnatural-for-each size
(lambda (f)
(let ((from-f
(vector-ref res f)))
(if (vector-ref from-f m)
(gnatural-for-each size
(lambda (t)
(if (vector-ref from-m t)
(vector-set! from-f t #t)))))))))))
res)))
and out - degree bounded by 2 , upto isomorphism .
(define (run n)
(fold-over-rdg n
2
cons
'()))
(define (main)
(run-benchmark
"graphs"
graphs-iters
(lambda (result) (equal? (length result) 596))
(lambda (n) (lambda () (run n)))
5))
|
0902434140be41eebbc39b87f3effe63de9d2c68cca8774560b46ec3155e01a1 | schwering/golog | Car.hs | module RSTC.Car where
import Data.Ix
import System.IO.Unsafe
data Lane = LeftLane | RightLane deriving (Eq, Enum, Show)
data Car = A | B | C | D | E | F | G | H deriving (Bounded, Enum, Eq, Ix, Ord, Show)
cars :: [Car]
--cars = [B .. H]
--cars = [D,H]
cars = [B,D,H]
debug :: (Show a) => a -> a
debug x = unsafePerformIO (do putStrLn (show x)
return x)
debug' :: (Show a) => String -> a -> a
debug' s x = unsafePerformIO (do putStrLn (s ++ ": " ++ (show x))
return x)
| null | https://raw.githubusercontent.com/schwering/golog/e5a0dba9598d616762271b5bef9fd51a53c1f829/plan-recog/src/RSTC/Car.hs | haskell | cars = [B .. H]
cars = [D,H] | module RSTC.Car where
import Data.Ix
import System.IO.Unsafe
data Lane = LeftLane | RightLane deriving (Eq, Enum, Show)
data Car = A | B | C | D | E | F | G | H deriving (Bounded, Enum, Eq, Ix, Ord, Show)
cars :: [Car]
cars = [B,D,H]
debug :: (Show a) => a -> a
debug x = unsafePerformIO (do putStrLn (show x)
return x)
debug' :: (Show a) => String -> a -> a
debug' s x = unsafePerformIO (do putStrLn (s ++ ": " ++ (show x))
return x)
|
462f0033365d36a1f6264e7cfffa443254ed00fb95feaa01a10b3c28bf712214 | lucasdicioccio/deptrack-project | Networking.hs | # LANGUAGE DataKinds #
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
module Devops.Networking (
Interface (..) , interfaceName
, ConfiguredInterface (..) , configuredInterface
, IpNetString , Port
, MacAddressString
, HostString
, Bridge , bridge
, Tap , tap
, BridgedInterface , bridgedInterface
, ipForwarding
, nating
--
, Index , AddressPlan (..)
, zerothIP , broadcastIpStr , netmaskIpStr , prefixLenString
, ipNetString
, TenspaceIndex , tenspaceAddressPlan
--
, Remote (..)
, Remoted (..)
, Proxied (..) , Listening (..) , Exposed (..)
, publicFacingService
, proxyRemote , publicFacingProxy
, existingRemote
, exposed2listening
--
, TTL
) where
import Data.Monoid ((<>))
import Data.String.Conversions (convertString)
import Data.Text (Text)
import qualified Data.Text as Text
import Data.Typeable (Typeable)
import Prelude hiding (readFile)
import System.IO.Strict (readFile)
import Text.Printf (printf)
import Devops.Binary
import Devops.Debian.Commands
import Devops.Debian.User (User (..))
import Devops.Base
import Devops.Utils
type Index = Int
-- | An IP-Addressing plan for a local subnet tree.
-- Currently assumes a "/24" prefix.
data AddressPlan = AddressPlan { indices :: [Index]
, localhostIp :: IpNetString
, localNetwork :: IpNetString
, fixedMac :: Index -> MacAddressString
, fixedIp :: Index -> IpNetString
, fixedHostName :: Index -> HostString
, fixed0xHostName :: Index -> HostString
}
ipNetString :: Text -> Text -> IpNetString
ipNetString ip pfx = ip <> "/" <> pfx
zerothIP :: AddressPlan -> IpNetString
zerothIP = Text.takeWhile ((/=)'/') . localNetwork
| WARNING only works on /24 ! !
broadcastIpStr :: AddressPlan -> IpNetString
broadcastIpStr plan =
let z = zerothIP plan in
let txtPfx = take 3 (Text.splitOn "." z) in
Text.intercalate "." (txtPfx ++ ["255"])
netmaskIpStr :: AddressPlan -> IpNetString
netmaskIpStr _ = "255.255.255.0"
prefixLenString :: AddressPlan -> Text
prefixLenString = Text.drop 1 . Text.dropWhile ((/=)'/') . localNetwork
| An index representing a 10 - space network .
Should be in [ 1 .. 254 ]
type TenspaceIndex = Index
| A default address plan allowing hosts on the 10.1.1.0\24 range .
tenspaceAddressPlan :: TenspaceIndex -> AddressPlan
tenspaceAddressPlan n | n < 1 || n > 254 = error "n should be in [1..254]"
tenspaceAddressPlan n =
AddressPlan [2..254] localIp localNet fmac fip fhost f0xhost
where
localIp :: IpNetString
localIp = Text.pack $ "10." <> show n <> ".1.1"
localNet :: IpNetString
localNet = Text.pack $ "10." <> show n <> ".1.0/24"
fmac :: Index -> MacAddressString
fmac idx | idx < 255 = Text.pack $ printf "52:54:%02x:22:33:%02x" n idx
| otherwise = error $ printf "invalid index for MAC address: %d" idx
fip :: Index -> IpNetString
fip idx | idx < 255 = Text.pack $ printf "10.%d.1.%d" n idx
| otherwise = error $ printf "invalid index for IP address: %d" idx
fhost :: Index -> HostString
fhost idx = Text.pack $ printf "vm%03d" idx
f0xhost :: Index -> HostString
f0xhost idx = Text.pack $ printf "vm0x%02x" idx
data IPForwarding = IPForwarding
data NATing = NATing !Interface !Interface -- from/to
data Bridge = Bridge !Name
data Tap = Tap !Name !User
data Interface = TapIface !Tap | BridgeIface !Bridge | PhysicalIface !Name | OtherInetIface !Name
data ConfiguredInterface = ConfiguredInterface !IpNetString !Interface
interfaceName :: Interface -> Name
interfaceName (TapIface (Tap n _)) = n
interfaceName (BridgeIface (Bridge n)) = n
interfaceName (PhysicalIface n) = n
interfaceName (OtherInetIface n) = n
type BridgedInterface = (Interface, Bridge)
type IpNetString = Text
type MacAddressString = Text
type Port a = Int -- Port exposing a given service of type a.
type HostString = Text
-- | A remote host.
data Remote = Remote { remoteIp :: !IpNetString }
-- | A value on a remote.
data Remoted a = Remoted !Remote !a
deriving (Functor, Foldable, Traversable)
-- | A proxied service.
data Proxied a = Proxied { proxiedServiceInfo :: !(IpNetString,Port a)
, proxiedServiceLocalPort :: !(Port a)
, proxiedService :: !a
} deriving Functor
-- | A service listening on a local port.
data Listening a = Listening { listeningPort :: !(Port a) , listeningService :: !a }
deriving Functor
-- | A service exposed on a local port.
data Exposed a = Exposed { exposedPort :: !(Port a) , exposedService :: !a }
deriving Functor
-- | Builds an existing remote.
existingRemote :: IpNetString -> DevOp env Remote
existingRemote ip = declare mkOp (pure $ Remote ip)
where mkOp = noop ("existing-remote: " <> ip)
("an already-existing network host")
ipForwardingProcPath :: FilePath
ipForwardingProcPath = "/proc/sys/net/ipv4/ip_forward"
isForwardingEnabled :: IO Bool
isForwardingEnabled = (=="1\n") <$> readFile ipForwardingProcPath
enableForwarding,disableForwarding :: IO ()
enableForwarding = writeFile ipForwardingProcPath "1\n"
disableForwarding = writeFile ipForwardingProcPath "0\n"
ipForwarding :: DevOp env IPForwarding
ipForwarding =
let mkop _ = buildOp ("linux-ip-forwarding")
("ensures that /proc/sys/net/ipv4/ip_forward is 1")
(fromBool <$> isForwardingEnabled)
(enableForwarding)
(disableForwarding)
noAction
in devop id mkop (pure IPForwarding)
configuration using iptables .
-- The main problem is that iptables rules are a global shared value and order matters.
We should break - down individual needs ( e.g. , = forward related in ,
-- forward everything out etc.). Also, use a graph-optimization to collect,
-- merge, and atomically commit rules.
nating :: DevOp env (Binary "iptables")
-> DevOp env Interface
-> DevOp env Interface
-> DevOp env (NATing, Binary "iptables")
nating binaries internet lan = devop id mkOp $ do
nat <- NATing <$> internet <*> lan
bins <- binaries
return (nat, bins)
where
mkOp ((NATing a b), i) = buildOp
("linux-ip-network-address-translation: " <> interfaceName b <> " via " <> interfaceName a)
("ensures that Linux NAT is enabled")
(checkBinaryExitCodeAndStdout null i [
"-w"
, "-t", "nat"
, "-C", "POSTROUTING"
, "-o", Text.unpack $ interfaceName a
, "-j", "MASQUERADE" ] "")
(blindRun i [
"-w"
, "-t", "nat"
, "-I", "POSTROUTING"
, "-o", Text.unpack $ interfaceName a
, "-j", "MASQUERADE" ] ""
>> blindRun i [
"-w"
, "-I", "FORWARD"
, "-i", Text.unpack $ interfaceName b
, "-o", Text.unpack $ interfaceName a
, "-j", "ACCEPT" ] ""
>> blindRun i [
"-w"
, "-I", "FORWARD"
, "-i", Text.unpack $ interfaceName a
, "-o", Text.unpack $ interfaceName b
, "-m", "state"
, "--state", "RELATED,ESTABLISHED"
, "-j", "ACCEPT" ] ""
)
(blindRun i [
"-w"
, "-t", "nat"
, "-D", "POSTROUTING"
, "-o", Text.unpack $ interfaceName a
, "-j", "MASQUERADE" ] ""
>> blindRun i [
"-w"
, "-D", "FORWARD"
, "-i", Text.unpack $ interfaceName b
, "-o", Text.unpack $ interfaceName a
, "-j", "ACCEPT" ] ""
>> blindRun i [
"-w"
, "-D", "FORWARD"
, "-i", Text.unpack $ interfaceName a
, "-o", Text.unpack $ interfaceName b
, "-m", "state"
, "--state", "RELATED,ESTABLISHED"
, "-j", "ACCEPT" ] ""
)
noAction
bridge :: Name -> DevOp env (Binary "brctl", Binary "ip") -> DevOp env (Bridge, (Binary "brctl", Binary "ip"))
bridge name binaries = devop id mkop $ do
let br = Bridge name
bins <- binaries
return (br, bins)
where
mkop (_,(b,ip)) = buildOp ("linux-ip-network-bridge: " <> name)
("ensures that softbridge " <> name <> " exists")
(checkExitCode "ip" ["addr", "show", Text.unpack name] "")
(blindRun b ["addbr", Text.unpack name] ""
>> blindRun ip ["link", "set", "dev", Text.unpack name, "up"] "")
(blindRun ip ["link", "set", "dev", Text.unpack name, "down"] ""
>> blindRun b ["delbr", Text.unpack name] "")
noAction
tap :: Name -> DevOp env User -> DevOp env (Binary "tunctl") -> DevOp env (Tap, Binary "tunctl")
tap name usr binaries = devop id mkOp $ do
(,) <$> (Tap name <$> usr) <*> binaries
where
mkOp (Tap _ (User u), t) = buildOp
("linux-ip-network-tap: " <> name)
("ensures that tap interface " <> name <> " belongs to user " <> convertString u)
(checkExitCode "ip" ["addr", "show", Text.unpack name] "")
(blindRun t ["-u", Text.unpack u, "-t", Text.unpack name] "")
(blindRun t ["-d", Text.unpack name] "")
noAction
configuredInterface :: IpNetString -> DevOp env Interface -> DevOp env (Binary "ip") -> DevOp env (ConfiguredInterface)
configuredInterface addrStr mkIface binaries = devop fst mkOp $ do
iface <- ConfiguredInterface addrStr <$> mkIface
bins <- binaries
return (iface, bins)
where
mkOp ((ConfiguredInterface _ iface), ip) = buildOp
("linux-ip-network-set:" <> interfaceName iface <> " as " <> addrStr)
("ensures that an interface has an IP")
noCheck
(blindRun ip ["addr", "add", Text.unpack addrStr, "dev", Text.unpack $ interfaceName iface] "")
(blindRun ip ["addr", "del", Text.unpack addrStr, "dev", Text.unpack $ interfaceName iface] "")
noAction
bridgedInterface :: DevOp env Interface -> DevOp env Bridge -> DevOp env (Binary "brctl", Binary "ip") -> DevOp env (Interface, Bridge, (Binary "brctl", Binary "ip"))
bridgedInterface mkIface mkBridge binaries =
let mkOp ((TapIface (Tap n _)), Bridge br, (b,ip)) = buildOp
("linux-ip-network-bridged-tap: " <> n <> "<->" <> br)
("ensures that a tap interface is bridged")
noCheck
(blindRun b ["addif", Text.unpack br, Text.unpack n] ""
>> blindRun ip ["link", "set", "dev", Text.unpack n, "up", "promisc", "on"] "")
(blindRun ip ["link", "set", "dev", Text.unpack n, "down"] ""
>> blindRun b ["delif", Text.unpack br, Text.unpack n] "")
noAction
mkOp _ = error "only knows how to bridge a TapIface"
in devop id mkOp ((,,) <$> mkIface <*> mkBridge <*> binaries)
-- | Proxies and forward traffic from a local port to a remotely-listening service.
proxyRemote :: Typeable a
=> Port a
-> DevOp env ConfiguredInterface
-> DevOp env (Remoted (Listening a))
-> DevOp env (Proxied a)
proxyRemote publicPort mkInternet mkRemote = devop snd mkOp $ do
(Remoted (Remote ip) (Listening machinePort x)) <- mkRemote
iptablesCommand <- iptables
internet <- mkInternet
return ((iptablesCommand, internet), Proxied (ip, machinePort) publicPort x)
where
mkOp ((i, (ConfiguredInterface publicIp a)), Proxied (ip, machinePort) _ _) =
buildOp (Text.pack $ printf "proxied-service: %s:%d to %s:%d" (Text.unpack publicIp) publicPort (Text.unpack ip) machinePort)
("setups port-mapping between public ip/port and private ip/port")
(checkBinaryExitCodeAndStdout null i [
"-w"
, "-t", "nat"
, "-C", "PREROUTING"
, "-i", Text.unpack $ interfaceName a
, "-p", "tcp", "--dport", show publicPort
, "-j", "DNAT"
, "--to", printf "%s:%d" (Text.unpack ip) machinePort ] "")
(blindRun i [
"-w"
, "-t", "nat"
, "-I", "POSTROUTING"
, "-o", Text.unpack $ interfaceName a
, "-p", "tcp", "--sport", show machinePort
, "-j", "SNAT"
, "--to", Text.unpack publicIp ] ""
>> blindRun i [
"-w"
, "-t", "nat"
, "-I", "PREROUTING"
, "-i", Text.unpack $ interfaceName a
, "-p", "tcp", "--dport", show publicPort
, "-j", "DNAT"
, "--to", printf "%s:%d" (Text.unpack ip) machinePort ] ""
)
(blindRun i [
"-w"
, "-t", "nat"
, "-D", "POSTROUTING"
, "-o", Text.unpack $ interfaceName a
, "-p", "tcp", "--sport", show machinePort
, "-j", "SNAT"
, "--to", Text.unpack $ publicIp ] ""
>> blindRun i [
"-w"
, "-t", "nat"
, "-D", "PREROUTING"
, "-i", Text.unpack $ interfaceName a
, "-p", "tcp", "--dport", show publicPort
, "-j", "DNAT"
, "--to", printf "%s:%d" (Text.unpack ip) machinePort ] ""
)
noAction
-- | Exposes a proxied service to the Internet.
-- * Listening service is proxied -> private port is used because prerouting rewrites ports
publicFacingProxy :: Typeable a => DevOp env (Proxied a) -> DevOp env (Exposed a)
publicFacingProxy mkProxy = devop snd mkOp $ do
(Proxied (_,privatePort) port val) <- mkProxy
iptablesCommand <- iptables
return ((iptablesCommand,privatePort), Exposed port val)
where
mkOp ((i,port),(Exposed publicPort _)) =
buildOp (Text.pack $ printf "exposed-port: %d" publicPort)
("opens port on the firewall")
(checkBinaryExitCodeAndStdout null i [
"-w"
, "-C", "FORWARD"
, "-p", "tcp", "--dport", show port
, "-j", "ACCEPT" ] "")
(blindRun i [
"-w"
, "-I", "FORWARD"
, "-p", "tcp", "--dport", show port
, "-j", "ACCEPT" ] "")
(blindRun i [
"-w"
, "-D", "FORWARD"
, "-p", "tcp", "--dport", show port
, "-j", "ACCEPT" ] "")
noAction
* Listening service is open locally - > should be using the INPUT chain .
publicFacingService :: Typeable a => DevOp env (Listening a) -> DevOp env (Exposed a)
publicFacingService mkListening = devop snd mkOp $ do
(Listening port val) <- mkListening
iptablesCommand <- iptables
return (iptablesCommand, Exposed port val)
where mkOp (i,(Exposed port _)) =
buildOp (Text.pack $ printf "exposed-port: %d" port)
("opens port on the firewall")
(checkBinaryExitCodeAndStdout null i [
"-w"
, "-C", "INPUT"
, "-p", "tcp", "--dport", show port
, "-j", "ACCEPT" ] "")
(blindRun i [
"-w"
, "-I", "INPUT"
, "-p", "tcp", "--dport", show port
, "-j", "ACCEPT" ] "")
(blindRun i [
"-w"
, "-D", "INPUT"
, "-p", "tcp", "--dport", show port
, "-j", "ACCEPT" ] "")
noAction
exposed2listening :: Exposed a -> Listening a
exposed2listening (Exposed a b) = Listening a b
type TTL = Int
| null | https://raw.githubusercontent.com/lucasdicioccio/deptrack-project/cd3d59a796815af8ae8db32c47b1e1cdc209ac71/deptrack-devops-recipes/src/Devops/Networking.hs | haskell | # LANGUAGE DeriveFunctor #
# LANGUAGE DeriveFoldable #
# LANGUAGE DeriveTraversable #
# LANGUAGE OverloadedStrings #
# LANGUAGE RankNTypes #
| An IP-Addressing plan for a local subnet tree.
Currently assumes a "/24" prefix.
from/to
Port exposing a given service of type a.
| A remote host.
| A value on a remote.
| A proxied service.
| A service listening on a local port.
| A service exposed on a local port.
| Builds an existing remote.
The main problem is that iptables rules are a global shared value and order matters.
forward everything out etc.). Also, use a graph-optimization to collect,
merge, and atomically commit rules.
| Proxies and forward traffic from a local port to a remotely-listening service.
| Exposes a proxied service to the Internet.
* Listening service is proxied -> private port is used because prerouting rewrites ports | # LANGUAGE DataKinds #
module Devops.Networking (
Interface (..) , interfaceName
, ConfiguredInterface (..) , configuredInterface
, IpNetString , Port
, MacAddressString
, HostString
, Bridge , bridge
, Tap , tap
, BridgedInterface , bridgedInterface
, ipForwarding
, nating
, Index , AddressPlan (..)
, zerothIP , broadcastIpStr , netmaskIpStr , prefixLenString
, ipNetString
, TenspaceIndex , tenspaceAddressPlan
, Remote (..)
, Remoted (..)
, Proxied (..) , Listening (..) , Exposed (..)
, publicFacingService
, proxyRemote , publicFacingProxy
, existingRemote
, exposed2listening
, TTL
) where
import Data.Monoid ((<>))
import Data.String.Conversions (convertString)
import Data.Text (Text)
import qualified Data.Text as Text
import Data.Typeable (Typeable)
import Prelude hiding (readFile)
import System.IO.Strict (readFile)
import Text.Printf (printf)
import Devops.Binary
import Devops.Debian.Commands
import Devops.Debian.User (User (..))
import Devops.Base
import Devops.Utils
type Index = Int
data AddressPlan = AddressPlan { indices :: [Index]
, localhostIp :: IpNetString
, localNetwork :: IpNetString
, fixedMac :: Index -> MacAddressString
, fixedIp :: Index -> IpNetString
, fixedHostName :: Index -> HostString
, fixed0xHostName :: Index -> HostString
}
ipNetString :: Text -> Text -> IpNetString
ipNetString ip pfx = ip <> "/" <> pfx
zerothIP :: AddressPlan -> IpNetString
zerothIP = Text.takeWhile ((/=)'/') . localNetwork
| WARNING only works on /24 ! !
broadcastIpStr :: AddressPlan -> IpNetString
broadcastIpStr plan =
let z = zerothIP plan in
let txtPfx = take 3 (Text.splitOn "." z) in
Text.intercalate "." (txtPfx ++ ["255"])
netmaskIpStr :: AddressPlan -> IpNetString
netmaskIpStr _ = "255.255.255.0"
prefixLenString :: AddressPlan -> Text
prefixLenString = Text.drop 1 . Text.dropWhile ((/=)'/') . localNetwork
| An index representing a 10 - space network .
Should be in [ 1 .. 254 ]
type TenspaceIndex = Index
| A default address plan allowing hosts on the 10.1.1.0\24 range .
tenspaceAddressPlan :: TenspaceIndex -> AddressPlan
tenspaceAddressPlan n | n < 1 || n > 254 = error "n should be in [1..254]"
tenspaceAddressPlan n =
AddressPlan [2..254] localIp localNet fmac fip fhost f0xhost
where
localIp :: IpNetString
localIp = Text.pack $ "10." <> show n <> ".1.1"
localNet :: IpNetString
localNet = Text.pack $ "10." <> show n <> ".1.0/24"
fmac :: Index -> MacAddressString
fmac idx | idx < 255 = Text.pack $ printf "52:54:%02x:22:33:%02x" n idx
| otherwise = error $ printf "invalid index for MAC address: %d" idx
fip :: Index -> IpNetString
fip idx | idx < 255 = Text.pack $ printf "10.%d.1.%d" n idx
| otherwise = error $ printf "invalid index for IP address: %d" idx
fhost :: Index -> HostString
fhost idx = Text.pack $ printf "vm%03d" idx
f0xhost :: Index -> HostString
f0xhost idx = Text.pack $ printf "vm0x%02x" idx
data IPForwarding = IPForwarding
data Bridge = Bridge !Name
data Tap = Tap !Name !User
data Interface = TapIface !Tap | BridgeIface !Bridge | PhysicalIface !Name | OtherInetIface !Name
data ConfiguredInterface = ConfiguredInterface !IpNetString !Interface
interfaceName :: Interface -> Name
interfaceName (TapIface (Tap n _)) = n
interfaceName (BridgeIface (Bridge n)) = n
interfaceName (PhysicalIface n) = n
interfaceName (OtherInetIface n) = n
type BridgedInterface = (Interface, Bridge)
type IpNetString = Text
type MacAddressString = Text
type HostString = Text
data Remote = Remote { remoteIp :: !IpNetString }
data Remoted a = Remoted !Remote !a
deriving (Functor, Foldable, Traversable)
data Proxied a = Proxied { proxiedServiceInfo :: !(IpNetString,Port a)
, proxiedServiceLocalPort :: !(Port a)
, proxiedService :: !a
} deriving Functor
data Listening a = Listening { listeningPort :: !(Port a) , listeningService :: !a }
deriving Functor
data Exposed a = Exposed { exposedPort :: !(Port a) , exposedService :: !a }
deriving Functor
existingRemote :: IpNetString -> DevOp env Remote
existingRemote ip = declare mkOp (pure $ Remote ip)
where mkOp = noop ("existing-remote: " <> ip)
("an already-existing network host")
ipForwardingProcPath :: FilePath
ipForwardingProcPath = "/proc/sys/net/ipv4/ip_forward"
isForwardingEnabled :: IO Bool
isForwardingEnabled = (=="1\n") <$> readFile ipForwardingProcPath
enableForwarding,disableForwarding :: IO ()
enableForwarding = writeFile ipForwardingProcPath "1\n"
disableForwarding = writeFile ipForwardingProcPath "0\n"
ipForwarding :: DevOp env IPForwarding
ipForwarding =
let mkop _ = buildOp ("linux-ip-forwarding")
("ensures that /proc/sys/net/ipv4/ip_forward is 1")
(fromBool <$> isForwardingEnabled)
(enableForwarding)
(disableForwarding)
noAction
in devop id mkop (pure IPForwarding)
configuration using iptables .
We should break - down individual needs ( e.g. , = forward related in ,
nating :: DevOp env (Binary "iptables")
-> DevOp env Interface
-> DevOp env Interface
-> DevOp env (NATing, Binary "iptables")
nating binaries internet lan = devop id mkOp $ do
nat <- NATing <$> internet <*> lan
bins <- binaries
return (nat, bins)
where
mkOp ((NATing a b), i) = buildOp
("linux-ip-network-address-translation: " <> interfaceName b <> " via " <> interfaceName a)
("ensures that Linux NAT is enabled")
(checkBinaryExitCodeAndStdout null i [
"-w"
, "-t", "nat"
, "-C", "POSTROUTING"
, "-o", Text.unpack $ interfaceName a
, "-j", "MASQUERADE" ] "")
(blindRun i [
"-w"
, "-t", "nat"
, "-I", "POSTROUTING"
, "-o", Text.unpack $ interfaceName a
, "-j", "MASQUERADE" ] ""
>> blindRun i [
"-w"
, "-I", "FORWARD"
, "-i", Text.unpack $ interfaceName b
, "-o", Text.unpack $ interfaceName a
, "-j", "ACCEPT" ] ""
>> blindRun i [
"-w"
, "-I", "FORWARD"
, "-i", Text.unpack $ interfaceName a
, "-o", Text.unpack $ interfaceName b
, "-m", "state"
, "--state", "RELATED,ESTABLISHED"
, "-j", "ACCEPT" ] ""
)
(blindRun i [
"-w"
, "-t", "nat"
, "-D", "POSTROUTING"
, "-o", Text.unpack $ interfaceName a
, "-j", "MASQUERADE" ] ""
>> blindRun i [
"-w"
, "-D", "FORWARD"
, "-i", Text.unpack $ interfaceName b
, "-o", Text.unpack $ interfaceName a
, "-j", "ACCEPT" ] ""
>> blindRun i [
"-w"
, "-D", "FORWARD"
, "-i", Text.unpack $ interfaceName a
, "-o", Text.unpack $ interfaceName b
, "-m", "state"
, "--state", "RELATED,ESTABLISHED"
, "-j", "ACCEPT" ] ""
)
noAction
bridge :: Name -> DevOp env (Binary "brctl", Binary "ip") -> DevOp env (Bridge, (Binary "brctl", Binary "ip"))
bridge name binaries = devop id mkop $ do
let br = Bridge name
bins <- binaries
return (br, bins)
where
mkop (_,(b,ip)) = buildOp ("linux-ip-network-bridge: " <> name)
("ensures that softbridge " <> name <> " exists")
(checkExitCode "ip" ["addr", "show", Text.unpack name] "")
(blindRun b ["addbr", Text.unpack name] ""
>> blindRun ip ["link", "set", "dev", Text.unpack name, "up"] "")
(blindRun ip ["link", "set", "dev", Text.unpack name, "down"] ""
>> blindRun b ["delbr", Text.unpack name] "")
noAction
tap :: Name -> DevOp env User -> DevOp env (Binary "tunctl") -> DevOp env (Tap, Binary "tunctl")
tap name usr binaries = devop id mkOp $ do
(,) <$> (Tap name <$> usr) <*> binaries
where
mkOp (Tap _ (User u), t) = buildOp
("linux-ip-network-tap: " <> name)
("ensures that tap interface " <> name <> " belongs to user " <> convertString u)
(checkExitCode "ip" ["addr", "show", Text.unpack name] "")
(blindRun t ["-u", Text.unpack u, "-t", Text.unpack name] "")
(blindRun t ["-d", Text.unpack name] "")
noAction
configuredInterface :: IpNetString -> DevOp env Interface -> DevOp env (Binary "ip") -> DevOp env (ConfiguredInterface)
configuredInterface addrStr mkIface binaries = devop fst mkOp $ do
iface <- ConfiguredInterface addrStr <$> mkIface
bins <- binaries
return (iface, bins)
where
mkOp ((ConfiguredInterface _ iface), ip) = buildOp
("linux-ip-network-set:" <> interfaceName iface <> " as " <> addrStr)
("ensures that an interface has an IP")
noCheck
(blindRun ip ["addr", "add", Text.unpack addrStr, "dev", Text.unpack $ interfaceName iface] "")
(blindRun ip ["addr", "del", Text.unpack addrStr, "dev", Text.unpack $ interfaceName iface] "")
noAction
bridgedInterface :: DevOp env Interface -> DevOp env Bridge -> DevOp env (Binary "brctl", Binary "ip") -> DevOp env (Interface, Bridge, (Binary "brctl", Binary "ip"))
bridgedInterface mkIface mkBridge binaries =
let mkOp ((TapIface (Tap n _)), Bridge br, (b,ip)) = buildOp
("linux-ip-network-bridged-tap: " <> n <> "<->" <> br)
("ensures that a tap interface is bridged")
noCheck
(blindRun b ["addif", Text.unpack br, Text.unpack n] ""
>> blindRun ip ["link", "set", "dev", Text.unpack n, "up", "promisc", "on"] "")
(blindRun ip ["link", "set", "dev", Text.unpack n, "down"] ""
>> blindRun b ["delif", Text.unpack br, Text.unpack n] "")
noAction
mkOp _ = error "only knows how to bridge a TapIface"
in devop id mkOp ((,,) <$> mkIface <*> mkBridge <*> binaries)
proxyRemote :: Typeable a
=> Port a
-> DevOp env ConfiguredInterface
-> DevOp env (Remoted (Listening a))
-> DevOp env (Proxied a)
proxyRemote publicPort mkInternet mkRemote = devop snd mkOp $ do
(Remoted (Remote ip) (Listening machinePort x)) <- mkRemote
iptablesCommand <- iptables
internet <- mkInternet
return ((iptablesCommand, internet), Proxied (ip, machinePort) publicPort x)
where
mkOp ((i, (ConfiguredInterface publicIp a)), Proxied (ip, machinePort) _ _) =
buildOp (Text.pack $ printf "proxied-service: %s:%d to %s:%d" (Text.unpack publicIp) publicPort (Text.unpack ip) machinePort)
("setups port-mapping between public ip/port and private ip/port")
(checkBinaryExitCodeAndStdout null i [
"-w"
, "-t", "nat"
, "-C", "PREROUTING"
, "-i", Text.unpack $ interfaceName a
, "-p", "tcp", "--dport", show publicPort
, "-j", "DNAT"
, "--to", printf "%s:%d" (Text.unpack ip) machinePort ] "")
(blindRun i [
"-w"
, "-t", "nat"
, "-I", "POSTROUTING"
, "-o", Text.unpack $ interfaceName a
, "-p", "tcp", "--sport", show machinePort
, "-j", "SNAT"
, "--to", Text.unpack publicIp ] ""
>> blindRun i [
"-w"
, "-t", "nat"
, "-I", "PREROUTING"
, "-i", Text.unpack $ interfaceName a
, "-p", "tcp", "--dport", show publicPort
, "-j", "DNAT"
, "--to", printf "%s:%d" (Text.unpack ip) machinePort ] ""
)
(blindRun i [
"-w"
, "-t", "nat"
, "-D", "POSTROUTING"
, "-o", Text.unpack $ interfaceName a
, "-p", "tcp", "--sport", show machinePort
, "-j", "SNAT"
, "--to", Text.unpack $ publicIp ] ""
>> blindRun i [
"-w"
, "-t", "nat"
, "-D", "PREROUTING"
, "-i", Text.unpack $ interfaceName a
, "-p", "tcp", "--dport", show publicPort
, "-j", "DNAT"
, "--to", printf "%s:%d" (Text.unpack ip) machinePort ] ""
)
noAction
publicFacingProxy :: Typeable a => DevOp env (Proxied a) -> DevOp env (Exposed a)
publicFacingProxy mkProxy = devop snd mkOp $ do
(Proxied (_,privatePort) port val) <- mkProxy
iptablesCommand <- iptables
return ((iptablesCommand,privatePort), Exposed port val)
where
mkOp ((i,port),(Exposed publicPort _)) =
buildOp (Text.pack $ printf "exposed-port: %d" publicPort)
("opens port on the firewall")
(checkBinaryExitCodeAndStdout null i [
"-w"
, "-C", "FORWARD"
, "-p", "tcp", "--dport", show port
, "-j", "ACCEPT" ] "")
(blindRun i [
"-w"
, "-I", "FORWARD"
, "-p", "tcp", "--dport", show port
, "-j", "ACCEPT" ] "")
(blindRun i [
"-w"
, "-D", "FORWARD"
, "-p", "tcp", "--dport", show port
, "-j", "ACCEPT" ] "")
noAction
* Listening service is open locally - > should be using the INPUT chain .
publicFacingService :: Typeable a => DevOp env (Listening a) -> DevOp env (Exposed a)
publicFacingService mkListening = devop snd mkOp $ do
(Listening port val) <- mkListening
iptablesCommand <- iptables
return (iptablesCommand, Exposed port val)
where mkOp (i,(Exposed port _)) =
buildOp (Text.pack $ printf "exposed-port: %d" port)
("opens port on the firewall")
(checkBinaryExitCodeAndStdout null i [
"-w"
, "-C", "INPUT"
, "-p", "tcp", "--dport", show port
, "-j", "ACCEPT" ] "")
(blindRun i [
"-w"
, "-I", "INPUT"
, "-p", "tcp", "--dport", show port
, "-j", "ACCEPT" ] "")
(blindRun i [
"-w"
, "-D", "INPUT"
, "-p", "tcp", "--dport", show port
, "-j", "ACCEPT" ] "")
noAction
exposed2listening :: Exposed a -> Listening a
exposed2listening (Exposed a b) = Listening a b
type TTL = Int
|
23fc136391810b3204868e3482fe5d526d6bca7948e0a9e686a0fc8e54685a35 | e-bigmoon/haskell-blog | Tips6.hs | #!/usr/bin/env stack
stack repl --resolver lts-15.4
--package shakespeare
--package yesod
--package shakespeare
--package yesod
-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
# LANGUAGE TemplateHaskell #
{-# LANGUAGE TypeFamilies #-}
import Text.Julius
import Yesod
data App = App
mkYesod "App" [parseRoutes|
/check1 Check1R GET -- Safe
/check2 Check2R GET -- Safe
/check3 Check3R GET -- Safe
/check4 Check4R GET -- Unsafe
/check5 Check5R GET -- Unsafe
|]
instance Yesod App
:3000 / check1?p=<script > alert(document.cookie)</script >
getCheck1R :: Handler Html
getCheck1R = defaultLayout $ do
mParam <- lookupGetParam "p"
[whamlet|
#{maybe "" id mParam}
|]
-- :3000/check2?p="></form>XSS"
getCheck2R :: Handler Html
getCheck2R = defaultLayout $ do
mParam <- lookupGetParam "p"
[whamlet|
<form action="" method="POST">
氏名<input name="name" value="#{maybe "" id mParam}"><br>
|]
:3000 / check3?p=1+onmouseover%3dalert(document.cookie )
getCheck3R :: Handler Html
getCheck3R = defaultLayout $ do
mParam <- lookupGetParam "p"
[whamlet|
<input type=text name=mail value=#{maybe "" id mParam}>
|]
:3000 / check4?p = javascript : alert(document.cookie )
getCheck4R :: Handler Html
getCheck4R = defaultLayout $ do
mParam <- lookupGetParam "p"
[whamlet|
<a href=#{maybe "" id mParam}>
ブックマーク
|]
-- :3000/check5?p='),alert(document.cookie)//
getCheck5R :: Handler Html
getCheck5R = defaultLayout $ do
mParam <- lookupGetParam "p"
[whamlet|
<body onload="init('#{maybe "" id mParam}')">
|]
toWidget [julius|
function init(text) {
// 適当な処理
}
|]
main :: IO ()
main = warp 3000 App
| null | https://raw.githubusercontent.com/e-bigmoon/haskell-blog/5c9e7c25f31ea6856c5d333e8e991dbceab21c56/sample-code/yesod/tips/Tips6.hs | haskell | resolver lts-15.4
package shakespeare
package yesod
package shakespeare
package yesod
# LANGUAGE OverloadedStrings #
# LANGUAGE QuasiQuotes #
# LANGUAGE TypeFamilies #
Safe
Safe
Safe
Unsafe
Unsafe
:3000/check2?p="></form>XSS"
:3000/check5?p='),alert(document.cookie)// | #!/usr/bin/env stack
-}
# LANGUAGE TemplateHaskell #
import Text.Julius
import Yesod
data App = App
mkYesod "App" [parseRoutes|
|]
instance Yesod App
:3000 / check1?p=<script > alert(document.cookie)</script >
getCheck1R :: Handler Html
getCheck1R = defaultLayout $ do
mParam <- lookupGetParam "p"
[whamlet|
#{maybe "" id mParam}
|]
getCheck2R :: Handler Html
getCheck2R = defaultLayout $ do
mParam <- lookupGetParam "p"
[whamlet|
<form action="" method="POST">
氏名<input name="name" value="#{maybe "" id mParam}"><br>
|]
:3000 / check3?p=1+onmouseover%3dalert(document.cookie )
getCheck3R :: Handler Html
getCheck3R = defaultLayout $ do
mParam <- lookupGetParam "p"
[whamlet|
<input type=text name=mail value=#{maybe "" id mParam}>
|]
:3000 / check4?p = javascript : alert(document.cookie )
getCheck4R :: Handler Html
getCheck4R = defaultLayout $ do
mParam <- lookupGetParam "p"
[whamlet|
<a href=#{maybe "" id mParam}>
ブックマーク
|]
getCheck5R :: Handler Html
getCheck5R = defaultLayout $ do
mParam <- lookupGetParam "p"
[whamlet|
<body onload="init('#{maybe "" id mParam}')">
|]
toWidget [julius|
function init(text) {
// 適当な処理
}
|]
main :: IO ()
main = warp 3000 App
|
d5bbf53b70e237bd4891ab6a66b221dd2d3f282cfc36701f95c43617010a09c6 | dariusf/ppx_debug | pp.ml | open Ppxlib
let pexpr = Pprintast.expression
let pstr = Pprintast.structure
let debug_pexpr fmt { pexp_desc; _ } =
let name =
match pexp_desc with
| Pexp_ident _ -> "Pexp_ident"
| Pexp_constant _ -> "Pexp_constant"
| Pexp_let (_, _, _) -> "Pexp_let"
| Pexp_function _ -> "Pexp_function"
| Pexp_fun (_, _, _, _) -> "Pexp_fun"
| Pexp_apply (_, _) -> "Pexp_apply"
| Pexp_match (_, _) -> "Pexp_match"
| Pexp_try (_, _) -> "Pexp_try"
| Pexp_tuple _ -> "Pexp_tuple"
| Pexp_construct (_, _) -> "Pexp_construct"
| Pexp_variant (_, _) -> "Pexp_variant"
| Pexp_record (_, _) -> "Pexp_record"
| Pexp_field (_, _) -> "Pexp_field"
| Pexp_setfield (_, _, _) -> "Pexp_setfield"
| Pexp_array _ -> "Pexp_array"
| Pexp_ifthenelse (_, _, _) -> "Pexp_ifthenelse"
| Pexp_sequence (_, _) -> "Pexp_sequence"
| Pexp_while (_, _) -> "Pexp_while"
| Pexp_for (_, _, _, _, _) -> "Pexp_for"
| Pexp_constraint (_, _) -> "Pexp_constraint"
| Pexp_coerce (_, _, _) -> "Pexp_coerce"
| Pexp_send (_, _) -> "Pexp_send"
| Pexp_new _ -> "Pexp_new"
| Pexp_setinstvar (_, _) -> "Pexp_setinstvar"
| Pexp_override _ -> "Pexp_override"
| Pexp_letmodule (_, _, _) -> "Pexp_letmodule"
| Pexp_letexception (_, _) -> "Pexp_letexception"
| Pexp_assert _ -> "Pexp_assert"
| Pexp_lazy _ -> "Pexp_lazy"
| Pexp_poly (_, _) -> "Pexp_poly"
| Pexp_object _ -> "Pexp_object"
| Pexp_newtype (_, _) -> "Pexp_newtype"
| Pexp_pack _ -> "Pexp_pack"
| Pexp_open (_, _) -> "Pexp_open"
| Pexp_letop _ -> "Pexp_letop"
| Pexp_extension _ -> "Pexp_extension"
| Pexp_unreachable -> "Pexp_unreachable"
in
Format.fprintf fmt "%s" name
| null | https://raw.githubusercontent.com/dariusf/ppx_debug/4709e74d37672aee3f774e713b188fd986563137/ppx_debug_common/pp.ml | ocaml | open Ppxlib
let pexpr = Pprintast.expression
let pstr = Pprintast.structure
let debug_pexpr fmt { pexp_desc; _ } =
let name =
match pexp_desc with
| Pexp_ident _ -> "Pexp_ident"
| Pexp_constant _ -> "Pexp_constant"
| Pexp_let (_, _, _) -> "Pexp_let"
| Pexp_function _ -> "Pexp_function"
| Pexp_fun (_, _, _, _) -> "Pexp_fun"
| Pexp_apply (_, _) -> "Pexp_apply"
| Pexp_match (_, _) -> "Pexp_match"
| Pexp_try (_, _) -> "Pexp_try"
| Pexp_tuple _ -> "Pexp_tuple"
| Pexp_construct (_, _) -> "Pexp_construct"
| Pexp_variant (_, _) -> "Pexp_variant"
| Pexp_record (_, _) -> "Pexp_record"
| Pexp_field (_, _) -> "Pexp_field"
| Pexp_setfield (_, _, _) -> "Pexp_setfield"
| Pexp_array _ -> "Pexp_array"
| Pexp_ifthenelse (_, _, _) -> "Pexp_ifthenelse"
| Pexp_sequence (_, _) -> "Pexp_sequence"
| Pexp_while (_, _) -> "Pexp_while"
| Pexp_for (_, _, _, _, _) -> "Pexp_for"
| Pexp_constraint (_, _) -> "Pexp_constraint"
| Pexp_coerce (_, _, _) -> "Pexp_coerce"
| Pexp_send (_, _) -> "Pexp_send"
| Pexp_new _ -> "Pexp_new"
| Pexp_setinstvar (_, _) -> "Pexp_setinstvar"
| Pexp_override _ -> "Pexp_override"
| Pexp_letmodule (_, _, _) -> "Pexp_letmodule"
| Pexp_letexception (_, _) -> "Pexp_letexception"
| Pexp_assert _ -> "Pexp_assert"
| Pexp_lazy _ -> "Pexp_lazy"
| Pexp_poly (_, _) -> "Pexp_poly"
| Pexp_object _ -> "Pexp_object"
| Pexp_newtype (_, _) -> "Pexp_newtype"
| Pexp_pack _ -> "Pexp_pack"
| Pexp_open (_, _) -> "Pexp_open"
| Pexp_letop _ -> "Pexp_letop"
| Pexp_extension _ -> "Pexp_extension"
| Pexp_unreachable -> "Pexp_unreachable"
in
Format.fprintf fmt "%s" name
| |
4d820339a9259b5310e3ea5eba5076d27090e75eb037e880d32c4fb0720a4b0a | ghc/packages-Cabal | multi-target.test.hs | import Test.Cabal.Prelude
main = cabalTest $ withSourceCopy $ do
cwd <- fmap testCurrentDir getTestEnv
cabal "v2-sdist" ["a", "b"]
shouldExist $ cwd </> "dist-newstyle/sdist/a-0.1.tar.gz"
shouldExist $ cwd </> "dist-newstyle/sdist/b-0.1.tar.gz"
| null | https://raw.githubusercontent.com/ghc/packages-Cabal/6f22f2a789fa23edb210a2591d74ea6a5f767872/cabal-testsuite/PackageTests/NewSdist/MultiTarget/multi-target.test.hs | haskell | import Test.Cabal.Prelude
main = cabalTest $ withSourceCopy $ do
cwd <- fmap testCurrentDir getTestEnv
cabal "v2-sdist" ["a", "b"]
shouldExist $ cwd </> "dist-newstyle/sdist/a-0.1.tar.gz"
shouldExist $ cwd </> "dist-newstyle/sdist/b-0.1.tar.gz"
| |
c12c999ca7f93e45c68b50fa69762a8b0e3cfc1c538890cf87ee4a594ec6116e | hercules-ci/legacy-old-hercules | OAuth.hs | # LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
module Hercules.OAuth
( AuthState(..)
, AuthCode(..)
, authCallback
) where
import Control.Monad.Except.Extra
import Data.Aeson
import Data.ByteString.Lazy (fromStrict, toStrict)
import Data.Text
import Data.Text.Encoding
import Network.OAuth.OAuth2
import qualified Network.OAuth.OAuth2 as OA
import Servant
import Servant.Redirect
import Hercules.OAuth.Authenticators
import Hercules.OAuth.Types
import Hercules.ServerEnv
authCallback :: AuthenticatorName
-> Maybe AuthCode
-> Maybe AuthError
-> AuthStatePacked
-> App a
authCallback authName maybeCode maybeError packedState = do
-- Extract the state
state <- failWith err400 (unpackState packedState)
case (maybeCode, maybeError) of
(Nothing, Nothing) -> throwError err400
(Nothing, Just err) -> handleError state err
(Just code, Nothing) -> handleCode authName state code
(Just _, Just _) -> throwError err400
handleError :: AuthState
-> AuthError
-> App a
handleError state err = do
let redirectURI :: OA.URI
redirectURI = encodeUtf8 . unFrontendURL . authStateFrontendURL $ state
redirectError redirectURI (unAuthError err)
handleCode :: AuthenticatorName
-> AuthState
-> AuthCode
-> App a
handleCode authName state (AuthCode code) = do
-- Can we handle this authenticator
authenticator <- failWithM err404 (getAuthenticator authName)
let config = authenticatorConfig authenticator
let clientState = authStateClientState state
redirectURI :: OA.URI
redirectURI = encodeUtf8 . unFrontendURL . authStateFrontendURL $ state
failWithBS err = redirectError redirectURI (decodeUtf8 . toStrict $ err)
-- Get the access token for this user
token <- either failWithBS pure
=<< withHttpManager (\m -> fetchAccessToken m config (encodeUtf8 code))
-- Get the user info with the token
user <- either (redirectError redirectURI) pure
=<< authenticatorGetUserInfo authenticator token
Create a JWT
jwt <- either (const (redirectError redirectURI "Failed to create JWT")) pure
=<< makeUserJWT user
-- Return to the frontend
redirectSuccess redirectURI jwt clientState
redirectError :: OA.URI
-> Text
-- ^ An error message
-> App a
redirectError uri message =
let param = [("authFailure", encodeUtf8 message)]
in redirectBS (uri `appendQueryParam` param)
redirectSuccess :: OA.URI
-> PackedJWT
-- ^ This user's token
-> Maybe AuthClientState
-> App a
redirectSuccess uri jwt state =
let params = ("jwt", unPackedJWT jwt) :
case state of
Nothing -> []
Just s -> [("state", encodeUtf8 . unAuthClientState $ s)]
in redirectBS (uri `appendQueryParam` params)
unpackState :: AuthStatePacked -> Maybe AuthState
unpackState = decode . fromStrict . encodeUtf8 . unAuthStatePacked
| null | https://raw.githubusercontent.com/hercules-ci/legacy-old-hercules/db10eb399a64355cdcbba0e18beb1514588772e9/backend/src/Hercules/OAuth.hs | haskell | # LANGUAGE OverloadedStrings #
Extract the state
Can we handle this authenticator
Get the access token for this user
Get the user info with the token
Return to the frontend
^ An error message
^ This user's token | # LANGUAGE LambdaCase #
module Hercules.OAuth
( AuthState(..)
, AuthCode(..)
, authCallback
) where
import Control.Monad.Except.Extra
import Data.Aeson
import Data.ByteString.Lazy (fromStrict, toStrict)
import Data.Text
import Data.Text.Encoding
import Network.OAuth.OAuth2
import qualified Network.OAuth.OAuth2 as OA
import Servant
import Servant.Redirect
import Hercules.OAuth.Authenticators
import Hercules.OAuth.Types
import Hercules.ServerEnv
authCallback :: AuthenticatorName
-> Maybe AuthCode
-> Maybe AuthError
-> AuthStatePacked
-> App a
authCallback authName maybeCode maybeError packedState = do
state <- failWith err400 (unpackState packedState)
case (maybeCode, maybeError) of
(Nothing, Nothing) -> throwError err400
(Nothing, Just err) -> handleError state err
(Just code, Nothing) -> handleCode authName state code
(Just _, Just _) -> throwError err400
handleError :: AuthState
-> AuthError
-> App a
handleError state err = do
let redirectURI :: OA.URI
redirectURI = encodeUtf8 . unFrontendURL . authStateFrontendURL $ state
redirectError redirectURI (unAuthError err)
handleCode :: AuthenticatorName
-> AuthState
-> AuthCode
-> App a
handleCode authName state (AuthCode code) = do
authenticator <- failWithM err404 (getAuthenticator authName)
let config = authenticatorConfig authenticator
let clientState = authStateClientState state
redirectURI :: OA.URI
redirectURI = encodeUtf8 . unFrontendURL . authStateFrontendURL $ state
failWithBS err = redirectError redirectURI (decodeUtf8 . toStrict $ err)
token <- either failWithBS pure
=<< withHttpManager (\m -> fetchAccessToken m config (encodeUtf8 code))
user <- either (redirectError redirectURI) pure
=<< authenticatorGetUserInfo authenticator token
Create a JWT
jwt <- either (const (redirectError redirectURI "Failed to create JWT")) pure
=<< makeUserJWT user
redirectSuccess redirectURI jwt clientState
redirectError :: OA.URI
-> Text
-> App a
redirectError uri message =
let param = [("authFailure", encodeUtf8 message)]
in redirectBS (uri `appendQueryParam` param)
redirectSuccess :: OA.URI
-> PackedJWT
-> Maybe AuthClientState
-> App a
redirectSuccess uri jwt state =
let params = ("jwt", unPackedJWT jwt) :
case state of
Nothing -> []
Just s -> [("state", encodeUtf8 . unAuthClientState $ s)]
in redirectBS (uri `appendQueryParam` params)
unpackState :: AuthStatePacked -> Maybe AuthState
unpackState = decode . fromStrict . encodeUtf8 . unAuthStatePacked
|
434e34e98bfc5e6dc04fc26085ec4e61d21cdd7b6fbdba31f6a4a40f663cd3cb | ryanpbrewster/haskell | template.hs |
import System.Environment (getArgs)
main = do
args <- getArgs
txt <- readFile (head args)
putStr $ solveProblem txt
wordsBy pred s = wordsBy' pred $ dropWhile pred s
where wordsBy' _ [] = []
wordsBy' pred s = let (f,r) = break pred s
in f:wordsBy' pred (dropWhile pred r)
solveProblem txt = let lns = lines txt
| null | https://raw.githubusercontent.com/ryanpbrewster/haskell/6edd0afe234008a48b4871032dedfd143ca6e412/CodeEval/template.hs | haskell |
import System.Environment (getArgs)
main = do
args <- getArgs
txt <- readFile (head args)
putStr $ solveProblem txt
wordsBy pred s = wordsBy' pred $ dropWhile pred s
where wordsBy' _ [] = []
wordsBy' pred s = let (f,r) = break pred s
in f:wordsBy' pred (dropWhile pred r)
solveProblem txt = let lns = lines txt
| |
7ad8dc81e3f814f86e0d4371d4b319ae06830aafc456bc4ae470628f7f763c31 | OCamlPro/typerex-lint | plugin_typedtree.polymorphic_function.1.ml | type t = A of int
let _ =
(A 3) = (A 4)
| null | https://raw.githubusercontent.com/OCamlPro/typerex-lint/6d9e994c8278fb65e1f7de91d74876531691120c/tools/ocp-lint-doc/examples/plugin_typedtree.polymorphic_function.1.ml | ocaml | type t = A of int
let _ =
(A 3) = (A 4)
| |
4a3ff34b0e115d9d3abc4af760061eaf0adf6c3953565178999f941f9d4e8aac | rabbitmq/rabbitmq-mqtt | rabbit_mqtt.erl | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
%%
Copyright ( c ) 2007 - 2020 VMware , Inc. or its affiliates . All rights reserved .
%%
-module(rabbit_mqtt).
-behaviour(application).
-export([start/2, stop/1]).
-export([connection_info_local/1,
emit_connection_info_local/3,
emit_connection_info_all/4,
close_all_client_connections/1]).
start(normal, []) ->
{ok, Listeners} = application:get_env(tcp_listeners),
{ok, SslListeners} = application:get_env(ssl_listeners),
ok = mqtt_node:start(),
Result = rabbit_mqtt_sup:start_link({Listeners, SslListeners}, []),
EMPid = case rabbit_event:start_link() of
{ok, Pid} -> Pid;
{error, {already_started, Pid}} -> Pid
end,
gen_event:add_handler(EMPid, rabbit_mqtt_internal_event_handler, []),
Result.
stop(_) ->
rabbit_mqtt_sup:stop_listeners().
-spec close_all_client_connections(string() | binary()) -> {'ok', non_neg_integer()}.
close_all_client_connections(Reason) ->
Connections = rabbit_mqtt_collector:list(),
[rabbit_mqtt_reader:close_connection(Pid, Reason) || {_, Pid} <- Connections],
{ok, length(Connections)}.
emit_connection_info_all(Nodes, Items, Ref, AggregatorPid) ->
Pids = [spawn_link(Node, rabbit_mqtt, emit_connection_info_local,
[Items, Ref, AggregatorPid])
|| Node <- Nodes],
rabbit_control_misc:await_emitters_termination(Pids),
ok.
emit_connection_info_local(Items, Ref, AggregatorPid) ->
rabbit_control_misc:emitting_map_with_exit_handler(
AggregatorPid, Ref, fun({_, Pid}) ->
rabbit_mqtt_reader:info(Pid, Items)
end,
rabbit_mqtt_collector:list()).
connection_info_local(Items) ->
Connections = rabbit_mqtt_collector:list(),
[rabbit_mqtt_reader:info(Pid, Items)
|| {_, Pid} <- Connections].
| null | https://raw.githubusercontent.com/rabbitmq/rabbitmq-mqtt/817971bfec4461630a2ef7e27d4fa9f4c4fb8ff9/src/rabbit_mqtt.erl | erlang | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
Copyright ( c ) 2007 - 2020 VMware , Inc. or its affiliates . All rights reserved .
-module(rabbit_mqtt).
-behaviour(application).
-export([start/2, stop/1]).
-export([connection_info_local/1,
emit_connection_info_local/3,
emit_connection_info_all/4,
close_all_client_connections/1]).
start(normal, []) ->
{ok, Listeners} = application:get_env(tcp_listeners),
{ok, SslListeners} = application:get_env(ssl_listeners),
ok = mqtt_node:start(),
Result = rabbit_mqtt_sup:start_link({Listeners, SslListeners}, []),
EMPid = case rabbit_event:start_link() of
{ok, Pid} -> Pid;
{error, {already_started, Pid}} -> Pid
end,
gen_event:add_handler(EMPid, rabbit_mqtt_internal_event_handler, []),
Result.
stop(_) ->
rabbit_mqtt_sup:stop_listeners().
-spec close_all_client_connections(string() | binary()) -> {'ok', non_neg_integer()}.
close_all_client_connections(Reason) ->
Connections = rabbit_mqtt_collector:list(),
[rabbit_mqtt_reader:close_connection(Pid, Reason) || {_, Pid} <- Connections],
{ok, length(Connections)}.
emit_connection_info_all(Nodes, Items, Ref, AggregatorPid) ->
Pids = [spawn_link(Node, rabbit_mqtt, emit_connection_info_local,
[Items, Ref, AggregatorPid])
|| Node <- Nodes],
rabbit_control_misc:await_emitters_termination(Pids),
ok.
emit_connection_info_local(Items, Ref, AggregatorPid) ->
rabbit_control_misc:emitting_map_with_exit_handler(
AggregatorPid, Ref, fun({_, Pid}) ->
rabbit_mqtt_reader:info(Pid, Items)
end,
rabbit_mqtt_collector:list()).
connection_info_local(Items) ->
Connections = rabbit_mqtt_collector:list(),
[rabbit_mqtt_reader:info(Pid, Items)
|| {_, Pid} <- Connections].
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.