_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 |
|---|---|---|---|---|---|---|---|---|
3347dd0b5601e6b057818099b22261c8e2936ca1c6d8bd2a78a449072e788efc | jordwalke/rehp | jsooTopPpx.ml | Js_of_ocaml library
* /
* Copyright ( C ) 2015 OCamlPro
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation , with linking exception ;
* either version 2.1 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 Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
* /
* Copyright (C) 2015 OCamlPro
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, with linking exception;
* either version 2.1 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*)
open Js_of_ocaml_compiler.Stdlib
let ppx_rewriters = ref []
let () = Ast_mapper.register_function := fun _ f -> ppx_rewriters := f :: !ppx_rewriters
let preprocess_structure str =
let open Ast_mapper in
List.fold_right !ppx_rewriters ~init:str ~f:(fun ppx_rewriter str ->
let mapper = ppx_rewriter [] in
mapper.structure mapper str )
let preprocess_signature str =
let open Ast_mapper in
List.fold_right !ppx_rewriters ~init:str ~f:(fun ppx_rewriter str ->
let mapper = ppx_rewriter [] in
mapper.signature mapper str )
let preprocess_phrase phrase =
let open Parsetree in
match phrase with
| Ptop_def str -> Ptop_def (preprocess_structure str)
| Ptop_dir _ as x -> x
| null | https://raw.githubusercontent.com/jordwalke/rehp/f122b94f0a3f06410ddba59e3c9c603b33aadabf/toplevel/lib/jsooTopPpx.ml | ocaml | Js_of_ocaml library
* /
* Copyright ( C ) 2015 OCamlPro
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation , with linking exception ;
* either version 2.1 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 Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
* /
* Copyright (C) 2015 OCamlPro
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, with linking exception;
* either version 2.1 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*)
open Js_of_ocaml_compiler.Stdlib
let ppx_rewriters = ref []
let () = Ast_mapper.register_function := fun _ f -> ppx_rewriters := f :: !ppx_rewriters
let preprocess_structure str =
let open Ast_mapper in
List.fold_right !ppx_rewriters ~init:str ~f:(fun ppx_rewriter str ->
let mapper = ppx_rewriter [] in
mapper.structure mapper str )
let preprocess_signature str =
let open Ast_mapper in
List.fold_right !ppx_rewriters ~init:str ~f:(fun ppx_rewriter str ->
let mapper = ppx_rewriter [] in
mapper.signature mapper str )
let preprocess_phrase phrase =
let open Parsetree in
match phrase with
| Ptop_def str -> Ptop_def (preprocess_structure str)
| Ptop_dir _ as x -> x
| |
27462068f2d8fb6e177e38e70ead0e072d262543372d387ac967431555cb393d | gwkkwg/cl-containers | queues.lisp | ;;;-*- Mode: Lisp; Package: containers -*-
(in-package #:containers)
;;; Abstract Queue interface
;;;
;;; supports: enqueue (insert-item), dequeue (delete-first), empty!,
size , empty - p , first - element
(defclass* abstract-queue (initial-contents-mixin ordered-container-mixin)
())
(defmethod enqueue ((queue abstract-queue) item)
(insert-item queue item))
(defmethod dequeue ((queue abstract-queue))
(delete-first queue))
(defmethod empty! ((q abstract-queue))
Dequeue items until the queue is empty . Inefficient , but always works .
(do ()
((empty-p q) q)
(delete-first q))
(values))
(defmethod first-element :before ((q abstract-queue))
(error-if-queue-empty q "Tried to examine first-element from an empty queue."))
(defmethod delete-first :before ((q abstract-queue))
(error-if-queue-empty q "Tried to dequeue from an empty queue."))
(defmethod error-if-queue-empty ((q abstract-queue) &optional
(message "Cannot work with an empty queue")
&rest rest)
(when (empty-p q)
(error message rest)))
;;; Priority Queues on 'arbitrary' containers
;;;
The underlying container must support : insert - item , first - element
;;; delete-item, empty-p, empty!, size, find-item,
;;; delete-item and delete-item-if
(defclass* priority-queue-on-container (iteratable-container-mixin
sorted-container-mixin
findable-container-mixin
concrete-container
abstract-queue)
((container nil r))
(:default-initargs
:container-type 'binary-search-tree))
(defmethod initialize-instance :around
((object priority-queue-on-container) &rest args
&key container-type &allow-other-keys)
(remf args :container-type)
(remf args :initial-contents)
(setf (slot-value object 'container)
(apply #'make-container container-type args))
(call-next-method))
(defmethod insert-item ((q priority-queue-on-container) item)
(insert-item (container q) item))
(defmethod delete-first ((q priority-queue-on-container))
(let ((m (first-node (container q))))
(delete-node (container q) m)
(element m)))
(defmethod empty-p ((q priority-queue-on-container))
(empty-p (container q)))
(defmethod empty! ((q priority-queue-on-container))
(empty! (container q))
(values))
(defmethod size ((q priority-queue-on-container))
(size (container q)))
(defmethod first-element ((q priority-queue-on-container))
(first-element (container q)))
(defmethod (setf first-element) (value (q priority-queue-on-container))
(setf (first-element (container q)) value))
(defmethod find-item ((q priority-queue-on-container) (item t))
(let ((node (find-item (container q) item)))
(when node (element node))))
(defmethod find-node ((q priority-queue-on-container) (item t))
(find-node (container q) item))
(defmethod find-element ((q priority-queue-on-container) (item t))
(find-element (container q) item))
(defmethod delete-item ((q priority-queue-on-container) (item t))
(delete-item (container q) item))
(defmethod delete-node ((q priority-queue-on-container) (item t))
(delete-node (container q) item))
(defmethod delete-element ((q priority-queue-on-container) (item t))
(delete-element (container q) item))
(defmethod delete-item-if (test (q priority-queue-on-container))
(delete-item-if test (container q)))
(defmethod iterate-nodes ((q priority-queue-on-container) fn)
(iterate-nodes (container q) fn))
(defmethod iterate-elements ((q priority-queue-on-container) fn)
(iterate-elements (container q) fn))
;;; Standard no frills queue
(defclass* basic-queue (abstract-queue iteratable-container-mixin
concrete-container)
((queue nil :accessor queue-queue)
(indexer nil :accessor queue-header))
(:documentation "A simple FIFO queue implemented as a list with extra bookkeeping for efficiency."))
;; Some semantically helpful functions
(defun front-of-queue (queue)
(car (queue-header queue)))
(defun front-of-queue! (queue new)
(setf (car (queue-header queue)) new))
(defsetf front-of-queue front-of-queue!)
(defun tail-of-queue (queue)
(cdr (queue-header queue)))
(defun tail-of-queue! (queue new)
(setf (cdr (queue-header queue)) new))
(defsetf tail-of-queue tail-of-queue!)
(eval-when (:compile-toplevel)
(proclaim '(inline front-of-queue front-of-queue!))
(proclaim '(inline tail-of-queue tail-of-queue!)))
(defmethod insert-item ((q basic-queue) (item t))
"Add an item to the queue."
(let ((new-item (list item)))
(cond ((empty-p q)
(setf (queue-queue q) new-item
(queue-header q) (cons (queue-queue q) (queue-queue q))))
(t
(setf (cdr (tail-of-queue q)) new-item
(tail-of-queue q) new-item))))
q)
(defmethod delete-first ((q basic-queue))
(let ((result (front-of-queue q)))
(setf (front-of-queue q) (cdr result)
result (first result))
;; reset things when I'm empty
(when (null (front-of-queue q))
(empty! q))
result))
(defmethod empty-p ((q basic-queue))
(null (queue-header q)))
(defmethod iterate-nodes ((q basic-queue) fn)
(let ((start (front-of-queue q)))
(mapc fn start))
(values q))
(defmethod size ((q basic-queue))
;;??slow
(if (empty-p q)
0
(length (front-of-queue q))))
(defmethod first-element ((q basic-queue))
"Returns the first item in a queue without changing the queue."
(car (front-of-queue q)))
(defmethod (setf first-element) (value (q basic-queue))
"Returns the first item in a queue without changing the queue."
(setf (car (front-of-queue q)) value))
(defmethod empty! ((q basic-queue))
"Empty a queue of all contents."
(setf (queue-queue q) nil
(queue-header q) nil)
(values))
(defmethod delete-item ((queue basic-queue) item)
(unless (empty-p queue)
(cond ((eq item (first-element queue))
(delete-first queue))
((eq item (car (tail-of-queue queue)))
;; expensive special case...
(setf (queue-queue queue) (remove item (queue-queue queue))
(front-of-queue queue) (queue-queue queue)
(tail-of-queue queue) (last (front-of-queue queue))))
(t
(setf (queue-queue queue) (delete item (queue-queue queue)))))))
| null | https://raw.githubusercontent.com/gwkkwg/cl-containers/3d1df53c22403121bffb5d553cf7acb1503850e7/dev/queues.lisp | lisp | -*- Mode: Lisp; Package: containers -*-
Abstract Queue interface
supports: enqueue (insert-item), dequeue (delete-first), empty!,
Priority Queues on 'arbitrary' containers
delete-item, empty-p, empty!, size, find-item,
delete-item and delete-item-if
Standard no frills queue
Some semantically helpful functions
reset things when I'm empty
??slow
expensive special case... |
(in-package #:containers)
size , empty - p , first - element
(defclass* abstract-queue (initial-contents-mixin ordered-container-mixin)
())
(defmethod enqueue ((queue abstract-queue) item)
(insert-item queue item))
(defmethod dequeue ((queue abstract-queue))
(delete-first queue))
(defmethod empty! ((q abstract-queue))
Dequeue items until the queue is empty . Inefficient , but always works .
(do ()
((empty-p q) q)
(delete-first q))
(values))
(defmethod first-element :before ((q abstract-queue))
(error-if-queue-empty q "Tried to examine first-element from an empty queue."))
(defmethod delete-first :before ((q abstract-queue))
(error-if-queue-empty q "Tried to dequeue from an empty queue."))
(defmethod error-if-queue-empty ((q abstract-queue) &optional
(message "Cannot work with an empty queue")
&rest rest)
(when (empty-p q)
(error message rest)))
The underlying container must support : insert - item , first - element
(defclass* priority-queue-on-container (iteratable-container-mixin
sorted-container-mixin
findable-container-mixin
concrete-container
abstract-queue)
((container nil r))
(:default-initargs
:container-type 'binary-search-tree))
(defmethod initialize-instance :around
((object priority-queue-on-container) &rest args
&key container-type &allow-other-keys)
(remf args :container-type)
(remf args :initial-contents)
(setf (slot-value object 'container)
(apply #'make-container container-type args))
(call-next-method))
(defmethod insert-item ((q priority-queue-on-container) item)
(insert-item (container q) item))
(defmethod delete-first ((q priority-queue-on-container))
(let ((m (first-node (container q))))
(delete-node (container q) m)
(element m)))
(defmethod empty-p ((q priority-queue-on-container))
(empty-p (container q)))
(defmethod empty! ((q priority-queue-on-container))
(empty! (container q))
(values))
(defmethod size ((q priority-queue-on-container))
(size (container q)))
(defmethod first-element ((q priority-queue-on-container))
(first-element (container q)))
(defmethod (setf first-element) (value (q priority-queue-on-container))
(setf (first-element (container q)) value))
(defmethod find-item ((q priority-queue-on-container) (item t))
(let ((node (find-item (container q) item)))
(when node (element node))))
(defmethod find-node ((q priority-queue-on-container) (item t))
(find-node (container q) item))
(defmethod find-element ((q priority-queue-on-container) (item t))
(find-element (container q) item))
(defmethod delete-item ((q priority-queue-on-container) (item t))
(delete-item (container q) item))
(defmethod delete-node ((q priority-queue-on-container) (item t))
(delete-node (container q) item))
(defmethod delete-element ((q priority-queue-on-container) (item t))
(delete-element (container q) item))
(defmethod delete-item-if (test (q priority-queue-on-container))
(delete-item-if test (container q)))
(defmethod iterate-nodes ((q priority-queue-on-container) fn)
(iterate-nodes (container q) fn))
(defmethod iterate-elements ((q priority-queue-on-container) fn)
(iterate-elements (container q) fn))
(defclass* basic-queue (abstract-queue iteratable-container-mixin
concrete-container)
((queue nil :accessor queue-queue)
(indexer nil :accessor queue-header))
(:documentation "A simple FIFO queue implemented as a list with extra bookkeeping for efficiency."))
(defun front-of-queue (queue)
(car (queue-header queue)))
(defun front-of-queue! (queue new)
(setf (car (queue-header queue)) new))
(defsetf front-of-queue front-of-queue!)
(defun tail-of-queue (queue)
(cdr (queue-header queue)))
(defun tail-of-queue! (queue new)
(setf (cdr (queue-header queue)) new))
(defsetf tail-of-queue tail-of-queue!)
(eval-when (:compile-toplevel)
(proclaim '(inline front-of-queue front-of-queue!))
(proclaim '(inline tail-of-queue tail-of-queue!)))
(defmethod insert-item ((q basic-queue) (item t))
"Add an item to the queue."
(let ((new-item (list item)))
(cond ((empty-p q)
(setf (queue-queue q) new-item
(queue-header q) (cons (queue-queue q) (queue-queue q))))
(t
(setf (cdr (tail-of-queue q)) new-item
(tail-of-queue q) new-item))))
q)
(defmethod delete-first ((q basic-queue))
(let ((result (front-of-queue q)))
(setf (front-of-queue q) (cdr result)
result (first result))
(when (null (front-of-queue q))
(empty! q))
result))
(defmethod empty-p ((q basic-queue))
(null (queue-header q)))
(defmethod iterate-nodes ((q basic-queue) fn)
(let ((start (front-of-queue q)))
(mapc fn start))
(values q))
(defmethod size ((q basic-queue))
(if (empty-p q)
0
(length (front-of-queue q))))
(defmethod first-element ((q basic-queue))
"Returns the first item in a queue without changing the queue."
(car (front-of-queue q)))
(defmethod (setf first-element) (value (q basic-queue))
"Returns the first item in a queue without changing the queue."
(setf (car (front-of-queue q)) value))
(defmethod empty! ((q basic-queue))
"Empty a queue of all contents."
(setf (queue-queue q) nil
(queue-header q) nil)
(values))
(defmethod delete-item ((queue basic-queue) item)
(unless (empty-p queue)
(cond ((eq item (first-element queue))
(delete-first queue))
((eq item (car (tail-of-queue queue)))
(setf (queue-queue queue) (remove item (queue-queue queue))
(front-of-queue queue) (queue-queue queue)
(tail-of-queue queue) (last (front-of-queue queue))))
(t
(setf (queue-queue queue) (delete item (queue-queue queue)))))))
|
c95a5d998a6a816d58904c1dea4c0b9d1fcaa2d1edf9e6f7e63353d1906635d3 | well-typed/optics | Prism.hs | -- |
-- Module: Optics.Prism
Description : A generalised or first - class constructor .
--
-- A 'Prism' generalises the notion of a constructor (just as a
-- 'Optics.Lens.Lens' generalises the notion of a field).
--
module Optics.Prism
(
-- * Formation
Prism
, Prism'
-- * Introduction
, prism
-- * Elimination
-- | A 'Prism' is in particular an 'Optics.AffineFold.AffineFold',
an ' Optics . . ' , a
' Optics . Review . Review ' and a ' Optics . Setter . Setter ' , therefore you can
-- specialise types to obtain:
--
-- @
-- 'Optics.AffineFold.preview' :: 'Prism'' s a -> s -> Maybe a
-- 'Optics.Review.review' :: 'Prism'' s a -> a -> s
-- @
--
-- @
-- 'Optics.Setter.over' :: 'Prism' s t a b -> (a -> b) -> s -> t
-- 'Optics.Setter.set' :: 'Prism' s t a b -> b -> s -> t
-- 'Optics.AffineTraversal.matching' :: 'Prism' s t a b -> s -> Either t a
-- @
--
-- If you want to 'Optics.AffineFold.preview' a type-modifying 'Prism' that is
-- insufficiently polymorphic to be used as a type-preserving 'Prism'', use
-- 'Optics.ReadOnly.getting':
--
-- @
-- 'Optics.AffineFold.preview' . 'Optics.ReadOnly.getting' :: 'Prism' s t a b -> s -> 'Maybe' a
-- @
-- * Computation
-- |
--
-- @
-- 'Optics.Review.review' ('prism' f g) ≡ f
-- 'Optics.AffineTraversal.matching' ('prism' f g) ≡ g
-- @
-- * Well-formedness
-- |
--
-- @
-- 'Optics.AffineTraversal.matching' o ('Optics.Review.review' o b) ≡ 'Right' b
-- 'Optics.AffineTraversal.matching' o s ≡ 'Right' a => 'Optics.Review.review' o a ≡ s
-- @
-- * Additional introduction forms
-- | See "Data.Maybe.Optics" and "Data.Either.Optics" for 'Prism's for the
-- corresponding types, and 'Optics.Cons.Core._Cons', 'Optics.Cons.Core._Snoc'
-- and 'Optics.Empty.Core._Empty' for 'Prism's for container types.
, prism'
, only
, nearly
-- * Additional elimination forms
, withPrism
-- * Combinators
, aside
, without
, below
-- * Subtyping
, A_Prism
-- | <<diagrams/Prism.png Prism in the optics hierarchy>>
)
where
import Control.Monad
import Data.Bifunctor
import Data.Profunctor.Indexed
import Optics.Internal.Optic
-- | Type synonym for a type-modifying prism.
type Prism s t a b = Optic A_Prism NoIx s t a b
-- | Type synonym for a type-preserving prism.
type Prism' s a = Optic' A_Prism NoIx s a
-- | Build a prism from a constructor and a matcher, which must respect the
-- well-formedness laws.
--
If you want to build a ' Prism ' from the representation , use
-- @prismVL@ from the @optics-vl@ package.
prism :: (b -> t) -> (s -> Either t a) -> Prism s t a b
prism construct match = Optic $ dimap match (either id construct) . right'
# INLINE prism #
-- | This is usually used to build a 'Prism'', when you have to use an operation
like ' Data.Typeable.cast ' which already returns a ' Maybe ' .
prism' :: (b -> s) -> (s -> Maybe a) -> Prism s s a b
prism' bs sma = prism bs (\s -> maybe (Left s) Right (sma s))
{-# INLINE prism' #-}
-- | Work with a 'Prism' as a constructor and a matcher.
withPrism
:: Is k A_Prism
=> Optic k is s t a b
-> ((b -> t) -> (s -> Either t a) -> r)
-> r
withPrism o k = case getOptic (castOptic @A_Prism o) (Market id Right) of
Market construct match -> k construct match
# INLINE withPrism #
----------------------------------------
-- | Use a 'Prism' to work over part of a structure.
aside :: Is k A_Prism => Optic k is s t a b -> Prism (e, s) (e, t) (e, a) (e, b)
aside k =
withPrism k $ \bt seta ->
prism (fmap bt) $ \(e,s) ->
case seta s of
Left t -> Left (e,t)
Right a -> Right (e,a)
# INLINE aside #
-- | Given a pair of prisms, project sums.
--
-- Viewing a 'Prism' as a co-'Optics.Lens.Lens', this combinator can be seen to
-- be dual to 'Optics.Lens.alongside'.
without
:: (Is k A_Prism, Is l A_Prism)
=> Optic k is s t a b
-> Optic l is u v c d
-> Prism (Either s u) (Either t v) (Either a c) (Either b d)
without k =
withPrism k $ \bt seta k' ->
withPrism k' $ \dv uevc ->
prism (bimap bt dv) $ \su ->
case su of
Left s -> bimap Left Left (seta s)
Right u -> bimap Right Right (uevc u)
# INLINE without #
| Lift a ' Prism ' through a ' ' functor , giving a ' Prism ' that
-- matches only if all the elements of the container match the 'Prism'.
below
:: (Is k A_Prism, Traversable f)
=> Optic' k is s a
-> Prism' (f s) (f a)
below k =
withPrism k $ \bt seta ->
prism (fmap bt) $ \s ->
case traverse seta s of
Left _ -> Left s
Right t -> Right t
# INLINE below #
-- | This 'Prism' compares for exact equality with a given value.
--
> > > only 4 # ( )
4
--
> > > 5 ^ ? only 4
-- Nothing
only :: Eq a => a -> Prism' a ()
only a = prism' (\() -> a) $ guard . (a ==)
# INLINE only #
-- | This 'Prism' compares for approximate equality with a given value and a
-- predicate for testing, an example where the value is the empty list and the
-- predicate checks that a list is empty (same as 'Optics.Empty._Empty' with the
' Optics . Empty . ' list instance ):
--
-- >>> nearly [] null # ()
-- []
-- >>> [1,2,3,4] ^? nearly [] null
-- Nothing
--
-- @'nearly' [] 'Prelude.null' :: 'Prism'' [a] ()@
--
-- To comply with the 'Prism' laws the arguments you supply to @nearly a p@ are
-- somewhat constrained.
--
We assume @p holds iff @x ≡ a@. Under that assumption then this is a valid
-- 'Prism'.
--
-- This is useful when working with a type where you can test equality for only
-- a subset of its values, and the prism selects such a value.
nearly :: a -> (a -> Bool) -> Prism' a ()
nearly a p = prism' (\() -> a) $ guard . p
# INLINE nearly #
-- $setup
> > > import Optics . Core
| null | https://raw.githubusercontent.com/well-typed/optics/7cc3f9c334cdf69feaf10f58b11d3dbe2f98812c/optics-core/src/Optics/Prism.hs | haskell | |
Module: Optics.Prism
A 'Prism' generalises the notion of a constructor (just as a
'Optics.Lens.Lens' generalises the notion of a field).
* Formation
* Introduction
* Elimination
| A 'Prism' is in particular an 'Optics.AffineFold.AffineFold',
specialise types to obtain:
@
'Optics.AffineFold.preview' :: 'Prism'' s a -> s -> Maybe a
'Optics.Review.review' :: 'Prism'' s a -> a -> s
@
@
'Optics.Setter.over' :: 'Prism' s t a b -> (a -> b) -> s -> t
'Optics.Setter.set' :: 'Prism' s t a b -> b -> s -> t
'Optics.AffineTraversal.matching' :: 'Prism' s t a b -> s -> Either t a
@
If you want to 'Optics.AffineFold.preview' a type-modifying 'Prism' that is
insufficiently polymorphic to be used as a type-preserving 'Prism'', use
'Optics.ReadOnly.getting':
@
'Optics.AffineFold.preview' . 'Optics.ReadOnly.getting' :: 'Prism' s t a b -> s -> 'Maybe' a
@
* Computation
|
@
'Optics.Review.review' ('prism' f g) ≡ f
'Optics.AffineTraversal.matching' ('prism' f g) ≡ g
@
* Well-formedness
|
@
'Optics.AffineTraversal.matching' o ('Optics.Review.review' o b) ≡ 'Right' b
'Optics.AffineTraversal.matching' o s ≡ 'Right' a => 'Optics.Review.review' o a ≡ s
@
* Additional introduction forms
| See "Data.Maybe.Optics" and "Data.Either.Optics" for 'Prism's for the
corresponding types, and 'Optics.Cons.Core._Cons', 'Optics.Cons.Core._Snoc'
and 'Optics.Empty.Core._Empty' for 'Prism's for container types.
* Additional elimination forms
* Combinators
* Subtyping
| <<diagrams/Prism.png Prism in the optics hierarchy>>
| Type synonym for a type-modifying prism.
| Type synonym for a type-preserving prism.
| Build a prism from a constructor and a matcher, which must respect the
well-formedness laws.
@prismVL@ from the @optics-vl@ package.
| This is usually used to build a 'Prism'', when you have to use an operation
# INLINE prism' #
| Work with a 'Prism' as a constructor and a matcher.
--------------------------------------
| Use a 'Prism' to work over part of a structure.
| Given a pair of prisms, project sums.
Viewing a 'Prism' as a co-'Optics.Lens.Lens', this combinator can be seen to
be dual to 'Optics.Lens.alongside'.
matches only if all the elements of the container match the 'Prism'.
| This 'Prism' compares for exact equality with a given value.
Nothing
| This 'Prism' compares for approximate equality with a given value and a
predicate for testing, an example where the value is the empty list and the
predicate checks that a list is empty (same as 'Optics.Empty._Empty' with the
>>> nearly [] null # ()
[]
>>> [1,2,3,4] ^? nearly [] null
Nothing
@'nearly' [] 'Prelude.null' :: 'Prism'' [a] ()@
To comply with the 'Prism' laws the arguments you supply to @nearly a p@ are
somewhat constrained.
'Prism'.
This is useful when working with a type where you can test equality for only
a subset of its values, and the prism selects such a value.
$setup | Description : A generalised or first - class constructor .
module Optics.Prism
(
Prism
, Prism'
, prism
an ' Optics . . ' , a
' Optics . Review . Review ' and a ' Optics . Setter . Setter ' , therefore you can
, prism'
, only
, nearly
, withPrism
, aside
, without
, below
, A_Prism
)
where
import Control.Monad
import Data.Bifunctor
import Data.Profunctor.Indexed
import Optics.Internal.Optic
type Prism s t a b = Optic A_Prism NoIx s t a b
type Prism' s a = Optic' A_Prism NoIx s a
If you want to build a ' Prism ' from the representation , use
prism :: (b -> t) -> (s -> Either t a) -> Prism s t a b
prism construct match = Optic $ dimap match (either id construct) . right'
# INLINE prism #
like ' Data.Typeable.cast ' which already returns a ' Maybe ' .
prism' :: (b -> s) -> (s -> Maybe a) -> Prism s s a b
prism' bs sma = prism bs (\s -> maybe (Left s) Right (sma s))
withPrism
:: Is k A_Prism
=> Optic k is s t a b
-> ((b -> t) -> (s -> Either t a) -> r)
-> r
withPrism o k = case getOptic (castOptic @A_Prism o) (Market id Right) of
Market construct match -> k construct match
# INLINE withPrism #
aside :: Is k A_Prism => Optic k is s t a b -> Prism (e, s) (e, t) (e, a) (e, b)
aside k =
withPrism k $ \bt seta ->
prism (fmap bt) $ \(e,s) ->
case seta s of
Left t -> Left (e,t)
Right a -> Right (e,a)
# INLINE aside #
without
:: (Is k A_Prism, Is l A_Prism)
=> Optic k is s t a b
-> Optic l is u v c d
-> Prism (Either s u) (Either t v) (Either a c) (Either b d)
without k =
withPrism k $ \bt seta k' ->
withPrism k' $ \dv uevc ->
prism (bimap bt dv) $ \su ->
case su of
Left s -> bimap Left Left (seta s)
Right u -> bimap Right Right (uevc u)
# INLINE without #
| Lift a ' Prism ' through a ' ' functor , giving a ' Prism ' that
below
:: (Is k A_Prism, Traversable f)
=> Optic' k is s a
-> Prism' (f s) (f a)
below k =
withPrism k $ \bt seta ->
prism (fmap bt) $ \s ->
case traverse seta s of
Left _ -> Left s
Right t -> Right t
# INLINE below #
> > > only 4 # ( )
4
> > > 5 ^ ? only 4
only :: Eq a => a -> Prism' a ()
only a = prism' (\() -> a) $ guard . (a ==)
# INLINE only #
' Optics . Empty . ' list instance ):
We assume @p holds iff @x ≡ a@. Under that assumption then this is a valid
nearly :: a -> (a -> Bool) -> Prism' a ()
nearly a p = prism' (\() -> a) $ guard . p
# INLINE nearly #
> > > import Optics . Core
|
b8f5956271baef49e642b8f88e004dc8ffaaa1760485f33e641cf49fde55ea0a | dbuenzli/ptime | ptime_clock.mli | ---------------------------------------------------------------------------
Copyright ( c ) 2015 The ptime programmers . All rights reserved .
Distributed under the ISC license , see terms at the end of the file .
---------------------------------------------------------------------------
Copyright (c) 2015 The ptime programmers. All rights reserved.
Distributed under the ISC license, see terms at the end of the file.
---------------------------------------------------------------------------*)
* POSIX time clock .
[ Ptime_clock ] provides access to a system POSIX time clock and to
the system 's current time zone offset .
This time does not increase monotically and is subject to system
calendar time adjustments . Use { ! } if you need monotonic
wall - clock time to measure time spans .
Consult important information about { { ! handling }
and { { ! platform_support}platform support } .
[Ptime_clock] provides access to a system POSIX time clock and to
the system's current time zone offset.
This time does not increase monotically and is subject to system
calendar time adjustments. Use {!Mtime} if you need monotonic
wall-clock time to measure time spans.
Consult important information about {{!err}error handling}
and {{!platform_support}platform support}. *)
* { 1 : clock POSIX clock }
val now : unit -> Ptime.t
* [ now ( ) ] is the current POSIX time , by definition always on the
UTC timeline .
@raise Sys_error see { { ! handling } .
UTC timeline.
@raise Sys_error see {{!err}error handling}. *)
val period : unit -> Ptime.span option
(** [period ()] is a positive POSIX time span representing
the clock's period (if available). *)
* { 1 : tz System time zone offset }
val current_tz_offset_s : unit -> Ptime.tz_offset_s option
* [ current_tz_offset_s ( ) ] is the system 's current local time zone
offset to UTC in seconds , if known . This is the duration local
time - UTC time in seconds .
offset to UTC in seconds, if known. This is the duration local
time - UTC time in seconds. *)
* { 1 : raw POSIX clock raw interface }
val now_d_ps : unit -> int * int64
* [ now_d_ps ( ) ] is [ ( d , ps ) ] representing POSIX time occuring at
[ d ] * 86'400e12 + [ ps ] POSIX picoseconds from the epoch
1970 - 01 - 01 00:00:00 UTC . [ ps ] is in the range
\[[0];[86_399_999_999_999_999L]\ ] .
@raise Sys_error see { { ! handling }
[d] * 86'400e12 + [ps] POSIX picoseconds from the epoch
1970-01-01 00:00:00 UTC. [ps] is in the range
\[[0];[86_399_999_999_999_999L]\].
@raise Sys_error see {{!err}error handling} *)
val period_d_ps : unit -> (int * int64) option
(** [period_d_ps ()] is if available [Some (d, ps)] representing the
clock's picosecond period [d] * 86'400e12 + [ps]. [ps] is in the
range \[[0];[86_399_999_999_999_999L]\]. *)
* { 1 : err Error handling }
The functions { ! now } and { ! } raise [ Sys_error ] whenever
they ca n't determine the current time or that it does n't fit in
[ Ptime ] 's well - defined { { ! Ptime.t}range } . This exception should
only be catched at the toplevel of your program to log it and
abort the program . It indicates a serious error condition in the
system .
All the other functions , whose functionality is less essential ,
simply silently return [ None ] if they ca n't determine the
information either because it is unavailable or because an error
occured .
{ 1 : platform_support Platform support }
{ ul
{ - Platforms with a POSIX clock ( includes Linux ) use
{ { : }[clock_gettime ] } with [ CLOCK_REALTIME ] . }
{ - On { { : / }
[ gettimeofday ] } is used . }
{ - On Windows
{ { : -us/library/windows/desktop/ms724390(v=vs.85).aspx}[GetSystemTime ] }
and
{ { : -us/library/windows/desktop/ms724421(v=vs.85).aspx}[GetTimeZoneInformation ] }
are used . }
{ - On JavaScript
{ { : ) ] } and
{ { : -international.org/ecma-262/6.0/index.html#sec-date.prototype.gettimezoneoffset}[Date.prototype.getTimezoneOffset ] } are used . } }
The functions {!now} and {!now_d_ps} raise [Sys_error] whenever
they can't determine the current time or that it doesn't fit in
[Ptime]'s well-defined {{!Ptime.t}range}. This exception should
only be catched at the toplevel of your program to log it and
abort the program. It indicates a serious error condition in the
system.
All the other functions, whose functionality is less essential,
simply silently return [None] if they can't determine the
information either because it is unavailable or because an error
occured.
{1:platform_support Platform support}
{ul
{- Platforms with a POSIX clock (includes Linux) use
{{:}[clock_gettime]} with [CLOCK_REALTIME].}
{- On Darwin {{:/}
[gettimeofday]} is used.}
{- On Windows
{{:-us/library/windows/desktop/ms724390(v=vs.85).aspx}[GetSystemTime]}
and
{{:-us/library/windows/desktop/ms724421(v=vs.85).aspx}[GetTimeZoneInformation]}
are used.}
{- On JavaScript
{{:-international.org/ecma-262/6.0/index.html#sec-date.now}[Date.now ()]} and
{{:-international.org/ecma-262/6.0/index.html#sec-date.prototype.gettimezoneoffset}[Date.prototype.getTimezoneOffset]} are used.}} *)
---------------------------------------------------------------------------
Copyright ( c ) 2015 The ptime programmers
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
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) 2015 The ptime programmers
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.
---------------------------------------------------------------------------*)
| null | https://raw.githubusercontent.com/dbuenzli/ptime/c6ef2dbf5d1fae2007b28cf41e45a0d383c3a303/src-clock/ptime_clock.mli | ocaml | * [period ()] is a positive POSIX time span representing
the clock's period (if available).
* [period_d_ps ()] is if available [Some (d, ps)] representing the
clock's picosecond period [d] * 86'400e12 + [ps]. [ps] is in the
range \[[0];[86_399_999_999_999_999L]\]. | ---------------------------------------------------------------------------
Copyright ( c ) 2015 The ptime programmers . All rights reserved .
Distributed under the ISC license , see terms at the end of the file .
---------------------------------------------------------------------------
Copyright (c) 2015 The ptime programmers. All rights reserved.
Distributed under the ISC license, see terms at the end of the file.
---------------------------------------------------------------------------*)
* POSIX time clock .
[ Ptime_clock ] provides access to a system POSIX time clock and to
the system 's current time zone offset .
This time does not increase monotically and is subject to system
calendar time adjustments . Use { ! } if you need monotonic
wall - clock time to measure time spans .
Consult important information about { { ! handling }
and { { ! platform_support}platform support } .
[Ptime_clock] provides access to a system POSIX time clock and to
the system's current time zone offset.
This time does not increase monotically and is subject to system
calendar time adjustments. Use {!Mtime} if you need monotonic
wall-clock time to measure time spans.
Consult important information about {{!err}error handling}
and {{!platform_support}platform support}. *)
* { 1 : clock POSIX clock }
val now : unit -> Ptime.t
* [ now ( ) ] is the current POSIX time , by definition always on the
UTC timeline .
@raise Sys_error see { { ! handling } .
UTC timeline.
@raise Sys_error see {{!err}error handling}. *)
val period : unit -> Ptime.span option
* { 1 : tz System time zone offset }
val current_tz_offset_s : unit -> Ptime.tz_offset_s option
* [ current_tz_offset_s ( ) ] is the system 's current local time zone
offset to UTC in seconds , if known . This is the duration local
time - UTC time in seconds .
offset to UTC in seconds, if known. This is the duration local
time - UTC time in seconds. *)
* { 1 : raw POSIX clock raw interface }
val now_d_ps : unit -> int * int64
* [ now_d_ps ( ) ] is [ ( d , ps ) ] representing POSIX time occuring at
[ d ] * 86'400e12 + [ ps ] POSIX picoseconds from the epoch
1970 - 01 - 01 00:00:00 UTC . [ ps ] is in the range
\[[0];[86_399_999_999_999_999L]\ ] .
@raise Sys_error see { { ! handling }
[d] * 86'400e12 + [ps] POSIX picoseconds from the epoch
1970-01-01 00:00:00 UTC. [ps] is in the range
\[[0];[86_399_999_999_999_999L]\].
@raise Sys_error see {{!err}error handling} *)
val period_d_ps : unit -> (int * int64) option
* { 1 : err Error handling }
The functions { ! now } and { ! } raise [ Sys_error ] whenever
they ca n't determine the current time or that it does n't fit in
[ Ptime ] 's well - defined { { ! Ptime.t}range } . This exception should
only be catched at the toplevel of your program to log it and
abort the program . It indicates a serious error condition in the
system .
All the other functions , whose functionality is less essential ,
simply silently return [ None ] if they ca n't determine the
information either because it is unavailable or because an error
occured .
{ 1 : platform_support Platform support }
{ ul
{ - Platforms with a POSIX clock ( includes Linux ) use
{ { : }[clock_gettime ] } with [ CLOCK_REALTIME ] . }
{ - On { { : / }
[ gettimeofday ] } is used . }
{ - On Windows
{ { : -us/library/windows/desktop/ms724390(v=vs.85).aspx}[GetSystemTime ] }
and
{ { : -us/library/windows/desktop/ms724421(v=vs.85).aspx}[GetTimeZoneInformation ] }
are used . }
{ - On JavaScript
{ { : ) ] } and
{ { : -international.org/ecma-262/6.0/index.html#sec-date.prototype.gettimezoneoffset}[Date.prototype.getTimezoneOffset ] } are used . } }
The functions {!now} and {!now_d_ps} raise [Sys_error] whenever
they can't determine the current time or that it doesn't fit in
[Ptime]'s well-defined {{!Ptime.t}range}. This exception should
only be catched at the toplevel of your program to log it and
abort the program. It indicates a serious error condition in the
system.
All the other functions, whose functionality is less essential,
simply silently return [None] if they can't determine the
information either because it is unavailable or because an error
occured.
{1:platform_support Platform support}
{ul
{- Platforms with a POSIX clock (includes Linux) use
{{:}[clock_gettime]} with [CLOCK_REALTIME].}
{- On Darwin {{:/}
[gettimeofday]} is used.}
{- On Windows
{{:-us/library/windows/desktop/ms724390(v=vs.85).aspx}[GetSystemTime]}
and
{{:-us/library/windows/desktop/ms724421(v=vs.85).aspx}[GetTimeZoneInformation]}
are used.}
{- On JavaScript
{{:-international.org/ecma-262/6.0/index.html#sec-date.now}[Date.now ()]} and
{{:-international.org/ecma-262/6.0/index.html#sec-date.prototype.gettimezoneoffset}[Date.prototype.getTimezoneOffset]} are used.}} *)
---------------------------------------------------------------------------
Copyright ( c ) 2015 The ptime programmers
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
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) 2015 The ptime programmers
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.
---------------------------------------------------------------------------*)
|
74a6183ce9e30a550b52267d7f478cb70f8b497811928a676979c2ece7fb9dd5 | hslua/hslua | DocumentationTests.hs | {-# LANGUAGE OverloadedStrings #-}
# LANGUAGE TypeApplications #
|
Module : HsLua . Packaging . DocumentationTests
Copyright : © 2021 - 2023 : MIT
Maintainer : < tarleb+ >
Tests for calling exposed functions .
Module : HsLua.Packaging.DocumentationTests
Copyright : © 2021-2023 Albert Krewinkel
License : MIT
Maintainer : Albert Krewinkel <tarleb+>
Tests for calling exposed Haskell functions.
-}
module HsLua.Packaging.DocumentationTests (tests) where
import Data.Version (makeVersion)
import HsLua.Core (top, Status (OK), Type (TypeNil, TypeString))
import HsLua.Packaging.Documentation
import HsLua.Packaging.Function
import HsLua.Marshalling (forcePeek, peekIntegral, pushIntegral, peekText)
import Test.Tasty.HsLua ((=:), shouldBeResultOf)
import Test.Tasty (TestTree, testGroup)
import qualified HsLua.Core as Lua
| Calling Haskell functions from Lua .
tests :: TestTree
tests = testGroup "Documentation"
[ testGroup "Function docs"
[ "retrieves function docs" =:
"factorial" `shouldBeResultOf` do
pushDocumentedFunction factorial
Lua.setglobal (functionName factorial)
pushDocumentedFunction documentation
Lua.setglobal "documentation"
OK <- Lua.dostring "return documentation(factorial)"
TypeString <- Lua.getfield top "name"
forcePeek $ peekText top
, "returns nil for undocumented function" =:
TypeNil `shouldBeResultOf` do
pushDocumentedFunction documentation
Lua.setglobal "documentation"
OK <- Lua.dostring "return documentation(function () return 1 end)"
Lua.ltype top
]
]
factorial :: DocumentedFunction Lua.Exception
factorial = defun "factorial" (liftPure $ \n -> product [1..n])
<#> parameter (peekIntegral @Integer) "integer" "n" ""
=#> functionResult pushIntegral "integer or string" "factorial"
#? "Calculates the factorial of a positive integer."
`since` makeVersion [1,0,0]
| null | https://raw.githubusercontent.com/hslua/hslua/178c225f3da193f09fc27877a5a30e66eef069fb/hslua-packaging/test/HsLua/Packaging/DocumentationTests.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE TypeApplications #
|
Module : HsLua . Packaging . DocumentationTests
Copyright : © 2021 - 2023 : MIT
Maintainer : < tarleb+ >
Tests for calling exposed functions .
Module : HsLua.Packaging.DocumentationTests
Copyright : © 2021-2023 Albert Krewinkel
License : MIT
Maintainer : Albert Krewinkel <tarleb+>
Tests for calling exposed Haskell functions.
-}
module HsLua.Packaging.DocumentationTests (tests) where
import Data.Version (makeVersion)
import HsLua.Core (top, Status (OK), Type (TypeNil, TypeString))
import HsLua.Packaging.Documentation
import HsLua.Packaging.Function
import HsLua.Marshalling (forcePeek, peekIntegral, pushIntegral, peekText)
import Test.Tasty.HsLua ((=:), shouldBeResultOf)
import Test.Tasty (TestTree, testGroup)
import qualified HsLua.Core as Lua
| Calling Haskell functions from Lua .
tests :: TestTree
tests = testGroup "Documentation"
[ testGroup "Function docs"
[ "retrieves function docs" =:
"factorial" `shouldBeResultOf` do
pushDocumentedFunction factorial
Lua.setglobal (functionName factorial)
pushDocumentedFunction documentation
Lua.setglobal "documentation"
OK <- Lua.dostring "return documentation(factorial)"
TypeString <- Lua.getfield top "name"
forcePeek $ peekText top
, "returns nil for undocumented function" =:
TypeNil `shouldBeResultOf` do
pushDocumentedFunction documentation
Lua.setglobal "documentation"
OK <- Lua.dostring "return documentation(function () return 1 end)"
Lua.ltype top
]
]
factorial :: DocumentedFunction Lua.Exception
factorial = defun "factorial" (liftPure $ \n -> product [1..n])
<#> parameter (peekIntegral @Integer) "integer" "n" ""
=#> functionResult pushIntegral "integer or string" "factorial"
#? "Calculates the factorial of a positive integer."
`since` makeVersion [1,0,0]
|
0cd6d8dccc359559affa5c8df196f3681f902cd29ced58c4a0d23cc6301c7634 | klimenko-serj/cl-fbclient | cl-fbclient-statement.lisp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
cl-fbclient-statement.lisp
;;;; STATEMENT
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package #:cl-fbclient)
;;===================================================================================
;;-----------------------------------------------------------------------------------
(defun make-stmt-handler ()
(cffi:foreign-alloc 'isc_stmt_handle :initial-element 0))
;;-----------------------------------------------------------------------------------
(defun XSQLDA-length (n)
(+ (cffi:foreign-type-size '(:struct XSQLDA))
(* (- n 1) (cffi:foreign-type-size '(:struct XSQLVAR)))))
;;-----------------------------------------------------------------------------------
(defun make-xsqlda (n)
(let ((new-xsqlda (cffi:foreign-alloc :char :count (XSQLDA-length n))))
;;:initial-element 0))) speed optimization?
(setf (cffi:foreign-slot-value new-xsqlda '(:struct xsqlda) 'version) 1
(cffi:foreign-slot-value new-xsqlda '(:struct xsqlda) 'sqln) n)
new-xsqlda))
;;-----------------------------------------------------------------------------------
(defun need-remake-xsqlda (tmp-xsqlda)
(> (cffi:foreign-slot-value tmp-xsqlda '(:struct xsqlda) 'sqld)
(cffi:foreign-slot-value tmp-xsqlda '(:struct xsqlda) 'sqln)))
;;-----------------------------------------------------------------------------------
(defun remake-xsqlda (tmp-xsqlda)
(unwind-protect
(make-xsqlda (cffi:foreign-slot-value tmp-xsqlda '(:struct xsqlda) 'sqld))
(cffi-sys:foreign-free tmp-xsqlda)))
;;-----------------------------------------------------------------------------------
(defun get-var-type-by-fbtype-num (type-num)
(case type-num
(496 ':int)
(500 ':short)
(482 ':float)
(480 ':double)
(452 ':text)
(448 ':varying)
(510 ':timestamp)
(580 ':decimal)
(520 ':blob)
;...
;TODO: other types
(T (error (format t "Unknown type #~A!~%" type-num)))))
;;===================================================================================
%
;;-----------------------------------------------------------------------------------
(defmacro %var (%xsqlda %index)
`(cffi:mem-aptr
(cffi:foreign-slot-pointer ,%xsqlda '(:struct xsqlda) 'sqlvar)
'(:struct xsqlvar) ,%index))
;;-----------------------------------------------------------------------------------
(defmacro %var-slot (%xsqlda %index %slot-name)
`(cffi:foreign-slot-value
(%var ,%xsqlda ,%index)
'(:struct xsqlvar) ,%slot-name))
;;-----------------------------------------------------------------------------------
(defmacro %vars-count-1 (%xsqlda)
`(- (cffi:foreign-slot-value ,%xsqlda '(:struct xsqlda) 'sqld) 1))
;;-----------------------------------------------------------------------------------
;;===================================================================================
;;-----------------------------------------------------------------------------------
(defun get-var-type (xsqlda* index)
(let ((tp (%var-slot xsqlda* index 'sqltype))
(can-nil T))
(if (oddp tp)
(decf tp)
(setf can-nil nil))
(values-list (list (get-var-type-by-fbtype-num tp) can-nil))))
;;-----------------------------------------------------------------------------------
(defun get-var-sqlln (xsqlda* index)
(cffi:foreign-slot-value
(%var xsqlda* index)
'(:struct xsqlvar) 'sqllen))
;;-----------------------------------------------------------------------------------
(defun alloc-var-data-default (xsqlda* index)
(setf (%var-slot xsqlda* index 'sqldata)
(cffi:foreign-alloc :char
:initial-element 0
:count (get-var-sqlln xsqlda* index))))
;;-----------------------------------------------------------------------------------
(defun alloc-vars-data (xsqlda*)
(loop for i from 0 to (%vars-count-1 xsqlda*) do
(when (nth-value 1 (get-var-type xsqlda* i))
(setf (%var-slot xsqlda* i 'sqlind)
(cffi:foreign-alloc :short)))
(alloc-var-data-default xsqlda* i)))
;;-----------------------------------------------------------------------------------
(defun free-vars-data (xsqlda*)
(loop for i from 0 to (%vars-count-1 xsqlda*) do
(when (nth-value 1 (get-var-type xsqlda* i))
(cffi-sys:foreign-free (%var-slot xsqlda* i 'sqlind)))
(cffi-sys:foreign-free (%var-slot xsqlda* i 'sqldata))))
;;-----------------------------------------------------------------------------------
(defun get-sql-type (stmt-handle-pointer)
(let ((status-vector* (make-status-vector))
(req* (cffi:foreign-alloc :char :initial-element 21))
(res* (cffi:foreign-alloc :char :count 8 :initial-element 0))
(st-type nil))
(isc-dsql-sql-info status-vector* stmt-handle-pointer 1 req* 8 res*)
(setf st-type (case (cffi:mem-aref res* :char 3)
(1 'select)
(2 'insert)
(3 'update)
(4 'delete)
(T nil)))
(cffi-sys:foreign-free req*) ; mem free.
(cffi-sys:foreign-free res*) ; mem free.
(cffi-sys:foreign-free status-vector*) ; mem free.
st-type))
;;-----------------------------------------------------------------------------------
(defun xsqlda-get-var-val (xsqlda* index)
(%var-slot xsqlda* index 'sqldata))
;;-----------------------------------------------------------------------------------
(defun xsqlda-get-var-sqlscale (xsqlda* index)
(%var-slot xsqlda* index 'sqlscale))
;;-----------------------------------------------------------------------------------
(defun is-var-nil (xsqlda* index)
(and (nth-value 1 (get-var-type xsqlda* index))
(= -1 (cffi:mem-aref (%var-slot xsqlda* index 'sqlind) :short))))
;;-----------------------------------------------------------------------------------
(defun get-var-name (xsqlda* index)
(cffi:foreign-string-to-lisp
(%var-slot xsqlda* index 'sqlname)
:count (%var-slot xsqlda* index 'sqlname_length)))
;;-----------------------------------------------------------------------------------
(defun get-vars-names (xsqlda*)
(loop for i from 0 to (- (get-vars-count xsqlda*) 1)
collect (get-var-name xsqlda* i)))
;;-----------------------------------------------------------------------------------
(defun get-vars-count (xsqlda*)
(cffi:foreign-slot-value xsqlda* '(:struct xsqlda) 'sqld))
;;-----------------------------------------------------------------------------------
(defun get-var-info (xsqlda* index)
(list :name (get-var-name xsqlda* index)
:type (get-var-type xsqlda* index)
:size (get-var-sqlln xsqlda* index)
:maybe-nil (nth-value 1 (get-var-type xsqlda* index))))
;;-----------------------------------------------------------------------------------
(defun get-vars-info (xsqlda*)
(loop for i from 0 to (%vars-count-1 xsqlda*)
collect (get-var-info xsqlda* i)))
;;-----------------------------------------------------------------------------------
;;===================================================================================
;; timestamp
;;-----------------------------------------------------------------------------------
(defparameter +mulp-vector+ #(1 1e-1 1e-2 1e-3 1e-4 1e-5 1e-6 1e-7 1e-8 1e-9 1e-10
1e-11 1e-12 1e-13 1e-14 1e-15 1e-16 1e-17 1e-18 1e-19 1e-20))
(defun pow-10 (n)
(elt +mulp-vector+ (- n)))
;;-----------------------------------------------------------------------------------
(defun fb-timestamp2datetime-list (fb-timestamp)
(let ((ttm (cffi:foreign-alloc '(:struct tm))))
(unwind-protect
(progn
(isc-decode-timestamp fb-timestamp ttm)
(with-foreign-slots ((sec min hour mday mon year) ttm (:struct tm))
(list :year (+ 1900 year) :mon (+ 1 mon) :mday mday :hour hour :min min :sec sec)))
(cffi-sys:foreign-free ttm)))) ; mem free.
;;-----------------------------------------------------------------------------------
(defun timestamp-alist-to-string (timestamp-alist)
(format nil
"~A.~A.~A ~A:~A:~A"
(getf timestamp-alist :mday)
(getf timestamp-alist :mon)
(getf timestamp-alist :year)
(getf timestamp-alist :hour)
(getf timestamp-alist :min)
(getf timestamp-alist :sec)))
;;-----------------------------------------------------------------------------------
(defparameter *timestamp-alist-converter* #'timestamp-alist-to-string)
;;-----------------------------------------------------------------------------------
(defun convert-timestamp-alist (timestamp-alist)
(if *timestamp-alist-converter*
(funcall *timestamp-alist-converter* timestamp-alist)
timestamp-alist))
;;===================================================================================
;; blob
;;-----------------------------------------------------------------------------------
(defun make-blob-handler ()
(cffi:foreign-alloc 'isc_blob_handle :initial-element 0))
;;-----------------------------------------------------------------------------------
(defclass fb-blob ()
((fb-tr :accessor fb-tr
:initarg :fb-tr)
(blob-id :accessor fb-blob-id
:initarg :id)
(blob-handle :accessor fb-blob-handle
:initform nil)))
;;-----------------------------------------------------------------------------------
(defun fb-blob-open (blob)
(setf (fb-blob-handle blob) (make-blob-handler))
(with-status-vector sv*
(isc-open-blob2 sv*
(db-handle* (fb-db (fb-tr blob)))
(transaction-handle* (fb-tr blob))
(fb-blob-handle blob)
(fb-blob-id blob)
0
(cffi-sys:null-pointer))
(process-status-vector sv* 51 "Unable to open blob."))) ;TODO: process status vector
;;-----------------------------------------------------------------------------------
(defun fb-blob-close (blob)
(with-status-vector sv*
(isc-close-blob sv* (fb-blob-handle blob))
(process-status-vector sv* 52 "Unable to close blob.")) ;TODO: process status vector
(cffi:foreign-free (fb-blob-handle blob)))
;;-----------------------------------------------------------------------------------
(defparameter *fb-blob-read-block-size* 1024)
;;-----------------------------------------------------------------------------------
(defun fb-blob-read (blob &key (buffer-size *fb-blob-read-block-size*)
(buffer (cffi:foreign-alloc :char :count buffer-size)))
(let* (;(buffer (cffi:foreign-alloc :char :count buffer-size))
(bytes-read (cffi:foreign-alloc :unsigned-short))
(answ (with-status-vector sv*
(isc-get-segment sv* (fb-blob-handle blob)
bytes-read buffer-size buffer))))
(unwind-protect (values buffer answ (mem-aref bytes-read :unsigned-short))
(foreign-free bytes-read))))
;;-----------------------------------------------------------------------------------
(defun fb-blob-load (blob)
(fb-blob-open blob)
(unwind-protect
(let ((data (cffi:foreign-alloc :char :count *fb-blob-read-block-size*))
(pos 0)
(temp-data Nil))
(loop do
(multiple-value-bind (buff answ bytes-read)
(fb-blob-read blob :buffer (inc-pointer data pos))
(declare (ignore buff))
(incf pos bytes-read)
(if (= answ 0)
(return (values data pos)) ;TODO: resize data??
(progn
(setf temp-data data)
(setf data (cffi:foreign-alloc
:char :count (+ pos *fb-blob-read-block-size*)))
(cffi:foreign-funcall "memcpy" :pointer data
:pointer temp-data :int pos)
(cffi:foreign-free temp-data))))))
(fb-blob-close blob)))
;;-----------------------------------------------------------------------------------
(defun fb-blob-to-string-convertor (blob)
(multiple-value-bind (data size) (fb-blob-load blob)
(unwind-protect
(foreign-string-to-lisp data :count size)
(foreign-free data))))
;;-----------------------------------------------------------------------------------
(defparameter *blob-convertor* #'fb-blob-to-string-convertor)
;;-----------------------------------------------------------------------------------
;TODO: ....etc
;;===================================================================================
;;===================================================================================
;; FB-STATEMENT
;;-----------------------------------------------------------------------------------
(defclass fb-statement ()
((fb-tr :accessor fb-tr
:initarg :fb-tr)
(request-str :accessor request-str
:initarg :request-str)
(statement-handle* :accessor statement-handle*
:initform (make-stmt-handler))
(xsqlda-output* :accessor xsqlda-output*
:initform nil)
(st-type :writer (setf st-type)
:reader fb-get-sql-type
:initform Nil))
(:documentation "Class that handles SQL statements."))
;;-----------------------------------------------------------------------------------
(defun fb-allocate-statement (fb-stmt)
"Method to allocate statement."
(with-status-vector status-vector*
(isc-dsql-allocate-statement status-vector*
(db-handle* (fb-db (fb-tr fb-stmt)))
(statement-handle* fb-stmt))
(process-status-vector status-vector* 30 "Unable to allocate statement")))
;;-----------------------------------------------------------------------------------
(defun fb-prepare-statement (fb-stmt)
"Method to prepare statement."
(with-status-vector status-vector*
(cffi:with-foreign-string (query-str* (request-str fb-stmt))
(isc-dsql-prepare status-vector*
(transaction-handle* (fb-tr fb-stmt))
(statement-handle* fb-stmt)
(length (request-str fb-stmt))
query-str*
0 ; 1 ??
(cffi:null-pointer)))
(process-status-vector status-vector*
31 (format nil "Unable to prepare statement: ~a"
(request-str fb-stmt))))
;; sql_info: query type
(setf (st-type fb-stmt) (get-sql-type (statement-handle* fb-stmt)))
;; SELECT - query
(when (eq (fb-get-sql-type fb-stmt) 'select)
(setf (xsqlda-output* fb-stmt) (make-xsqlda 10))
(with-status-vector status-vector*
(isc-dsql-describe status-vector*
(statement-handle* fb-stmt)
1
(xsqlda-output* fb-stmt))
(process-status-vector status-vector*
32 "Error in isc-dsql-describe"))
(when (need-remake-xsqlda (xsqlda-output* fb-stmt))
(setf (xsqlda-output* fb-stmt) (remake-xsqlda (xsqlda-output* fb-stmt)))
(with-status-vector status-vector*
(isc-dsql-describe status-vector*
(statement-handle* fb-stmt)
1
(xsqlda-output* fb-stmt))
(process-status-vector status-vector*
32 "Error in isc-dsql-describe")))
(alloc-vars-data (xsqlda-output* fb-stmt))))
;;-----------------------------------------------------------------------------------
(defun fb-execute-statement (fb-stmt)
"Method to execute statement."
(with-status-vector status-vector*
(if (eq (fb-get-sql-type fb-stmt) 'select)
(isc-dsql-execute status-vector*
(transaction-handle* (fb-tr fb-stmt))
(statement-handle* fb-stmt)
1
(cffi-sys:null-pointer))
(isc-dsql-execute2 status-vector*
(transaction-handle* (fb-tr fb-stmt))
(statement-handle* fb-stmt)
1
(cffi-sys:null-pointer)
(cffi-sys:null-pointer)))
(process-status-vector status-vector* 33 "Unable to execute statement")))
;-----------------------------------------------------------------------------------
(defmethod initialize-instance :after ((stmt fb-statement)
&key (no-auto-execute Nil)
(no-auto-prepare Nil) (no-auto-allocate Nil))
(unless no-auto-allocate
(fb-allocate-statement stmt)
(unless no-auto-prepare
(fb-prepare-statement stmt)
(unless no-auto-execute
(fb-execute-statement stmt)))))
;;-----------------------------------------------------------------------------------
(defun fb-statement-free (stmt)
"Method to free statement."
(when (xsqlda-output* stmt)
(free-vars-data (xsqlda-output* stmt)) ; mem free.
(cffi-sys:foreign-free (xsqlda-output* stmt))) ; mem free.
(with-status-vector status-vector*
(isc-dsql-free-statement status-vector* (statement-handle* stmt) 2) ;DSQL_drop (no DSQL_close!!!)
(process-status-vector status-vector* 35 "Unable to free statement"))
(cffi-sys:foreign-free (statement-handle* stmt)))
;;-----------------------------------------------------------------------------------
;;===================================================================================
;; fetching data
;;-----------------------------------------------------------------------------------
(defun fb-statement-fetch (stmt)
"Method to fetch results from executed statement."
(if (eq (fb-get-sql-type stmt) 'select)
(with-status-vector status-vector*
(let ((fetch-res (isc-dsql-fetch status-vector* (statement-handle* stmt)
1 (xsqlda-output* stmt))))
(process-status-vector status-vector* 36 "Unable to fetch statement")
(when (= fetch-res 0) T)))
(error 'fb-error
:fb-error-code 36
:fb-error-text "Unable to fetch statement. Statement type is not SELECT."
:fbclient-msg "")))
;;-----------------------------------------------------------------------------------
;; auxiliary functions
;;-----------------------------------------------------------------------------------
(defun get-var-val-by-type (stmt index type)
(let ((xsqlda* (xsqlda-output* stmt)))
(cond ;case type
((eq type ':text)
(cffi:foreign-string-to-lisp (xsqlda-get-var-val xsqlda* index)))
((eq type ':varying)
(cffi:foreign-string-to-lisp (inc-pointer (xsqlda-get-var-val xsqlda* index) 2)
:count (mem-aref (xsqlda-get-var-val xsqlda* index)
:short)))
((eq type ':timestamp)
(convert-timestamp-alist
(fb-timestamp2datetime-list (mem-aptr (xsqlda-get-var-val xsqlda* index)
'(:struct isc_timestamp)))))
((eq type ':decimal)
(* (cffi:mem-aref (xsqlda-get-var-val xsqlda* index) :long)
(pow-10 (xsqlda-get-var-sqlscale xsqlda* index))))
((eq type ':blob)
(let ((blob (make-instance 'fb-blob
:fb-tr (fb-tr stmt)
:id (let ((id (foreign-alloc '(:struct ISC_QUAD))))
(setf (mem-aref id '(:struct ISC_QUAD))
(mem-aref (xsqlda-get-var-val xsqlda* index)
'(:struct ISC_QUAD)))
id)))) ; TODO: Test it!
(if *blob-convertor*
(funcall *blob-convertor* blob)
blob)))
(T (cffi:mem-aref (xsqlda-get-var-val xsqlda* index) type)))))
;;-----------------------------------------------------------------------------------
(defun get-var-val (stmt index)
(let ((xsqlda* (xsqlda-output* stmt)))
(unless (is-var-nil xsqlda* index)
(get-var-val-by-type stmt index (nth-value 0 (get-var-type xsqlda* index))))))
;;-----------------------------------------------------------------------------------
(defun get-var-val+name (stmt index)
(list (intern (get-var-name (xsqlda-output* stmt) index) "KEYWORD")
(get-var-val stmt index)))
;;-----------------------------------------------------------------------------------
(defun get-vars-vals-list (stmt)
(let ((xsqlda* (xsqlda-output* stmt)))
? ? count - 1
;;-----------------------------------------------------------------------------------
(defun get-vars-vals+names-list (stmt &optional (names Nil))
(let* ((xsqlda* (xsqlda-output* stmt))
? ? count - 1
(if names
(loop for i from 0 to max-index
append (if (nth i names)
(list (nth i names) (get-var-val stmt i))
(get-var-val+name stmt i)))
(loop for i from 0 to max-index
append (get-var-val+name stmt i)))))
;;-----------------------------------------------------------------------------------
Interface functions
;;-----------------------------------------------------------------------------------
(defun fb-statement-get-var-val (stmt index)
"A method for obtaining the values of result variables. Used after Fetch."
(let ((cffi:*default-foreign-encoding* (encoding (fb-db (fb-tr stmt)))))
(get-var-val stmt index)))
;;-----------------------------------------------------------------------------------
(defun fb-statement-get-vars-vals-list (stmt)
"A method for obtaining the list of values of result variables. Used after Fetch."
(let ((cffi:*default-foreign-encoding* (encoding (fb-db (fb-tr stmt)))))
(get-vars-vals-list stmt)))
;;-----------------------------------------------------------------------------------
(defun fb-statement-get-var-val+name (stmt index)
"A method for obtaining the values and names of result variables. Used after Fetch."
(let ((cffi:*default-foreign-encoding* (encoding (fb-db (fb-tr stmt)))))
(get-var-val+name stmt index)))
;;-----------------------------------------------------------------------------------
(defun fb-statement-get-vars-vals+names-list (stmt &optional (names Nil))
"A method for obtaining the list of values and names of result variables. Used after Fetch."
(let ((cffi:*default-foreign-encoding* (encoding (fb-db (fb-tr stmt)))))
(get-vars-vals+names-list stmt names)))
;;-----------------------------------------------------------------------------------
(defun fb-statement-get-vars-names-list (stmt)
"A method for obtaining names of result variables. Used after Fetch."
(let ((cffi:*default-foreign-encoding* (encoding (fb-db (fb-tr stmt)))))
(get-vars-names stmt)))
;;-----------------------------------------------------------------------------------
(defun fb-statement-get-var-info (stmt index)
(get-var-info (xsqlda-output* stmt) index))
;;-----------------------------------------------------------------------------------
(defun fb-statement-get-vars-info (stmt)
(get-vars-info (xsqlda-output* stmt)))
;;-----------------------------------------------------------------------------------
;;===================================================================================
| null | https://raw.githubusercontent.com/klimenko-serj/cl-fbclient/7a87ea9764f7099c00e5e1c7b85b39a51f80b0a3/cl-fbclient-statement.lisp | lisp |
STATEMENT
===================================================================================
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
:initial-element 0))) speed optimization?
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
...
TODO: other types
===================================================================================
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
===================================================================================
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
mem free.
mem free.
mem free.
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
===================================================================================
timestamp
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
mem free.
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
===================================================================================
blob
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
TODO: process status vector
-----------------------------------------------------------------------------------
TODO: process status vector
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
(buffer (cffi:foreign-alloc :char :count buffer-size))
-----------------------------------------------------------------------------------
TODO: resize data??
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
TODO: ....etc
===================================================================================
===================================================================================
FB-STATEMENT
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
1 ??
sql_info: query type
SELECT - query
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
mem free.
mem free.
DSQL_drop (no DSQL_close!!!)
-----------------------------------------------------------------------------------
===================================================================================
fetching data
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
auxiliary functions
-----------------------------------------------------------------------------------
case type
TODO: Test it!
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
=================================================================================== | cl-fbclient-statement.lisp
(in-package #:cl-fbclient)
(defun make-stmt-handler ()
(cffi:foreign-alloc 'isc_stmt_handle :initial-element 0))
(defun XSQLDA-length (n)
(+ (cffi:foreign-type-size '(:struct XSQLDA))
(* (- n 1) (cffi:foreign-type-size '(:struct XSQLVAR)))))
(defun make-xsqlda (n)
(let ((new-xsqlda (cffi:foreign-alloc :char :count (XSQLDA-length n))))
(setf (cffi:foreign-slot-value new-xsqlda '(:struct xsqlda) 'version) 1
(cffi:foreign-slot-value new-xsqlda '(:struct xsqlda) 'sqln) n)
new-xsqlda))
(defun need-remake-xsqlda (tmp-xsqlda)
(> (cffi:foreign-slot-value tmp-xsqlda '(:struct xsqlda) 'sqld)
(cffi:foreign-slot-value tmp-xsqlda '(:struct xsqlda) 'sqln)))
(defun remake-xsqlda (tmp-xsqlda)
(unwind-protect
(make-xsqlda (cffi:foreign-slot-value tmp-xsqlda '(:struct xsqlda) 'sqld))
(cffi-sys:foreign-free tmp-xsqlda)))
(defun get-var-type-by-fbtype-num (type-num)
(case type-num
(496 ':int)
(500 ':short)
(482 ':float)
(480 ':double)
(452 ':text)
(448 ':varying)
(510 ':timestamp)
(580 ':decimal)
(520 ':blob)
(T (error (format t "Unknown type #~A!~%" type-num)))))
%
(defmacro %var (%xsqlda %index)
`(cffi:mem-aptr
(cffi:foreign-slot-pointer ,%xsqlda '(:struct xsqlda) 'sqlvar)
'(:struct xsqlvar) ,%index))
(defmacro %var-slot (%xsqlda %index %slot-name)
`(cffi:foreign-slot-value
(%var ,%xsqlda ,%index)
'(:struct xsqlvar) ,%slot-name))
(defmacro %vars-count-1 (%xsqlda)
`(- (cffi:foreign-slot-value ,%xsqlda '(:struct xsqlda) 'sqld) 1))
(defun get-var-type (xsqlda* index)
(let ((tp (%var-slot xsqlda* index 'sqltype))
(can-nil T))
(if (oddp tp)
(decf tp)
(setf can-nil nil))
(values-list (list (get-var-type-by-fbtype-num tp) can-nil))))
(defun get-var-sqlln (xsqlda* index)
(cffi:foreign-slot-value
(%var xsqlda* index)
'(:struct xsqlvar) 'sqllen))
(defun alloc-var-data-default (xsqlda* index)
(setf (%var-slot xsqlda* index 'sqldata)
(cffi:foreign-alloc :char
:initial-element 0
:count (get-var-sqlln xsqlda* index))))
(defun alloc-vars-data (xsqlda*)
(loop for i from 0 to (%vars-count-1 xsqlda*) do
(when (nth-value 1 (get-var-type xsqlda* i))
(setf (%var-slot xsqlda* i 'sqlind)
(cffi:foreign-alloc :short)))
(alloc-var-data-default xsqlda* i)))
(defun free-vars-data (xsqlda*)
(loop for i from 0 to (%vars-count-1 xsqlda*) do
(when (nth-value 1 (get-var-type xsqlda* i))
(cffi-sys:foreign-free (%var-slot xsqlda* i 'sqlind)))
(cffi-sys:foreign-free (%var-slot xsqlda* i 'sqldata))))
(defun get-sql-type (stmt-handle-pointer)
(let ((status-vector* (make-status-vector))
(req* (cffi:foreign-alloc :char :initial-element 21))
(res* (cffi:foreign-alloc :char :count 8 :initial-element 0))
(st-type nil))
(isc-dsql-sql-info status-vector* stmt-handle-pointer 1 req* 8 res*)
(setf st-type (case (cffi:mem-aref res* :char 3)
(1 'select)
(2 'insert)
(3 'update)
(4 'delete)
(T nil)))
st-type))
(defun xsqlda-get-var-val (xsqlda* index)
(%var-slot xsqlda* index 'sqldata))
(defun xsqlda-get-var-sqlscale (xsqlda* index)
(%var-slot xsqlda* index 'sqlscale))
(defun is-var-nil (xsqlda* index)
(and (nth-value 1 (get-var-type xsqlda* index))
(= -1 (cffi:mem-aref (%var-slot xsqlda* index 'sqlind) :short))))
(defun get-var-name (xsqlda* index)
(cffi:foreign-string-to-lisp
(%var-slot xsqlda* index 'sqlname)
:count (%var-slot xsqlda* index 'sqlname_length)))
(defun get-vars-names (xsqlda*)
(loop for i from 0 to (- (get-vars-count xsqlda*) 1)
collect (get-var-name xsqlda* i)))
(defun get-vars-count (xsqlda*)
(cffi:foreign-slot-value xsqlda* '(:struct xsqlda) 'sqld))
(defun get-var-info (xsqlda* index)
(list :name (get-var-name xsqlda* index)
:type (get-var-type xsqlda* index)
:size (get-var-sqlln xsqlda* index)
:maybe-nil (nth-value 1 (get-var-type xsqlda* index))))
(defun get-vars-info (xsqlda*)
(loop for i from 0 to (%vars-count-1 xsqlda*)
collect (get-var-info xsqlda* i)))
(defparameter +mulp-vector+ #(1 1e-1 1e-2 1e-3 1e-4 1e-5 1e-6 1e-7 1e-8 1e-9 1e-10
1e-11 1e-12 1e-13 1e-14 1e-15 1e-16 1e-17 1e-18 1e-19 1e-20))
(defun pow-10 (n)
(elt +mulp-vector+ (- n)))
(defun fb-timestamp2datetime-list (fb-timestamp)
(let ((ttm (cffi:foreign-alloc '(:struct tm))))
(unwind-protect
(progn
(isc-decode-timestamp fb-timestamp ttm)
(with-foreign-slots ((sec min hour mday mon year) ttm (:struct tm))
(list :year (+ 1900 year) :mon (+ 1 mon) :mday mday :hour hour :min min :sec sec)))
(defun timestamp-alist-to-string (timestamp-alist)
(format nil
"~A.~A.~A ~A:~A:~A"
(getf timestamp-alist :mday)
(getf timestamp-alist :mon)
(getf timestamp-alist :year)
(getf timestamp-alist :hour)
(getf timestamp-alist :min)
(getf timestamp-alist :sec)))
(defparameter *timestamp-alist-converter* #'timestamp-alist-to-string)
(defun convert-timestamp-alist (timestamp-alist)
(if *timestamp-alist-converter*
(funcall *timestamp-alist-converter* timestamp-alist)
timestamp-alist))
(defun make-blob-handler ()
(cffi:foreign-alloc 'isc_blob_handle :initial-element 0))
(defclass fb-blob ()
((fb-tr :accessor fb-tr
:initarg :fb-tr)
(blob-id :accessor fb-blob-id
:initarg :id)
(blob-handle :accessor fb-blob-handle
:initform nil)))
(defun fb-blob-open (blob)
(setf (fb-blob-handle blob) (make-blob-handler))
(with-status-vector sv*
(isc-open-blob2 sv*
(db-handle* (fb-db (fb-tr blob)))
(transaction-handle* (fb-tr blob))
(fb-blob-handle blob)
(fb-blob-id blob)
0
(cffi-sys:null-pointer))
(defun fb-blob-close (blob)
(with-status-vector sv*
(isc-close-blob sv* (fb-blob-handle blob))
(cffi:foreign-free (fb-blob-handle blob)))
(defparameter *fb-blob-read-block-size* 1024)
(defun fb-blob-read (blob &key (buffer-size *fb-blob-read-block-size*)
(buffer (cffi:foreign-alloc :char :count buffer-size)))
(bytes-read (cffi:foreign-alloc :unsigned-short))
(answ (with-status-vector sv*
(isc-get-segment sv* (fb-blob-handle blob)
bytes-read buffer-size buffer))))
(unwind-protect (values buffer answ (mem-aref bytes-read :unsigned-short))
(foreign-free bytes-read))))
(defun fb-blob-load (blob)
(fb-blob-open blob)
(unwind-protect
(let ((data (cffi:foreign-alloc :char :count *fb-blob-read-block-size*))
(pos 0)
(temp-data Nil))
(loop do
(multiple-value-bind (buff answ bytes-read)
(fb-blob-read blob :buffer (inc-pointer data pos))
(declare (ignore buff))
(incf pos bytes-read)
(if (= answ 0)
(progn
(setf temp-data data)
(setf data (cffi:foreign-alloc
:char :count (+ pos *fb-blob-read-block-size*)))
(cffi:foreign-funcall "memcpy" :pointer data
:pointer temp-data :int pos)
(cffi:foreign-free temp-data))))))
(fb-blob-close blob)))
(defun fb-blob-to-string-convertor (blob)
(multiple-value-bind (data size) (fb-blob-load blob)
(unwind-protect
(foreign-string-to-lisp data :count size)
(foreign-free data))))
(defparameter *blob-convertor* #'fb-blob-to-string-convertor)
(defclass fb-statement ()
((fb-tr :accessor fb-tr
:initarg :fb-tr)
(request-str :accessor request-str
:initarg :request-str)
(statement-handle* :accessor statement-handle*
:initform (make-stmt-handler))
(xsqlda-output* :accessor xsqlda-output*
:initform nil)
(st-type :writer (setf st-type)
:reader fb-get-sql-type
:initform Nil))
(:documentation "Class that handles SQL statements."))
(defun fb-allocate-statement (fb-stmt)
"Method to allocate statement."
(with-status-vector status-vector*
(isc-dsql-allocate-statement status-vector*
(db-handle* (fb-db (fb-tr fb-stmt)))
(statement-handle* fb-stmt))
(process-status-vector status-vector* 30 "Unable to allocate statement")))
(defun fb-prepare-statement (fb-stmt)
"Method to prepare statement."
(with-status-vector status-vector*
(cffi:with-foreign-string (query-str* (request-str fb-stmt))
(isc-dsql-prepare status-vector*
(transaction-handle* (fb-tr fb-stmt))
(statement-handle* fb-stmt)
(length (request-str fb-stmt))
query-str*
(cffi:null-pointer)))
(process-status-vector status-vector*
31 (format nil "Unable to prepare statement: ~a"
(request-str fb-stmt))))
(setf (st-type fb-stmt) (get-sql-type (statement-handle* fb-stmt)))
(when (eq (fb-get-sql-type fb-stmt) 'select)
(setf (xsqlda-output* fb-stmt) (make-xsqlda 10))
(with-status-vector status-vector*
(isc-dsql-describe status-vector*
(statement-handle* fb-stmt)
1
(xsqlda-output* fb-stmt))
(process-status-vector status-vector*
32 "Error in isc-dsql-describe"))
(when (need-remake-xsqlda (xsqlda-output* fb-stmt))
(setf (xsqlda-output* fb-stmt) (remake-xsqlda (xsqlda-output* fb-stmt)))
(with-status-vector status-vector*
(isc-dsql-describe status-vector*
(statement-handle* fb-stmt)
1
(xsqlda-output* fb-stmt))
(process-status-vector status-vector*
32 "Error in isc-dsql-describe")))
(alloc-vars-data (xsqlda-output* fb-stmt))))
(defun fb-execute-statement (fb-stmt)
"Method to execute statement."
(with-status-vector status-vector*
(if (eq (fb-get-sql-type fb-stmt) 'select)
(isc-dsql-execute status-vector*
(transaction-handle* (fb-tr fb-stmt))
(statement-handle* fb-stmt)
1
(cffi-sys:null-pointer))
(isc-dsql-execute2 status-vector*
(transaction-handle* (fb-tr fb-stmt))
(statement-handle* fb-stmt)
1
(cffi-sys:null-pointer)
(cffi-sys:null-pointer)))
(process-status-vector status-vector* 33 "Unable to execute statement")))
(defmethod initialize-instance :after ((stmt fb-statement)
&key (no-auto-execute Nil)
(no-auto-prepare Nil) (no-auto-allocate Nil))
(unless no-auto-allocate
(fb-allocate-statement stmt)
(unless no-auto-prepare
(fb-prepare-statement stmt)
(unless no-auto-execute
(fb-execute-statement stmt)))))
(defun fb-statement-free (stmt)
"Method to free statement."
(when (xsqlda-output* stmt)
(with-status-vector status-vector*
(process-status-vector status-vector* 35 "Unable to free statement"))
(cffi-sys:foreign-free (statement-handle* stmt)))
(defun fb-statement-fetch (stmt)
"Method to fetch results from executed statement."
(if (eq (fb-get-sql-type stmt) 'select)
(with-status-vector status-vector*
(let ((fetch-res (isc-dsql-fetch status-vector* (statement-handle* stmt)
1 (xsqlda-output* stmt))))
(process-status-vector status-vector* 36 "Unable to fetch statement")
(when (= fetch-res 0) T)))
(error 'fb-error
:fb-error-code 36
:fb-error-text "Unable to fetch statement. Statement type is not SELECT."
:fbclient-msg "")))
(defun get-var-val-by-type (stmt index type)
(let ((xsqlda* (xsqlda-output* stmt)))
((eq type ':text)
(cffi:foreign-string-to-lisp (xsqlda-get-var-val xsqlda* index)))
((eq type ':varying)
(cffi:foreign-string-to-lisp (inc-pointer (xsqlda-get-var-val xsqlda* index) 2)
:count (mem-aref (xsqlda-get-var-val xsqlda* index)
:short)))
((eq type ':timestamp)
(convert-timestamp-alist
(fb-timestamp2datetime-list (mem-aptr (xsqlda-get-var-val xsqlda* index)
'(:struct isc_timestamp)))))
((eq type ':decimal)
(* (cffi:mem-aref (xsqlda-get-var-val xsqlda* index) :long)
(pow-10 (xsqlda-get-var-sqlscale xsqlda* index))))
((eq type ':blob)
(let ((blob (make-instance 'fb-blob
:fb-tr (fb-tr stmt)
:id (let ((id (foreign-alloc '(:struct ISC_QUAD))))
(setf (mem-aref id '(:struct ISC_QUAD))
(mem-aref (xsqlda-get-var-val xsqlda* index)
'(:struct ISC_QUAD)))
(if *blob-convertor*
(funcall *blob-convertor* blob)
blob)))
(T (cffi:mem-aref (xsqlda-get-var-val xsqlda* index) type)))))
(defun get-var-val (stmt index)
(let ((xsqlda* (xsqlda-output* stmt)))
(unless (is-var-nil xsqlda* index)
(get-var-val-by-type stmt index (nth-value 0 (get-var-type xsqlda* index))))))
(defun get-var-val+name (stmt index)
(list (intern (get-var-name (xsqlda-output* stmt) index) "KEYWORD")
(get-var-val stmt index)))
(defun get-vars-vals-list (stmt)
(let ((xsqlda* (xsqlda-output* stmt)))
? ? count - 1
(defun get-vars-vals+names-list (stmt &optional (names Nil))
(let* ((xsqlda* (xsqlda-output* stmt))
? ? count - 1
(if names
(loop for i from 0 to max-index
append (if (nth i names)
(list (nth i names) (get-var-val stmt i))
(get-var-val+name stmt i)))
(loop for i from 0 to max-index
append (get-var-val+name stmt i)))))
Interface functions
(defun fb-statement-get-var-val (stmt index)
"A method for obtaining the values of result variables. Used after Fetch."
(let ((cffi:*default-foreign-encoding* (encoding (fb-db (fb-tr stmt)))))
(get-var-val stmt index)))
(defun fb-statement-get-vars-vals-list (stmt)
"A method for obtaining the list of values of result variables. Used after Fetch."
(let ((cffi:*default-foreign-encoding* (encoding (fb-db (fb-tr stmt)))))
(get-vars-vals-list stmt)))
(defun fb-statement-get-var-val+name (stmt index)
"A method for obtaining the values and names of result variables. Used after Fetch."
(let ((cffi:*default-foreign-encoding* (encoding (fb-db (fb-tr stmt)))))
(get-var-val+name stmt index)))
(defun fb-statement-get-vars-vals+names-list (stmt &optional (names Nil))
"A method for obtaining the list of values and names of result variables. Used after Fetch."
(let ((cffi:*default-foreign-encoding* (encoding (fb-db (fb-tr stmt)))))
(get-vars-vals+names-list stmt names)))
(defun fb-statement-get-vars-names-list (stmt)
"A method for obtaining names of result variables. Used after Fetch."
(let ((cffi:*default-foreign-encoding* (encoding (fb-db (fb-tr stmt)))))
(get-vars-names stmt)))
(defun fb-statement-get-var-info (stmt index)
(get-var-info (xsqlda-output* stmt) index))
(defun fb-statement-get-vars-info (stmt)
(get-vars-info (xsqlda-output* stmt)))
|
2fab4ca958461d2ff950aed0fc927bbb237520ee80da686f8b302a676243d71a | eponai/sulolive | main.cljs | (ns ^:figwheel-no-load env.android.main
(:require [om.next :as om]
[sulo-native.android.core :as core]
[sulo-native.state :as state]
[figwheel.client :as figwheel :include-macros true]))
(enable-console-print!)
(figwheel/watch-and-reload
:websocket-url "ws:3449/figwheel-ws"
:heads-up-display false
:jsload-callback #(om/add-root! state/reconciler core/AppRoot 1))
(core/init)
Do not delete , root - el is used by the figwheel-bridge.js
(def root-el (core/app-root)) | null | https://raw.githubusercontent.com/eponai/sulolive/7a70701bbd3df6bbb92682679dcedb53f8822c18/sulo-native/env/dev/env/android/main.cljs | clojure | (ns ^:figwheel-no-load env.android.main
(:require [om.next :as om]
[sulo-native.android.core :as core]
[sulo-native.state :as state]
[figwheel.client :as figwheel :include-macros true]))
(enable-console-print!)
(figwheel/watch-and-reload
:websocket-url "ws:3449/figwheel-ws"
:heads-up-display false
:jsload-callback #(om/add-root! state/reconciler core/AppRoot 1))
(core/init)
Do not delete , root - el is used by the figwheel-bridge.js
(def root-el (core/app-root)) | |
12e7067bc4c6810c25a31ce8c05f18a718b1a57253bbf317349556c90dbc844a | david-christiansen/brush | main.rkt | #lang racket/base
(require "private/lp.rkt")
(provide program PROGRAM)
(module reader syntax/module-reader
brush/lp/lang/lang2
#:read read-inside
#:read-syntax read-syntax-inside
#:whole-body-readers? #t
#:language-info (scribble-base-language-info)
#:info (scribble-base-info)
(require scribble/reader
(only-in scribble/base/reader
scribble-base-info
scribble-base-language-info)))
| null | https://raw.githubusercontent.com/david-christiansen/brush/91b83cda313f77f2068f0c02753c55c2563680d5/main.rkt | racket | #lang racket/base
(require "private/lp.rkt")
(provide program PROGRAM)
(module reader syntax/module-reader
brush/lp/lang/lang2
#:read read-inside
#:read-syntax read-syntax-inside
#:whole-body-readers? #t
#:language-info (scribble-base-language-info)
#:info (scribble-base-info)
(require scribble/reader
(only-in scribble/base/reader
scribble-base-info
scribble-base-language-info)))
| |
2a14fbd2f095cda3f5b49336c327e8e1d7534388e13d3b0492693e9d1562985a | ocaml-batteries-team/batteries-included | batBase64.ml |
* Base64 - Base64 codec
* Copyright ( C ) 2003
*
* This library is free software ; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation ; either
* version 2.1 of the License , or ( at your option ) any later version ,
* with the special exception on linking described in file LICENSE .
*
* This library is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
* Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
* Base64 - Base64 codec
* Copyright (C) 2003 Nicolas Cannasse
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version,
* with the special exception on linking described in file LICENSE.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
exception Invalid_char
exception Invalid_table
UNUSED exception Invalid_padding
external unsafe_char_of_int : int -> char = "%identity"
type encoding_table = char array
type decoding_table = int array
let chars = [|
'A';'B';'C';'D';'E';'F';'G';'H';'I';'J';'K';'L';'M';'N';'O';'P';
'Q';'R';'S';'T';'U';'V';'W';'X';'Y';'Z';'a';'b';'c';'d';'e';'f';
'g';'h';'i';'j';'k';'l';'m';'n';'o';'p';'q';'r';'s';'t';'u';'v';
'w';'x';'y';'z';'0';'1';'2';'3';'4';'5';'6';'7';'8';'9';'+';'/'
|]
let make_decoding_table tbl =
if Array.length tbl <> 64 then raise Invalid_table;
let d = Array.make 256 (-1) in
for i = 0 to 63 do
Array.unsafe_set d (int_of_char (Array.unsafe_get tbl i)) i;
done;
d
let inv_chars = make_decoding_table chars
let encode ?(tbl=chars) ch =
if Array.length tbl <> 64 then raise Invalid_table;
let data = ref 0 in
let count = ref 0 in
let flush() =
if !count > 0 then begin
let d = (!data lsl (6 - !count)) land 63 in
BatIO.write ch (Array.unsafe_get tbl d);
end;
count := 0;
in
let write c =
let c = int_of_char c in
data := (!data lsl 8) lor c;
count := !count + 8;
while !count >= 6 do
count := !count - 6;
let d = (!data asr !count) land 63 in
BatIO.write ch (Array.unsafe_get tbl d)
done;
in
let output s p l =
for i = p to p + l - 1 do
write (Bytes.unsafe_get s i)
done;
l
in
BatIO.create_out ~write ~output
~flush:(fun () -> flush(); BatIO.flush ch)
~close:(fun() -> flush(); BatIO.close_out ch)
let decode ?(tbl=inv_chars) ch =
if Array.length tbl <> 256 then raise Invalid_table;
let data = ref 0 in
let count = ref 0 in
let rec fetch() =
if !count >= 8 then begin
count := !count - 8;
let d = (!data asr !count) land 0xFF in
unsafe_char_of_int d
end else
let c = int_of_char (BatIO.read ch) in
let c = Array.unsafe_get tbl c in
if c = -1 then raise Invalid_char;
data := (!data lsl 6) lor c;
count := !count + 6;
fetch()
in
let read = fetch in
let input s p l =
let i = ref 0 in
try
while !i < l do
Bytes.unsafe_set s (p + !i) (fetch());
incr i;
done;
l
with
BatIO.No_more_input when !i > 0 ->
!i
in
let close() =
count := 0;
BatIO.close_in ch
in
BatIO.create_in ~read ~input ~close
let str_encode ?(tbl=chars) s =
let ch = encode ~tbl (BatIO.output_string()) in
BatIO.nwrite ch s;
BatIO.close_out ch
let str_decode ?(tbl=inv_chars) s =
let ch = decode ~tbl (BatIO.input_string s) in
BatIO.nread ch ((String.length s * 6) / 8)
$ Q str_decode ; str_encode
( Q.string ) ( fun s - > s = str_decode ( str_encode s ) )
( Q.string ) ( fun s - > let e = str_encode s in e = str_encode ( str_decode e ) )
(Q.string) (fun s -> s = str_decode (str_encode s))
(Q.string) (fun s -> let e = str_encode s in e = str_encode (str_decode e))
*)
$ T make_decoding_table
try ignore ( make_decoding_table [ |'1'| ] ) ; false \
with Invalid_table - > true
try ignore ( make_decoding_table ( Array.make 2000 ' 1 ' ) ) ; false \
with Invalid_table - > true
try ignore (make_decoding_table [|'1'|]); false \
with Invalid_table -> true
try ignore (make_decoding_table (Array.make 2000 '1')); false \
with Invalid_table -> true
*)
(*$T str_encode
try ignore (str_encode ~tbl:[|'1'|] "mlk"); false \
with Invalid_table -> true
try ignore (str_encode ~tbl:(Array.make 2000 '1') "mlk"); false \
with Invalid_table -> true
*)
$ T str_decode
try ignore ( str_decode ~tbl:[|1| ] " mlk " ) ; false \
with Invalid_table - > true
try ignore ( str_decode ~tbl:(Array.make 2000 1 ) " mlk " ) ; false \
with Invalid_table - > true
try ignore (str_decode ~tbl:[|1|] "mlk"); false \
with Invalid_table -> true
try ignore (str_decode ~tbl:(Array.make 2000 1) "mlk"); false \
with Invalid_table -> true
*)
| null | https://raw.githubusercontent.com/ocaml-batteries-team/batteries-included/f143ef5ec583d87d538b8f06f06d046d64555e90/src/batBase64.ml | ocaml | $T str_encode
try ignore (str_encode ~tbl:[|'1'|] "mlk"); false \
with Invalid_table -> true
try ignore (str_encode ~tbl:(Array.make 2000 '1') "mlk"); false \
with Invalid_table -> true
|
* Base64 - Base64 codec
* Copyright ( C ) 2003
*
* This library is free software ; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation ; either
* version 2.1 of the License , or ( at your option ) any later version ,
* with the special exception on linking described in file LICENSE .
*
* This library is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
* Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
* Base64 - Base64 codec
* Copyright (C) 2003 Nicolas Cannasse
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version,
* with the special exception on linking described in file LICENSE.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
exception Invalid_char
exception Invalid_table
UNUSED exception Invalid_padding
external unsafe_char_of_int : int -> char = "%identity"
type encoding_table = char array
type decoding_table = int array
let chars = [|
'A';'B';'C';'D';'E';'F';'G';'H';'I';'J';'K';'L';'M';'N';'O';'P';
'Q';'R';'S';'T';'U';'V';'W';'X';'Y';'Z';'a';'b';'c';'d';'e';'f';
'g';'h';'i';'j';'k';'l';'m';'n';'o';'p';'q';'r';'s';'t';'u';'v';
'w';'x';'y';'z';'0';'1';'2';'3';'4';'5';'6';'7';'8';'9';'+';'/'
|]
let make_decoding_table tbl =
if Array.length tbl <> 64 then raise Invalid_table;
let d = Array.make 256 (-1) in
for i = 0 to 63 do
Array.unsafe_set d (int_of_char (Array.unsafe_get tbl i)) i;
done;
d
let inv_chars = make_decoding_table chars
let encode ?(tbl=chars) ch =
if Array.length tbl <> 64 then raise Invalid_table;
let data = ref 0 in
let count = ref 0 in
let flush() =
if !count > 0 then begin
let d = (!data lsl (6 - !count)) land 63 in
BatIO.write ch (Array.unsafe_get tbl d);
end;
count := 0;
in
let write c =
let c = int_of_char c in
data := (!data lsl 8) lor c;
count := !count + 8;
while !count >= 6 do
count := !count - 6;
let d = (!data asr !count) land 63 in
BatIO.write ch (Array.unsafe_get tbl d)
done;
in
let output s p l =
for i = p to p + l - 1 do
write (Bytes.unsafe_get s i)
done;
l
in
BatIO.create_out ~write ~output
~flush:(fun () -> flush(); BatIO.flush ch)
~close:(fun() -> flush(); BatIO.close_out ch)
let decode ?(tbl=inv_chars) ch =
if Array.length tbl <> 256 then raise Invalid_table;
let data = ref 0 in
let count = ref 0 in
let rec fetch() =
if !count >= 8 then begin
count := !count - 8;
let d = (!data asr !count) land 0xFF in
unsafe_char_of_int d
end else
let c = int_of_char (BatIO.read ch) in
let c = Array.unsafe_get tbl c in
if c = -1 then raise Invalid_char;
data := (!data lsl 6) lor c;
count := !count + 6;
fetch()
in
let read = fetch in
let input s p l =
let i = ref 0 in
try
while !i < l do
Bytes.unsafe_set s (p + !i) (fetch());
incr i;
done;
l
with
BatIO.No_more_input when !i > 0 ->
!i
in
let close() =
count := 0;
BatIO.close_in ch
in
BatIO.create_in ~read ~input ~close
let str_encode ?(tbl=chars) s =
let ch = encode ~tbl (BatIO.output_string()) in
BatIO.nwrite ch s;
BatIO.close_out ch
let str_decode ?(tbl=inv_chars) s =
let ch = decode ~tbl (BatIO.input_string s) in
BatIO.nread ch ((String.length s * 6) / 8)
$ Q str_decode ; str_encode
( Q.string ) ( fun s - > s = str_decode ( str_encode s ) )
( Q.string ) ( fun s - > let e = str_encode s in e = str_encode ( str_decode e ) )
(Q.string) (fun s -> s = str_decode (str_encode s))
(Q.string) (fun s -> let e = str_encode s in e = str_encode (str_decode e))
*)
$ T make_decoding_table
try ignore ( make_decoding_table [ |'1'| ] ) ; false \
with Invalid_table - > true
try ignore ( make_decoding_table ( Array.make 2000 ' 1 ' ) ) ; false \
with Invalid_table - > true
try ignore (make_decoding_table [|'1'|]); false \
with Invalid_table -> true
try ignore (make_decoding_table (Array.make 2000 '1')); false \
with Invalid_table -> true
*)
$ T str_decode
try ignore ( str_decode ~tbl:[|1| ] " mlk " ) ; false \
with Invalid_table - > true
try ignore ( str_decode ~tbl:(Array.make 2000 1 ) " mlk " ) ; false \
with Invalid_table - > true
try ignore (str_decode ~tbl:[|1|] "mlk"); false \
with Invalid_table -> true
try ignore (str_decode ~tbl:(Array.make 2000 1) "mlk"); false \
with Invalid_table -> true
*)
|
08fa39e758ab8607b50fc9c7c12cd018a714946b7bb614aac1528c9a3349cf22 | agentm/project-m36 | hair.hs | # LANGUAGE DeriveGeneric , , OverloadedStrings , DerivingVia #
import ProjectM36.Client
import ProjectM36.Relation.Show.Term
import GHC.Generics
import Data.Text
import Control.DeepSeq
import qualified Data.Map as M
import qualified Data.Text.IO as TIO
import Data.Proxy
import Codec.Winery
data Hair = Bald | Brown | Blond | OtherColor Text
deriving (Generic, Show, Eq, NFData, Atomable)
deriving Serialise via WineryVariant Hair
main :: IO ()
main = do
--connect to the database
let connInfo = InProcessConnectionInfo NoPersistence emptyNotificationCallback []
eCheck v = do
x <- v
case x of
Left err -> error (show err)
Right x' -> pure x'
conn <- eCheck $ connectProjectM36 connInfo
--create a database session at the default branch of the fresh database
sessionId <- eCheck $ createSessionAtHead conn "master"
--create the data type in the database context
eCheck $ executeDatabaseContextExpr sessionId conn (toAddTypeExpr (Proxy :: Proxy Hair))
create a relation with the new Hair AtomType
let blond = NakedAtomExpr (toAtom Blond)
eCheck $ executeDatabaseContextExpr sessionId conn
(Assign "people"
(MakeRelationFromExprs Nothing $ TupleExprs () [
TupleExpr (M.fromList [("hair", blond), ("name", NakedAtomExpr (TextAtom "Colin"))])]))
let restrictionPredicate = AttributeEqualityPredicate "hair" blond
peopleRel <- eCheck $ executeRelationalExpr sessionId conn (Restrict restrictionPredicate (RelationVariable "people" ()))
TIO.putStrLn (showRelation peopleRel)
| null | https://raw.githubusercontent.com/agentm/project-m36/57a75b35e84bebf0945db6dae53350fda83f24b6/examples/hair.hs | haskell | connect to the database
create a database session at the default branch of the fresh database
create the data type in the database context | # LANGUAGE DeriveGeneric , , OverloadedStrings , DerivingVia #
import ProjectM36.Client
import ProjectM36.Relation.Show.Term
import GHC.Generics
import Data.Text
import Control.DeepSeq
import qualified Data.Map as M
import qualified Data.Text.IO as TIO
import Data.Proxy
import Codec.Winery
data Hair = Bald | Brown | Blond | OtherColor Text
deriving (Generic, Show, Eq, NFData, Atomable)
deriving Serialise via WineryVariant Hair
main :: IO ()
main = do
let connInfo = InProcessConnectionInfo NoPersistence emptyNotificationCallback []
eCheck v = do
x <- v
case x of
Left err -> error (show err)
Right x' -> pure x'
conn <- eCheck $ connectProjectM36 connInfo
sessionId <- eCheck $ createSessionAtHead conn "master"
eCheck $ executeDatabaseContextExpr sessionId conn (toAddTypeExpr (Proxy :: Proxy Hair))
create a relation with the new Hair AtomType
let blond = NakedAtomExpr (toAtom Blond)
eCheck $ executeDatabaseContextExpr sessionId conn
(Assign "people"
(MakeRelationFromExprs Nothing $ TupleExprs () [
TupleExpr (M.fromList [("hair", blond), ("name", NakedAtomExpr (TextAtom "Colin"))])]))
let restrictionPredicate = AttributeEqualityPredicate "hair" blond
peopleRel <- eCheck $ executeRelationalExpr sessionId conn (Restrict restrictionPredicate (RelationVariable "people" ()))
TIO.putStrLn (showRelation peopleRel)
|
3b3c269715c3daf9d13c79777db834b9fb7b623f4f8f796d781d28c1ee122a02 | xclerc/ocamljava | atomicReference.mli |
* This file is part of library .
* Copyright ( C ) 2007 - 2015 .
*
* library is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation ; either version 3 of the License , or
* ( at your option ) any later version .
*
* library is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program . If not , see < / > .
* This file is part of OCaml-Java library.
* Copyright (C) 2007-2015 Xavier Clerc.
*
* OCaml-Java library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* OCaml-Java library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see </>.
*)
(** Atomic containers for values. *)
type 'a t = java'util'concurrent'atomic'AtomicReference java_instance
* The type of atomic containers for values .
{ b WARNING :} physical comparison is used by the container .
{ b CONSEQUENCE 1 :} should be used with caution to store [ int32 ] ,
[ int64 ] , [ nativeint ] , or [ double ] values as they are wrapped into
blocks . Hence , comparisons are done on block addresses rather than
on wrapped values .
{ b CONSEQUENCE 2 :} as uses boxed values for [ int ] values ,
the container should not be used to store [ int ] values .
Any other type can be safely stored ( caching of { i some } [ int ] values
ensure that sum types are correctly handled ) .
{b WARNING:} physical comparison is used by the container.
{b CONSEQUENCE 1:} should be used with caution to store [int32],
[int64], [nativeint], or [double] values as they are wrapped into
blocks. Hence, comparisons are done on block addresses rather than
on wrapped values.
{b CONSEQUENCE 2:} as OCaml-Java uses boxed values for [int] values,
the container should not be used to store [int] values.
Any other type can be safely stored (caching of {i some} [int] values
ensure that sum types are correctly handled). *)
val make : 'a -> 'a t
(** Returns a new container holding the passed value. *)
val compare_and_set : 'a t -> 'a -> 'a -> bool
(** [compare_and_set a e u] atomically sets the value of [a] to [u] if
the current value is [e]. Returns whether the value of [a] was equal
to [e]. *)
val get : 'a t -> 'a
(** Returns the current value. *)
val get_and_set : 'a t -> 'a -> 'a
(** [get_and_set a x] atomically sets the value of [a] to [x], and
returns the previous value. *)
val lazy_set : 'a t -> 'a -> unit
(** [lazy_set a x] eventually sets the value of [a] to [x]. *)
val set : 'a t -> 'a -> unit
(** [set a x] sets the value of [a] to [x]. *)
val weak_compare_and_set : 'a t -> 'a -> 'a -> bool
(** Similar to {!compare_and_set}, with a {i weak} semantics: may be
faster on some platforms, but does not provide ordering guarantees. *)
* { 6 Null value }
val null : 'a t
(** The [null] value. *)
external is_null : 'a t -> bool =
"java is_null"
(** [is_null obj] returns [true] iff [obj] is equal to [null]. *)
external is_not_null : 'a t -> bool =
"java is_not_null"
(** [is_not_null obj] returns [false] iff [obj] is equal to [null]. *)
* { 6 Miscellaneous }
val wrap : 'a t -> 'a t option
(** [wrap obj] wraps the reference [obj] into an option type:
- [Some x] if [obj] is not [null];
- [None] if [obj] is [null]. *)
val unwrap : 'a t option -> 'a t
(** [unwrap obj] unwraps the option [obj] into a bare reference:
- [Some x] is mapped to [x];
- [None] is mapped to [null]. *)
| null | https://raw.githubusercontent.com/xclerc/ocamljava/8330bfdfd01d0c348f2ba2f0f23d8f5a8f6015b1/library/concurrent/src/atomic/atomicReference.mli | ocaml | * Atomic containers for values.
* Returns a new container holding the passed value.
* [compare_and_set a e u] atomically sets the value of [a] to [u] if
the current value is [e]. Returns whether the value of [a] was equal
to [e].
* Returns the current value.
* [get_and_set a x] atomically sets the value of [a] to [x], and
returns the previous value.
* [lazy_set a x] eventually sets the value of [a] to [x].
* [set a x] sets the value of [a] to [x].
* Similar to {!compare_and_set}, with a {i weak} semantics: may be
faster on some platforms, but does not provide ordering guarantees.
* The [null] value.
* [is_null obj] returns [true] iff [obj] is equal to [null].
* [is_not_null obj] returns [false] iff [obj] is equal to [null].
* [wrap obj] wraps the reference [obj] into an option type:
- [Some x] if [obj] is not [null];
- [None] if [obj] is [null].
* [unwrap obj] unwraps the option [obj] into a bare reference:
- [Some x] is mapped to [x];
- [None] is mapped to [null]. |
* This file is part of library .
* Copyright ( C ) 2007 - 2015 .
*
* library is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation ; either version 3 of the License , or
* ( at your option ) any later version .
*
* library is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program . If not , see < / > .
* This file is part of OCaml-Java library.
* Copyright (C) 2007-2015 Xavier Clerc.
*
* OCaml-Java library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* OCaml-Java library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see </>.
*)
type 'a t = java'util'concurrent'atomic'AtomicReference java_instance
* The type of atomic containers for values .
{ b WARNING :} physical comparison is used by the container .
{ b CONSEQUENCE 1 :} should be used with caution to store [ int32 ] ,
[ int64 ] , [ nativeint ] , or [ double ] values as they are wrapped into
blocks . Hence , comparisons are done on block addresses rather than
on wrapped values .
{ b CONSEQUENCE 2 :} as uses boxed values for [ int ] values ,
the container should not be used to store [ int ] values .
Any other type can be safely stored ( caching of { i some } [ int ] values
ensure that sum types are correctly handled ) .
{b WARNING:} physical comparison is used by the container.
{b CONSEQUENCE 1:} should be used with caution to store [int32],
[int64], [nativeint], or [double] values as they are wrapped into
blocks. Hence, comparisons are done on block addresses rather than
on wrapped values.
{b CONSEQUENCE 2:} as OCaml-Java uses boxed values for [int] values,
the container should not be used to store [int] values.
Any other type can be safely stored (caching of {i some} [int] values
ensure that sum types are correctly handled). *)
val make : 'a -> 'a t
val compare_and_set : 'a t -> 'a -> 'a -> bool
val get : 'a t -> 'a
val get_and_set : 'a t -> 'a -> 'a
val lazy_set : 'a t -> 'a -> unit
val set : 'a t -> 'a -> unit
val weak_compare_and_set : 'a t -> 'a -> 'a -> bool
* { 6 Null value }
val null : 'a t
external is_null : 'a t -> bool =
"java is_null"
external is_not_null : 'a t -> bool =
"java is_not_null"
* { 6 Miscellaneous }
val wrap : 'a t -> 'a t option
val unwrap : 'a t option -> 'a t
|
64d43982e2295f976bf16dbdf3444e04ca4a7e54744b7649ca44e1325ac6cd51 | jabber-at/ejabberd | mod_admin_update_sql.erl | %%%-------------------------------------------------------------------
%%% File : mod_admin_update_sql.erl
Author : < >
%%% Purpose : Convert SQL DB to the new format
Created : 9 Aug 2017 by < >
%%%
%%%
ejabberd , Copyright ( C ) 2002 - 2018 ProcessOne
%%%
%%% 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 .
%%%
%%%-------------------------------------------------------------------
-module(mod_admin_update_sql).
-author('').
-behaviour(gen_mod).
-export([start/2, stop/1, reload/3, mod_options/1,
get_commands_spec/0, depends/2]).
% Commands API
-export([update_sql/0]).
-include("logger.hrl").
-include("ejabberd_commands.hrl").
-include("xmpp.hrl").
-include("ejabberd_sql_pt.hrl").
%%%
%%% gen_mod
%%%
start(_Host, _Opts) ->
ejabberd_commands:register_commands(get_commands_spec()).
stop(_Host) ->
ejabberd_commands:unregister_commands(get_commands_spec()).
reload(_Host, _NewOpts, _OldOpts) ->
ok.
depends(_Host, _Opts) ->
[].
%%%
%%% Register commands
%%%
get_commands_spec() ->
[#ejabberd_commands{name = update_sql, tags = [sql],
desc = "Convert SQL DB to the new format",
module = ?MODULE, function = update_sql,
args = [],
args_example = [],
args_desc = [],
result = {res, rescode},
result_example = ok,
result_desc = "Status code: 0 on success, 1 otherwise"}
].
update_sql() ->
lists:foreach(
fun(Host) ->
case ejabberd_sql_sup:get_pids(Host) of
[] ->
ok;
_ ->
update_sql(Host)
end
end, ejabberd_config:get_myhosts()),
ok.
-record(state, {host :: binary(),
dbtype :: mysql | pgsql | sqlite | mssql | odbc,
escape}).
update_sql(Host) ->
LHost = jid:nameprep(Host),
DBType = ejabberd_config:get_option({sql_type, LHost}, undefined),
IsSupported =
case DBType of
pgsql -> true;
_ -> false
end,
if
not IsSupported ->
io:format("Converting ~p DB is not supported~n", [DBType]),
error;
true ->
Escape =
case DBType of
mssql -> fun ejabberd_sql:standard_escape/1;
sqlite -> fun ejabberd_sql:standard_escape/1;
_ -> fun ejabberd_sql:escape/1
end,
State = #state{host = LHost,
dbtype = DBType,
escape = Escape},
update_tables(State)
end.
update_tables(State) ->
add_sh_column(State, "users"),
drop_pkey(State, "users"),
add_pkey(State, "users", ["server_host", "username"]),
drop_sh_default(State, "users"),
add_sh_column(State, "last"),
drop_pkey(State, "last"),
add_pkey(State, "last", ["server_host", "username"]),
drop_sh_default(State, "last"),
add_sh_column(State, "rosterusers"),
drop_index(State, "i_rosteru_user_jid"),
drop_index(State, "i_rosteru_username"),
drop_index(State, "i_rosteru_jid"),
create_unique_index(State, "rosterusers", "i_rosteru_sh_user_jid", ["server_host", "username", "jid"]),
create_index(State, "rosterusers", "i_rosteru_sh_username", ["server_host", "username"]),
create_index(State, "rosterusers", "i_rosteru_sh_jid", ["server_host", "jid"]),
drop_sh_default(State, "rosterusers"),
add_sh_column(State, "rostergroups"),
drop_index(State, "pk_rosterg_user_jid"),
create_index(State, "rostergroups", "i_rosterg_sh_user_jid", ["server_host", "username", "jid"]),
drop_sh_default(State, "rostergroups"),
add_sh_column(State, "sr_group"),
add_pkey(State, "sr_group", ["server_host", "name"]),
drop_sh_default(State, "sr_group"),
add_sh_column(State, "sr_user"),
drop_index(State, "i_sr_user_jid_grp"),
drop_index(State, "i_sr_user_jid"),
drop_index(State, "i_sr_user_grp"),
add_pkey(State, "sr_user", ["server_host", "jid", "grp"]),
create_index(State, "sr_user", "i_sr_user_sh_jid", ["server_host", "jid"]),
create_index(State, "sr_user", "i_sr_user_sh_grp", ["server_host", "grp"]),
drop_sh_default(State, "sr_user"),
add_sh_column(State, "spool"),
drop_index(State, "i_despool"),
create_index(State, "spool", "i_spool_sh_username", ["server_host", "username"]),
drop_sh_default(State, "spool"),
add_sh_column(State, "archive"),
drop_index(State, "i_username"),
drop_index(State, "i_username_timestamp"),
drop_index(State, "i_timestamp"),
drop_index(State, "i_peer"),
drop_index(State, "i_bare_peer"),
create_index(State, "archive", "i_archive_sh_username_timestamp", ["server_host", "username", "timestamp"]),
create_index(State, "archive", "i_archive_sh_timestamp", ["server_host", "timestamp"]),
create_index(State, "archive", "i_archive_sh_peer", ["server_host", "peer"]),
create_index(State, "archive", "i_archive_sh_bare_peer", ["server_host", "bare_peer"]),
drop_sh_default(State, "archive"),
add_sh_column(State, "archive_prefs"),
drop_pkey(State, "archive_prefs"),
add_pkey(State, "archive_prefs", ["server_host", "username"]),
drop_sh_default(State, "archive_prefs"),
add_sh_column(State, "vcard"),
drop_pkey(State, "vcard"),
add_pkey(State, "vcard", ["server_host", "username"]),
drop_sh_default(State, "vcard"),
add_sh_column(State, "vcard_search"),
drop_pkey(State, "vcard_search"),
drop_index(State, "i_vcard_search_lfn"),
drop_index(State, "i_vcard_search_lfamily"),
drop_index(State, "i_vcard_search_lgiven"),
drop_index(State, "i_vcard_search_lmiddle"),
drop_index(State, "i_vcard_search_lnickname"),
drop_index(State, "i_vcard_search_lbday"),
drop_index(State, "i_vcard_search_lctry"),
drop_index(State, "i_vcard_search_llocality"),
drop_index(State, "i_vcard_search_lemail"),
drop_index(State, "i_vcard_search_lorgname"),
drop_index(State, "i_vcard_search_lorgunit"),
add_pkey(State, "vcard_search", ["server_host", "username"]),
create_index(State, "vcard_search", "i_vcard_search_sh_lfn", ["server_host", "lfn"]),
create_index(State, "vcard_search", "i_vcard_search_sh_lfamily", ["server_host", "lfamily"]),
create_index(State, "vcard_search", "i_vcard_search_sh_lgiven", ["server_host", "lgiven"]),
create_index(State, "vcard_search", "i_vcard_search_sh_lmiddle", ["server_host", "lmiddle"]),
create_index(State, "vcard_search", "i_vcard_search_sh_lnickname", ["server_host", "lnickname"]),
create_index(State, "vcard_search", "i_vcard_search_sh_lbday", ["server_host", "lbday"]),
create_index(State, "vcard_search", "i_vcard_search_sh_lctry", ["server_host", "lctry"]),
create_index(State, "vcard_search", "i_vcard_search_sh_llocality", ["server_host", "llocality"]),
create_index(State, "vcard_search", "i_vcard_search_sh_lemail", ["server_host", "lemail"]),
create_index(State, "vcard_search", "i_vcard_search_sh_lorgname", ["server_host", "lorgname"]),
create_index(State, "vcard_search", "i_vcard_search_sh_lorgunit", ["server_host", "lorgunit"]),
drop_sh_default(State, "vcard_search"),
add_sh_column(State, "privacy_default_list"),
drop_pkey(State, "privacy_default_list"),
add_pkey(State, "privacy_default_list", ["server_host", "username"]),
drop_sh_default(State, "privacy_default_list"),
add_sh_column(State, "privacy_list"),
drop_index(State, "i_privacy_list_username"),
drop_index(State, "i_privacy_list_username_name"),
create_index(State, "privacy_list", "i_privacy_list_sh_username", ["server_host", "username"]),
create_unique_index(State, "privacy_list", "i_privacy_list_sh_username_name", ["server_host", "username", "name"]),
drop_sh_default(State, "privacy_list"),
add_sh_column(State, "private_storage"),
drop_index(State, "i_private_storage_username"),
drop_index(State, "i_private_storage_username_namespace"),
add_pkey(State, "private_storage", ["server_host", "username", "namespace"]),
create_index(State, "private_storage", "i_private_storage_sh_username", ["server_host", "username"]),
drop_sh_default(State, "private_storage"),
add_sh_column(State, "roster_version"),
drop_pkey(State, "roster_version"),
add_pkey(State, "roster_version", ["server_host", "username"]),
drop_sh_default(State, "roster_version"),
add_sh_column(State, "muc_room"),
drop_sh_default(State, "muc_room"),
add_sh_column(State, "muc_registered"),
drop_sh_default(State, "muc_registered"),
add_sh_column(State, "muc_online_room"),
drop_sh_default(State, "muc_online_room"),
add_sh_column(State, "muc_online_users"),
drop_sh_default(State, "muc_online_users"),
add_sh_column(State, "motd"),
drop_pkey(State, "motd"),
add_pkey(State, "motd", ["server_host", "username"]),
drop_sh_default(State, "motd"),
add_sh_column(State, "sm"),
drop_index(State, "i_sm_sid"),
drop_index(State, "i_sm_username"),
add_pkey(State, "sm", ["usec", "pid"]),
create_index(State, "sm", "i_sm_sh_username", ["server_host", "username"]),
drop_sh_default(State, "sm"),
add_sh_column(State, "carboncopy"),
drop_index(State, "i_carboncopy_ur"),
drop_index(State, "i_carboncopy_user"),
add_pkey(State, "carboncopy", ["server_host", "username", "resource"]),
create_index(State, "carboncopy", "i_carboncopy_sh_user", ["server_host", "username"]),
drop_sh_default(State, "carboncopy"),
add_sh_column(State, "push_session"),
drop_index(State, "i_push_usn"),
drop_index(State, "i_push_ut"),
add_pkey(State, "push_session", ["server_host", "username", "timestamp"]),
create_index(State, "push_session", "i_push_session_susn", ["server_host", "username", "service", "node"]),
drop_sh_default(State, "push_session"),
ok.
add_sh_column(#state{dbtype = pgsql} = State, Table) ->
sql_query(
State#state.host,
["ALTER TABLE ", Table, " ADD COLUMN server_host text NOT NULL DEFAULT '",
(State#state.escape)(State#state.host),
"';"]);
add_sh_column(#state{dbtype = mysql} = State, Table) ->
sql_query(
State#state.host,
["ALTER TABLE ", Table, " ADD COLUMN server_host text NOT NULL DEFAULT '",
(State#state.escape)(State#state.host),
"';"]).
drop_pkey(#state{dbtype = pgsql} = State, Table) ->
sql_query(
State#state.host,
["ALTER TABLE ", Table, " DROP CONSTRAINT ", Table, "_pkey;"]);
drop_pkey(#state{dbtype = mysql} = State, Table) ->
sql_query(
State#state.host,
["ALTER TABLE ", Table, " DROP PRIMARY KEY;"]).
add_pkey(#state{dbtype = pgsql} = State, Table, Cols) ->
SCols = string:join(Cols, ", "),
sql_query(
State#state.host,
["ALTER TABLE ", Table, " ADD PRIMARY KEY (", SCols, ");"]);
add_pkey(#state{dbtype = mysql} = State, Table, Cols) ->
SCols = string:join(Cols, ", "),
sql_query(
State#state.host,
["ALTER TABLE ", Table, " ADD PRIMARY KEY (", SCols, ");"]).
drop_sh_default(#state{dbtype = pgsql} = State, Table) ->
sql_query(
State#state.host,
["ALTER TABLE ", Table, " ALTER COLUMN server_host DROP DEFAULT;"]);
drop_sh_default(#state{dbtype = mysql} = State, Table) ->
sql_query(
State#state.host,
["ALTER TABLE ", Table, " ALTER COLUMN server_host DROP DEFAULT;"]).
drop_index(#state{dbtype = pgsql} = State, Index) ->
sql_query(
State#state.host,
["DROP INDEX ", Index, ";"]);
drop_index(#state{dbtype = mysql} = State, Index) ->
sql_query(
State#state.host,
["DROP INDEX ", Index, ";"]).
create_unique_index(#state{dbtype = pgsql} = State, Table, Index, Cols) ->
SCols = string:join(Cols, ", "),
sql_query(
State#state.host,
["CREATE UNIQUE INDEX ", Index, " ON ", Table, " USING btree (",
SCols, ");"]);
create_unique_index(#state{dbtype = mysql} = State, Table, Index, Cols) ->
Cols2 = [C ++ "(75)" || C <- Cols],
SCols = string:join(Cols2, ", "),
sql_query(
State#state.host,
["CREATE UNIQUE INDEX ", Index, " ON ", Table, "(",
SCols, ");"]).
create_index(#state{dbtype = pgsql} = State, Table, Index, Cols) ->
SCols = string:join(Cols, ", "),
sql_query(
State#state.host,
["CREATE INDEX ", Index, " ON ", Table, " USING btree (",
SCols, ");"]);
create_index(#state{dbtype = mysql} = State, Table, Index, Cols) ->
Cols2 = [C ++ "(75)" || C <- Cols],
SCols = string:join(Cols2, ", "),
sql_query(
State#state.host,
["CREATE INDEX ", Index, " ON ", Table, "(",
SCols, ");"]).
sql_query(Host, Query) ->
io:format("executing \"~s\" on ~s~n", [Query, Host]),
case ejabberd_sql:sql_query(Host, Query) of
{error, Error} ->
io:format("error: ~p~n", [Error]),
ok;
_ ->
ok
end.
mod_options(_) -> [].
| null | https://raw.githubusercontent.com/jabber-at/ejabberd/7bfec36856eaa4df21b26e879d3ba90285bad1aa/src/mod_admin_update_sql.erl | erlang | -------------------------------------------------------------------
File : mod_admin_update_sql.erl
Purpose : Convert SQL DB to the new format
This program is free software; you can redistribute it and/or
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.
-------------------------------------------------------------------
Commands API
gen_mod
Register commands
| Author : < >
Created : 9 Aug 2017 by < >
ejabberd , Copyright ( C ) 2002 - 2018 ProcessOne
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 2 of the
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 .
-module(mod_admin_update_sql).
-author('').
-behaviour(gen_mod).
-export([start/2, stop/1, reload/3, mod_options/1,
get_commands_spec/0, depends/2]).
-export([update_sql/0]).
-include("logger.hrl").
-include("ejabberd_commands.hrl").
-include("xmpp.hrl").
-include("ejabberd_sql_pt.hrl").
start(_Host, _Opts) ->
ejabberd_commands:register_commands(get_commands_spec()).
stop(_Host) ->
ejabberd_commands:unregister_commands(get_commands_spec()).
reload(_Host, _NewOpts, _OldOpts) ->
ok.
depends(_Host, _Opts) ->
[].
get_commands_spec() ->
[#ejabberd_commands{name = update_sql, tags = [sql],
desc = "Convert SQL DB to the new format",
module = ?MODULE, function = update_sql,
args = [],
args_example = [],
args_desc = [],
result = {res, rescode},
result_example = ok,
result_desc = "Status code: 0 on success, 1 otherwise"}
].
update_sql() ->
lists:foreach(
fun(Host) ->
case ejabberd_sql_sup:get_pids(Host) of
[] ->
ok;
_ ->
update_sql(Host)
end
end, ejabberd_config:get_myhosts()),
ok.
-record(state, {host :: binary(),
dbtype :: mysql | pgsql | sqlite | mssql | odbc,
escape}).
update_sql(Host) ->
LHost = jid:nameprep(Host),
DBType = ejabberd_config:get_option({sql_type, LHost}, undefined),
IsSupported =
case DBType of
pgsql -> true;
_ -> false
end,
if
not IsSupported ->
io:format("Converting ~p DB is not supported~n", [DBType]),
error;
true ->
Escape =
case DBType of
mssql -> fun ejabberd_sql:standard_escape/1;
sqlite -> fun ejabberd_sql:standard_escape/1;
_ -> fun ejabberd_sql:escape/1
end,
State = #state{host = LHost,
dbtype = DBType,
escape = Escape},
update_tables(State)
end.
update_tables(State) ->
add_sh_column(State, "users"),
drop_pkey(State, "users"),
add_pkey(State, "users", ["server_host", "username"]),
drop_sh_default(State, "users"),
add_sh_column(State, "last"),
drop_pkey(State, "last"),
add_pkey(State, "last", ["server_host", "username"]),
drop_sh_default(State, "last"),
add_sh_column(State, "rosterusers"),
drop_index(State, "i_rosteru_user_jid"),
drop_index(State, "i_rosteru_username"),
drop_index(State, "i_rosteru_jid"),
create_unique_index(State, "rosterusers", "i_rosteru_sh_user_jid", ["server_host", "username", "jid"]),
create_index(State, "rosterusers", "i_rosteru_sh_username", ["server_host", "username"]),
create_index(State, "rosterusers", "i_rosteru_sh_jid", ["server_host", "jid"]),
drop_sh_default(State, "rosterusers"),
add_sh_column(State, "rostergroups"),
drop_index(State, "pk_rosterg_user_jid"),
create_index(State, "rostergroups", "i_rosterg_sh_user_jid", ["server_host", "username", "jid"]),
drop_sh_default(State, "rostergroups"),
add_sh_column(State, "sr_group"),
add_pkey(State, "sr_group", ["server_host", "name"]),
drop_sh_default(State, "sr_group"),
add_sh_column(State, "sr_user"),
drop_index(State, "i_sr_user_jid_grp"),
drop_index(State, "i_sr_user_jid"),
drop_index(State, "i_sr_user_grp"),
add_pkey(State, "sr_user", ["server_host", "jid", "grp"]),
create_index(State, "sr_user", "i_sr_user_sh_jid", ["server_host", "jid"]),
create_index(State, "sr_user", "i_sr_user_sh_grp", ["server_host", "grp"]),
drop_sh_default(State, "sr_user"),
add_sh_column(State, "spool"),
drop_index(State, "i_despool"),
create_index(State, "spool", "i_spool_sh_username", ["server_host", "username"]),
drop_sh_default(State, "spool"),
add_sh_column(State, "archive"),
drop_index(State, "i_username"),
drop_index(State, "i_username_timestamp"),
drop_index(State, "i_timestamp"),
drop_index(State, "i_peer"),
drop_index(State, "i_bare_peer"),
create_index(State, "archive", "i_archive_sh_username_timestamp", ["server_host", "username", "timestamp"]),
create_index(State, "archive", "i_archive_sh_timestamp", ["server_host", "timestamp"]),
create_index(State, "archive", "i_archive_sh_peer", ["server_host", "peer"]),
create_index(State, "archive", "i_archive_sh_bare_peer", ["server_host", "bare_peer"]),
drop_sh_default(State, "archive"),
add_sh_column(State, "archive_prefs"),
drop_pkey(State, "archive_prefs"),
add_pkey(State, "archive_prefs", ["server_host", "username"]),
drop_sh_default(State, "archive_prefs"),
add_sh_column(State, "vcard"),
drop_pkey(State, "vcard"),
add_pkey(State, "vcard", ["server_host", "username"]),
drop_sh_default(State, "vcard"),
add_sh_column(State, "vcard_search"),
drop_pkey(State, "vcard_search"),
drop_index(State, "i_vcard_search_lfn"),
drop_index(State, "i_vcard_search_lfamily"),
drop_index(State, "i_vcard_search_lgiven"),
drop_index(State, "i_vcard_search_lmiddle"),
drop_index(State, "i_vcard_search_lnickname"),
drop_index(State, "i_vcard_search_lbday"),
drop_index(State, "i_vcard_search_lctry"),
drop_index(State, "i_vcard_search_llocality"),
drop_index(State, "i_vcard_search_lemail"),
drop_index(State, "i_vcard_search_lorgname"),
drop_index(State, "i_vcard_search_lorgunit"),
add_pkey(State, "vcard_search", ["server_host", "username"]),
create_index(State, "vcard_search", "i_vcard_search_sh_lfn", ["server_host", "lfn"]),
create_index(State, "vcard_search", "i_vcard_search_sh_lfamily", ["server_host", "lfamily"]),
create_index(State, "vcard_search", "i_vcard_search_sh_lgiven", ["server_host", "lgiven"]),
create_index(State, "vcard_search", "i_vcard_search_sh_lmiddle", ["server_host", "lmiddle"]),
create_index(State, "vcard_search", "i_vcard_search_sh_lnickname", ["server_host", "lnickname"]),
create_index(State, "vcard_search", "i_vcard_search_sh_lbday", ["server_host", "lbday"]),
create_index(State, "vcard_search", "i_vcard_search_sh_lctry", ["server_host", "lctry"]),
create_index(State, "vcard_search", "i_vcard_search_sh_llocality", ["server_host", "llocality"]),
create_index(State, "vcard_search", "i_vcard_search_sh_lemail", ["server_host", "lemail"]),
create_index(State, "vcard_search", "i_vcard_search_sh_lorgname", ["server_host", "lorgname"]),
create_index(State, "vcard_search", "i_vcard_search_sh_lorgunit", ["server_host", "lorgunit"]),
drop_sh_default(State, "vcard_search"),
add_sh_column(State, "privacy_default_list"),
drop_pkey(State, "privacy_default_list"),
add_pkey(State, "privacy_default_list", ["server_host", "username"]),
drop_sh_default(State, "privacy_default_list"),
add_sh_column(State, "privacy_list"),
drop_index(State, "i_privacy_list_username"),
drop_index(State, "i_privacy_list_username_name"),
create_index(State, "privacy_list", "i_privacy_list_sh_username", ["server_host", "username"]),
create_unique_index(State, "privacy_list", "i_privacy_list_sh_username_name", ["server_host", "username", "name"]),
drop_sh_default(State, "privacy_list"),
add_sh_column(State, "private_storage"),
drop_index(State, "i_private_storage_username"),
drop_index(State, "i_private_storage_username_namespace"),
add_pkey(State, "private_storage", ["server_host", "username", "namespace"]),
create_index(State, "private_storage", "i_private_storage_sh_username", ["server_host", "username"]),
drop_sh_default(State, "private_storage"),
add_sh_column(State, "roster_version"),
drop_pkey(State, "roster_version"),
add_pkey(State, "roster_version", ["server_host", "username"]),
drop_sh_default(State, "roster_version"),
add_sh_column(State, "muc_room"),
drop_sh_default(State, "muc_room"),
add_sh_column(State, "muc_registered"),
drop_sh_default(State, "muc_registered"),
add_sh_column(State, "muc_online_room"),
drop_sh_default(State, "muc_online_room"),
add_sh_column(State, "muc_online_users"),
drop_sh_default(State, "muc_online_users"),
add_sh_column(State, "motd"),
drop_pkey(State, "motd"),
add_pkey(State, "motd", ["server_host", "username"]),
drop_sh_default(State, "motd"),
add_sh_column(State, "sm"),
drop_index(State, "i_sm_sid"),
drop_index(State, "i_sm_username"),
add_pkey(State, "sm", ["usec", "pid"]),
create_index(State, "sm", "i_sm_sh_username", ["server_host", "username"]),
drop_sh_default(State, "sm"),
add_sh_column(State, "carboncopy"),
drop_index(State, "i_carboncopy_ur"),
drop_index(State, "i_carboncopy_user"),
add_pkey(State, "carboncopy", ["server_host", "username", "resource"]),
create_index(State, "carboncopy", "i_carboncopy_sh_user", ["server_host", "username"]),
drop_sh_default(State, "carboncopy"),
add_sh_column(State, "push_session"),
drop_index(State, "i_push_usn"),
drop_index(State, "i_push_ut"),
add_pkey(State, "push_session", ["server_host", "username", "timestamp"]),
create_index(State, "push_session", "i_push_session_susn", ["server_host", "username", "service", "node"]),
drop_sh_default(State, "push_session"),
ok.
add_sh_column(#state{dbtype = pgsql} = State, Table) ->
sql_query(
State#state.host,
["ALTER TABLE ", Table, " ADD COLUMN server_host text NOT NULL DEFAULT '",
(State#state.escape)(State#state.host),
"';"]);
add_sh_column(#state{dbtype = mysql} = State, Table) ->
sql_query(
State#state.host,
["ALTER TABLE ", Table, " ADD COLUMN server_host text NOT NULL DEFAULT '",
(State#state.escape)(State#state.host),
"';"]).
drop_pkey(#state{dbtype = pgsql} = State, Table) ->
sql_query(
State#state.host,
["ALTER TABLE ", Table, " DROP CONSTRAINT ", Table, "_pkey;"]);
drop_pkey(#state{dbtype = mysql} = State, Table) ->
sql_query(
State#state.host,
["ALTER TABLE ", Table, " DROP PRIMARY KEY;"]).
add_pkey(#state{dbtype = pgsql} = State, Table, Cols) ->
SCols = string:join(Cols, ", "),
sql_query(
State#state.host,
["ALTER TABLE ", Table, " ADD PRIMARY KEY (", SCols, ");"]);
add_pkey(#state{dbtype = mysql} = State, Table, Cols) ->
SCols = string:join(Cols, ", "),
sql_query(
State#state.host,
["ALTER TABLE ", Table, " ADD PRIMARY KEY (", SCols, ");"]).
drop_sh_default(#state{dbtype = pgsql} = State, Table) ->
sql_query(
State#state.host,
["ALTER TABLE ", Table, " ALTER COLUMN server_host DROP DEFAULT;"]);
drop_sh_default(#state{dbtype = mysql} = State, Table) ->
sql_query(
State#state.host,
["ALTER TABLE ", Table, " ALTER COLUMN server_host DROP DEFAULT;"]).
drop_index(#state{dbtype = pgsql} = State, Index) ->
sql_query(
State#state.host,
["DROP INDEX ", Index, ";"]);
drop_index(#state{dbtype = mysql} = State, Index) ->
sql_query(
State#state.host,
["DROP INDEX ", Index, ";"]).
create_unique_index(#state{dbtype = pgsql} = State, Table, Index, Cols) ->
SCols = string:join(Cols, ", "),
sql_query(
State#state.host,
["CREATE UNIQUE INDEX ", Index, " ON ", Table, " USING btree (",
SCols, ");"]);
create_unique_index(#state{dbtype = mysql} = State, Table, Index, Cols) ->
Cols2 = [C ++ "(75)" || C <- Cols],
SCols = string:join(Cols2, ", "),
sql_query(
State#state.host,
["CREATE UNIQUE INDEX ", Index, " ON ", Table, "(",
SCols, ");"]).
create_index(#state{dbtype = pgsql} = State, Table, Index, Cols) ->
SCols = string:join(Cols, ", "),
sql_query(
State#state.host,
["CREATE INDEX ", Index, " ON ", Table, " USING btree (",
SCols, ");"]);
create_index(#state{dbtype = mysql} = State, Table, Index, Cols) ->
Cols2 = [C ++ "(75)" || C <- Cols],
SCols = string:join(Cols2, ", "),
sql_query(
State#state.host,
["CREATE INDEX ", Index, " ON ", Table, "(",
SCols, ");"]).
sql_query(Host, Query) ->
io:format("executing \"~s\" on ~s~n", [Query, Host]),
case ejabberd_sql:sql_query(Host, Query) of
{error, Error} ->
io:format("error: ~p~n", [Error]),
ok;
_ ->
ok
end.
mod_options(_) -> [].
|
6ec28afea12854dd8782494614e9bd660b6fcc0ea9e38226258c6c8c8b0853a3 | fragnix/fragnix | Network.Wai.Middleware.RequestLogger.hs | {-# LANGUAGE Haskell2010, OverloadedStrings #-}
# LINE 1 " Network / Wai / Middleware / RequestLogger.hs " #
# LANGUAGE RecordWildCards #
-- NOTE: Due to , this module should
not use CPP .
module Network.Wai.Middleware.RequestLogger
( -- * Basic stdout logging
logStdout
, logStdoutDev
-- * Create more versions
, mkRequestLogger
, RequestLoggerSettings
, outputFormat
, autoFlush
, destination
, OutputFormat (..)
, OutputFormatter
, OutputFormatterWithDetails
, Destination (..)
, Callback
, IPAddrSource (..)
) where
import System.IO (Handle, hFlush, stdout)
import qualified Blaze.ByteString.Builder as B
import qualified Data.ByteString as BS
import Data.ByteString.Char8 (pack, unpack)
import Control.Monad (when)
import Control.Monad.IO.Class (liftIO)
import Network.Wai
( Request(..), requestBodyLength, RequestBodyLength(..)
, Middleware
, Response, responseStatus, responseHeaders
)
import System.Log.FastLogger
import Network.HTTP.Types as H
import Data.Maybe (fromMaybe)
import Data.Monoid (mconcat, (<>))
import Data.Time (getCurrentTime, diffUTCTime, NominalDiffTime)
import Network.Wai.Parse (sinkRequestBody, lbsBackEnd, fileName, Param, File
, getRequestBodyType)
import qualified Data.ByteString.Lazy as LBS
import qualified Data.ByteString.Char8 as S8
import System.Console.ANSI
import Data.IORef.Lifted
import System.IO.Unsafe
import Network.Wai.Internal (Response (..))
import Data.Default.Class (Default (def))
import Network.Wai.Logger
import Network.Wai.Middleware.RequestLogger.Internal
import Network.Wai.Header (contentLength)
import Data.Text.Encoding (decodeUtf8')
data OutputFormat = Apache IPAddrSource
| Detailed Bool -- ^ use colors?
| CustomOutputFormat OutputFormatter
| CustomOutputFormatWithDetails OutputFormatterWithDetails
type OutputFormatter = ZonedDate -> Request -> Status -> Maybe Integer -> LogStr
type OutputFormatterWithDetails =
ZonedDate -> Request -> Status -> Maybe Integer -> NominalDiffTime -> [S8.ByteString] -> B.Builder -> LogStr
data Destination = Handle Handle
| Logger LoggerSet
| Callback Callback
type Callback = LogStr -> IO ()
-- | @RequestLoggerSettings@ is an instance of Default. See <-default Data.Default> for more information.
--
-- @outputFormat@, @autoFlush@, and @destination@ are record fields
for the record type @RequestLoggerSettings@ , so they can be used to
-- modify settings values using record syntax.
data RequestLoggerSettings = RequestLoggerSettings
{
-- | Default value: @Detailed@ @True@.
outputFormat :: OutputFormat
-- | Only applies when using the @Handle@ constructor for @destination@.
--
Default value :
, autoFlush :: Bool
-- | Default: @Handle@ @stdout@.
, destination :: Destination
}
instance Default RequestLoggerSettings where
def = RequestLoggerSettings
{ outputFormat = Detailed True
, autoFlush = True
, destination = Handle stdout
}
mkRequestLogger :: RequestLoggerSettings -> IO Middleware
mkRequestLogger RequestLoggerSettings{..} = do
let (callback, flusher) =
case destination of
Handle h -> (BS.hPutStr h . logToByteString, when autoFlush (hFlush h))
Logger l -> (pushLogStr l, when autoFlush (flushLogStr l))
Callback c -> (c, return ())
callbackAndFlush str = callback str >> flusher
case outputFormat of
Apache ipsrc -> do
getdate <- getDateGetter flusher
apache <- initLogger ipsrc (LogCallback callback flusher) getdate
return $ apacheMiddleware apache
Detailed useColors -> detailedMiddleware callbackAndFlush useColors
CustomOutputFormat formatter -> do
getDate <- getDateGetter flusher
return $ customMiddleware callbackAndFlush getDate formatter
CustomOutputFormatWithDetails formatter -> do
getdate <- getDateGetter flusher
return $ customMiddlewareWithDetails callbackAndFlush getdate formatter
apacheMiddleware :: ApacheLoggerActions -> Middleware
apacheMiddleware ala app req sendResponse = app req $ \res -> do
let msize = contentLength (responseHeaders res)
apacheLogger ala req (responseStatus res) msize
sendResponse res
customMiddleware :: Callback -> IO ZonedDate -> OutputFormatter -> Middleware
customMiddleware cb getdate formatter app req sendResponse = app req $ \res -> do
date <- liftIO getdate
-- We use Nothing for the response size since we generally don't know it
liftIO $ cb $ formatter date req (responseStatus res) Nothing
sendResponse res
customMiddlewareWithDetails :: Callback -> IO ZonedDate -> OutputFormatterWithDetails -> Middleware
customMiddlewareWithDetails cb getdate formatter app req sendResponse = do
(req', reqBody) <- getRequestBody req
t0 <- getCurrentTime
app req' $ \res -> do
t1 <- getCurrentTime
date <- liftIO getdate
-- We use Nothing for the response size since we generally don't know it
builderIO <- newIORef $ B.fromByteString ""
res' <- recordChunks builderIO res
rspRcv <- sendResponse res'
_ <- liftIO . cb .
formatter date req' (responseStatus res') Nothing (t1 `diffUTCTime` t0) reqBody =<<
readIORef builderIO
return rspRcv
-- | Production request logger middleware.
--
This uses the ' Apache ' logging format , and takes IP addresses for clients from
the socket ( see ' IPAddrSource ' for more information ) . It logs to ' stdout ' .
# NOINLINE logStdout #
logStdout :: Middleware
logStdout = unsafePerformIO $ mkRequestLogger def { outputFormat = Apache FromSocket }
-- | Development request logger middleware.
--
-- This uses the 'Detailed' 'True' logging format and logs to 'stdout'.
# NOINLINE logStdoutDev #
logStdoutDev :: Middleware
logStdoutDev = unsafePerformIO $ mkRequestLogger def
-- | Prints a message using the given callback function for each request.
-- This is not for serious production use- it is inefficient.
-- It immediately consumes a POST body and fills it back in and is otherwise inefficient
--
-- Note that it logs the request immediately when it is received.
-- This meanst that you can accurately see the interleaving of requests.
-- And if the app crashes you have still logged the request.
However , if you are simulating 10 simultaneous users you may find this confusing .
--
This is lower - level - use ' ' unless you need greater control .
--
-- Example ouput:
--
-- > GET search
> Accept : text / html , application / xhtml+xml , application / xml;q=0.9,*/*;q=0.8
> Status : 200 OK 0.010555s
-- >
-- > GET static/css/normalize.css
> Params : [ ( " LXwioiBG " , " " ) ]
-- > Accept: text/css,*/*;q=0.1
> Status : 304 Not Modified 0.010555s
detailedMiddleware :: Callback -> Bool -> IO Middleware
detailedMiddleware cb useColors =
let (ansiColor, ansiMethod, ansiStatusCode) =
if useColors
then (ansiColor', ansiMethod', ansiStatusCode')
else (\_ t -> [t], (:[]), \_ t -> [t])
in return $ detailedMiddleware' cb ansiColor ansiMethod ansiStatusCode
ansiColor' :: Color -> BS.ByteString -> [BS.ByteString]
ansiColor' color bs =
[ pack $ setSGRCode [SetColor Foreground Dull color]
, bs
, pack $ setSGRCode [Reset]
]
-- | Tags http method with a unique color.
ansiMethod' :: BS.ByteString -> [BS.ByteString]
ansiMethod' m = case m of
"GET" -> ansiColor' Cyan m
"HEAD" -> ansiColor' Cyan m
"PUT" -> ansiColor' Green m
"POST" -> ansiColor' Yellow m
"DELETE" -> ansiColor' Red m
_ -> ansiColor' Magenta m
ansiStatusCode' :: BS.ByteString -> BS.ByteString -> [BS.ByteString]
ansiStatusCode' c t = case S8.take 1 c of
"2" -> ansiColor' Green t
"3" -> ansiColor' Yellow t
"4" -> ansiColor' Red t
"5" -> ansiColor' Magenta t
_ -> ansiColor' Blue t
recordChunks :: IORef B.Builder -> Response -> IO Response
recordChunks i (ResponseStream s h sb) =
return . ResponseStream s h $ (\send flush -> sb (\b -> modifyIORef i (<> b) >> send b) flush)
recordChunks i (ResponseBuilder s h b) =
modifyIORef i (<> b) >> (return $ ResponseBuilder s h b)
recordChunks _ r =
return r
getRequestBody :: Request -> IO (Request, [S8.ByteString])
getRequestBody req = do
let loop front = do
bs <- requestBody req
if S8.null bs
then return $ front []
else loop $ front . (bs:)
body <- loop id
-- logging the body here consumes it, so fill it back up
-- obviously not efficient, but this is the development logger
--
Note : previously , we simply used CL.sourceList . However ,
-- that meant that you could read the request body in twice.
-- While that in itself is not a problem, the issue is that,
-- in production, you wouldn't be able to do this, and
-- therefore some bugs wouldn't show up during testing. This
-- implementation ensures that each chunk is only returned
-- once.
ichunks <- newIORef body
let rbody = atomicModifyIORef ichunks $ \chunks ->
case chunks of
[] -> ([], S8.empty)
x:y -> (y, x)
let req' = req { requestBody = rbody }
return (req', body)
detailedMiddleware' :: Callback
-> (Color -> BS.ByteString -> [BS.ByteString])
-> (BS.ByteString -> [BS.ByteString])
-> (BS.ByteString -> BS.ByteString -> [BS.ByteString])
-> Middleware
detailedMiddleware' cb ansiColor ansiMethod ansiStatusCode app req sendResponse = do
(req', body) <-
second tuple item should not be necessary , but a test runner might mess it up
case (requestBodyLength req, contentLength (requestHeaders req)) of
-- log the request body if it is small
(KnownLength len, _) | len <= 2048 -> getRequestBody req
(_, Just len) | len <= 2048 -> getRequestBody req
_ -> return (req, [])
let reqbodylog _ = if null body then [""] else ansiColor White " Request Body: " <> body <> ["\n"]
reqbody = concatMap (either (const [""]) reqbodylog . decodeUtf8') body
postParams <- if requestMethod req `elem` ["GET", "HEAD"]
then return []
else do postParams <- liftIO $ allPostParams body
return $ collectPostParams postParams
let getParams = map emptyGetParam $ queryString req
accept = fromMaybe "" $ lookup H.hAccept $ requestHeaders req
params = let par | not $ null postParams = [pack (show postParams)]
| not $ null getParams = [pack (show getParams)]
| otherwise = []
in if null par then [""] else ansiColor White " Params: " <> par <> ["\n"]
t0 <- getCurrentTime
app req' $ \rsp -> do
let isRaw =
case rsp of
ResponseRaw{} -> True
_ -> False
stCode = statusBS rsp
stMsg = msgBS rsp
t1 <- getCurrentTime
-- log the status of the response
cb $ mconcat $ map toLogStr $
ansiMethod (requestMethod req) ++ [" ", rawPathInfo req, "\n"] ++
params ++ reqbody ++
ansiColor White " Accept: " ++ [accept, "\n"] ++
if isRaw then [] else
ansiColor White " Status: " ++
ansiStatusCode stCode (stCode <> " " <> stMsg) ++
[" ", pack $ show $ diffUTCTime t1 t0, "\n"]
sendResponse rsp
where
allPostParams body =
case getRequestBodyType req of
Nothing -> return ([], [])
Just rbt -> do
ichunks <- newIORef body
let rbody = atomicModifyIORef ichunks $ \chunks ->
case chunks of
[] -> ([], S8.empty)
x:y -> (y, x)
sinkRequestBody lbsBackEnd rbt rbody
emptyGetParam :: (BS.ByteString, Maybe BS.ByteString) -> (BS.ByteString, BS.ByteString)
emptyGetParam (k, Just v) = (k,v)
emptyGetParam (k, Nothing) = (k,"")
collectPostParams :: ([Param], [File LBS.ByteString]) -> [Param]
collectPostParams (postParams, files) = postParams ++
map (\(k,v) -> (k, "FILE: " <> fileName v)) files
statusBS :: Response -> BS.ByteString
statusBS = pack . show . statusCode . responseStatus
msgBS :: Response -> BS.ByteString
msgBS = statusMessage . responseStatus
| null | https://raw.githubusercontent.com/fragnix/fragnix/b9969e9c6366e2917a782f3ac4e77cce0835448b/tests/packages/scotty/Network.Wai.Middleware.RequestLogger.hs | haskell | # LANGUAGE Haskell2010, OverloadedStrings #
NOTE: Due to , this module should
* Basic stdout logging
* Create more versions
^ use colors?
| @RequestLoggerSettings@ is an instance of Default. See <-default Data.Default> for more information.
@outputFormat@, @autoFlush@, and @destination@ are record fields
modify settings values using record syntax.
| Default value: @Detailed@ @True@.
| Only applies when using the @Handle@ constructor for @destination@.
| Default: @Handle@ @stdout@.
We use Nothing for the response size since we generally don't know it
We use Nothing for the response size since we generally don't know it
| Production request logger middleware.
| Development request logger middleware.
This uses the 'Detailed' 'True' logging format and logs to 'stdout'.
| Prints a message using the given callback function for each request.
This is not for serious production use- it is inefficient.
It immediately consumes a POST body and fills it back in and is otherwise inefficient
Note that it logs the request immediately when it is received.
This meanst that you can accurately see the interleaving of requests.
And if the app crashes you have still logged the request.
Example ouput:
> GET search
>
> GET static/css/normalize.css
> Accept: text/css,*/*;q=0.1
| Tags http method with a unique color.
logging the body here consumes it, so fill it back up
obviously not efficient, but this is the development logger
that meant that you could read the request body in twice.
While that in itself is not a problem, the issue is that,
in production, you wouldn't be able to do this, and
therefore some bugs wouldn't show up during testing. This
implementation ensures that each chunk is only returned
once.
log the request body if it is small
log the status of the response | # LINE 1 " Network / Wai / Middleware / RequestLogger.hs " #
# LANGUAGE RecordWildCards #
not use CPP .
module Network.Wai.Middleware.RequestLogger
logStdout
, logStdoutDev
, mkRequestLogger
, RequestLoggerSettings
, outputFormat
, autoFlush
, destination
, OutputFormat (..)
, OutputFormatter
, OutputFormatterWithDetails
, Destination (..)
, Callback
, IPAddrSource (..)
) where
import System.IO (Handle, hFlush, stdout)
import qualified Blaze.ByteString.Builder as B
import qualified Data.ByteString as BS
import Data.ByteString.Char8 (pack, unpack)
import Control.Monad (when)
import Control.Monad.IO.Class (liftIO)
import Network.Wai
( Request(..), requestBodyLength, RequestBodyLength(..)
, Middleware
, Response, responseStatus, responseHeaders
)
import System.Log.FastLogger
import Network.HTTP.Types as H
import Data.Maybe (fromMaybe)
import Data.Monoid (mconcat, (<>))
import Data.Time (getCurrentTime, diffUTCTime, NominalDiffTime)
import Network.Wai.Parse (sinkRequestBody, lbsBackEnd, fileName, Param, File
, getRequestBodyType)
import qualified Data.ByteString.Lazy as LBS
import qualified Data.ByteString.Char8 as S8
import System.Console.ANSI
import Data.IORef.Lifted
import System.IO.Unsafe
import Network.Wai.Internal (Response (..))
import Data.Default.Class (Default (def))
import Network.Wai.Logger
import Network.Wai.Middleware.RequestLogger.Internal
import Network.Wai.Header (contentLength)
import Data.Text.Encoding (decodeUtf8')
data OutputFormat = Apache IPAddrSource
| CustomOutputFormat OutputFormatter
| CustomOutputFormatWithDetails OutputFormatterWithDetails
type OutputFormatter = ZonedDate -> Request -> Status -> Maybe Integer -> LogStr
type OutputFormatterWithDetails =
ZonedDate -> Request -> Status -> Maybe Integer -> NominalDiffTime -> [S8.ByteString] -> B.Builder -> LogStr
data Destination = Handle Handle
| Logger LoggerSet
| Callback Callback
type Callback = LogStr -> IO ()
for the record type @RequestLoggerSettings@ , so they can be used to
data RequestLoggerSettings = RequestLoggerSettings
{
outputFormat :: OutputFormat
Default value :
, autoFlush :: Bool
, destination :: Destination
}
instance Default RequestLoggerSettings where
def = RequestLoggerSettings
{ outputFormat = Detailed True
, autoFlush = True
, destination = Handle stdout
}
mkRequestLogger :: RequestLoggerSettings -> IO Middleware
mkRequestLogger RequestLoggerSettings{..} = do
let (callback, flusher) =
case destination of
Handle h -> (BS.hPutStr h . logToByteString, when autoFlush (hFlush h))
Logger l -> (pushLogStr l, when autoFlush (flushLogStr l))
Callback c -> (c, return ())
callbackAndFlush str = callback str >> flusher
case outputFormat of
Apache ipsrc -> do
getdate <- getDateGetter flusher
apache <- initLogger ipsrc (LogCallback callback flusher) getdate
return $ apacheMiddleware apache
Detailed useColors -> detailedMiddleware callbackAndFlush useColors
CustomOutputFormat formatter -> do
getDate <- getDateGetter flusher
return $ customMiddleware callbackAndFlush getDate formatter
CustomOutputFormatWithDetails formatter -> do
getdate <- getDateGetter flusher
return $ customMiddlewareWithDetails callbackAndFlush getdate formatter
apacheMiddleware :: ApacheLoggerActions -> Middleware
apacheMiddleware ala app req sendResponse = app req $ \res -> do
let msize = contentLength (responseHeaders res)
apacheLogger ala req (responseStatus res) msize
sendResponse res
customMiddleware :: Callback -> IO ZonedDate -> OutputFormatter -> Middleware
customMiddleware cb getdate formatter app req sendResponse = app req $ \res -> do
date <- liftIO getdate
liftIO $ cb $ formatter date req (responseStatus res) Nothing
sendResponse res
customMiddlewareWithDetails :: Callback -> IO ZonedDate -> OutputFormatterWithDetails -> Middleware
customMiddlewareWithDetails cb getdate formatter app req sendResponse = do
(req', reqBody) <- getRequestBody req
t0 <- getCurrentTime
app req' $ \res -> do
t1 <- getCurrentTime
date <- liftIO getdate
builderIO <- newIORef $ B.fromByteString ""
res' <- recordChunks builderIO res
rspRcv <- sendResponse res'
_ <- liftIO . cb .
formatter date req' (responseStatus res') Nothing (t1 `diffUTCTime` t0) reqBody =<<
readIORef builderIO
return rspRcv
This uses the ' Apache ' logging format , and takes IP addresses for clients from
the socket ( see ' IPAddrSource ' for more information ) . It logs to ' stdout ' .
# NOINLINE logStdout #
logStdout :: Middleware
logStdout = unsafePerformIO $ mkRequestLogger def { outputFormat = Apache FromSocket }
# NOINLINE logStdoutDev #
logStdoutDev :: Middleware
logStdoutDev = unsafePerformIO $ mkRequestLogger def
However , if you are simulating 10 simultaneous users you may find this confusing .
This is lower - level - use ' ' unless you need greater control .
> Accept : text / html , application / xhtml+xml , application / xml;q=0.9,*/*;q=0.8
> Status : 200 OK 0.010555s
> Params : [ ( " LXwioiBG " , " " ) ]
> Status : 304 Not Modified 0.010555s
detailedMiddleware :: Callback -> Bool -> IO Middleware
detailedMiddleware cb useColors =
let (ansiColor, ansiMethod, ansiStatusCode) =
if useColors
then (ansiColor', ansiMethod', ansiStatusCode')
else (\_ t -> [t], (:[]), \_ t -> [t])
in return $ detailedMiddleware' cb ansiColor ansiMethod ansiStatusCode
ansiColor' :: Color -> BS.ByteString -> [BS.ByteString]
ansiColor' color bs =
[ pack $ setSGRCode [SetColor Foreground Dull color]
, bs
, pack $ setSGRCode [Reset]
]
ansiMethod' :: BS.ByteString -> [BS.ByteString]
ansiMethod' m = case m of
"GET" -> ansiColor' Cyan m
"HEAD" -> ansiColor' Cyan m
"PUT" -> ansiColor' Green m
"POST" -> ansiColor' Yellow m
"DELETE" -> ansiColor' Red m
_ -> ansiColor' Magenta m
ansiStatusCode' :: BS.ByteString -> BS.ByteString -> [BS.ByteString]
ansiStatusCode' c t = case S8.take 1 c of
"2" -> ansiColor' Green t
"3" -> ansiColor' Yellow t
"4" -> ansiColor' Red t
"5" -> ansiColor' Magenta t
_ -> ansiColor' Blue t
recordChunks :: IORef B.Builder -> Response -> IO Response
recordChunks i (ResponseStream s h sb) =
return . ResponseStream s h $ (\send flush -> sb (\b -> modifyIORef i (<> b) >> send b) flush)
recordChunks i (ResponseBuilder s h b) =
modifyIORef i (<> b) >> (return $ ResponseBuilder s h b)
recordChunks _ r =
return r
getRequestBody :: Request -> IO (Request, [S8.ByteString])
getRequestBody req = do
let loop front = do
bs <- requestBody req
if S8.null bs
then return $ front []
else loop $ front . (bs:)
body <- loop id
Note : previously , we simply used CL.sourceList . However ,
ichunks <- newIORef body
let rbody = atomicModifyIORef ichunks $ \chunks ->
case chunks of
[] -> ([], S8.empty)
x:y -> (y, x)
let req' = req { requestBody = rbody }
return (req', body)
detailedMiddleware' :: Callback
-> (Color -> BS.ByteString -> [BS.ByteString])
-> (BS.ByteString -> [BS.ByteString])
-> (BS.ByteString -> BS.ByteString -> [BS.ByteString])
-> Middleware
detailedMiddleware' cb ansiColor ansiMethod ansiStatusCode app req sendResponse = do
(req', body) <-
second tuple item should not be necessary , but a test runner might mess it up
case (requestBodyLength req, contentLength (requestHeaders req)) of
(KnownLength len, _) | len <= 2048 -> getRequestBody req
(_, Just len) | len <= 2048 -> getRequestBody req
_ -> return (req, [])
let reqbodylog _ = if null body then [""] else ansiColor White " Request Body: " <> body <> ["\n"]
reqbody = concatMap (either (const [""]) reqbodylog . decodeUtf8') body
postParams <- if requestMethod req `elem` ["GET", "HEAD"]
then return []
else do postParams <- liftIO $ allPostParams body
return $ collectPostParams postParams
let getParams = map emptyGetParam $ queryString req
accept = fromMaybe "" $ lookup H.hAccept $ requestHeaders req
params = let par | not $ null postParams = [pack (show postParams)]
| not $ null getParams = [pack (show getParams)]
| otherwise = []
in if null par then [""] else ansiColor White " Params: " <> par <> ["\n"]
t0 <- getCurrentTime
app req' $ \rsp -> do
let isRaw =
case rsp of
ResponseRaw{} -> True
_ -> False
stCode = statusBS rsp
stMsg = msgBS rsp
t1 <- getCurrentTime
cb $ mconcat $ map toLogStr $
ansiMethod (requestMethod req) ++ [" ", rawPathInfo req, "\n"] ++
params ++ reqbody ++
ansiColor White " Accept: " ++ [accept, "\n"] ++
if isRaw then [] else
ansiColor White " Status: " ++
ansiStatusCode stCode (stCode <> " " <> stMsg) ++
[" ", pack $ show $ diffUTCTime t1 t0, "\n"]
sendResponse rsp
where
allPostParams body =
case getRequestBodyType req of
Nothing -> return ([], [])
Just rbt -> do
ichunks <- newIORef body
let rbody = atomicModifyIORef ichunks $ \chunks ->
case chunks of
[] -> ([], S8.empty)
x:y -> (y, x)
sinkRequestBody lbsBackEnd rbt rbody
emptyGetParam :: (BS.ByteString, Maybe BS.ByteString) -> (BS.ByteString, BS.ByteString)
emptyGetParam (k, Just v) = (k,v)
emptyGetParam (k, Nothing) = (k,"")
collectPostParams :: ([Param], [File LBS.ByteString]) -> [Param]
collectPostParams (postParams, files) = postParams ++
map (\(k,v) -> (k, "FILE: " <> fileName v)) files
statusBS :: Response -> BS.ByteString
statusBS = pack . show . statusCode . responseStatus
msgBS :: Response -> BS.ByteString
msgBS = statusMessage . responseStatus
|
6bf792b9a510556e81f26519763bf3501c106cd726341fc979899755a38449c6 | Simre1/haskell-game | Final.hs | # LANGUAGE TemplateHaskell #
module Polysemy.Final
(
-- * Effect
Final(..)
, ThroughWeavingToFinal
-- * Actions
, withWeavingToFinal
, withStrategicToFinal
, embedFinal
-- * Combinators for Interpreting to the Final Monad
, interpretFinal
-- * Strategy
-- | Strategy is a domain-specific language very similar to @Tactics@
( see ' Polysemy . Tactical ' ) , and is used to describe how higher - order
-- effects are threaded down to the final monad.
--
-- Much like @Tactics@, computations can be run and threaded
through the use of ' runS ' and ' bindS ' , and first - order constructors
-- may use 'pureS'. In addition, 'liftS' may be used to
-- lift actions of the final monad.
--
-- Unlike @Tactics@, the final return value within a 'Strategic'
-- must be a monadic value of the target monad
-- with the functorial state wrapped inside of it.
, Strategic
, WithStrategy
, pureS
, liftS
, runS
, bindS
, getInspectorS
, getInitialStateS
-- * Interpretations
, runFinal
, finalToFinal
-- * Interpretations for Other Effects
, embedToFinal
) where
import Polysemy.Internal
import Polysemy.Internal.Combinators
import Polysemy.Internal.Union
import Polysemy.Internal.Strategy
import Polysemy.Internal.TH.Effect
-----------------------------------------------------------------------------
-- | This represents a function which produces
-- an action of the final monad @m@ given:
--
-- * The initial effectful state at the moment the action
-- is to be executed.
--
* A way to convert @z@ ( which is typically @'Sem ' r@ ) to @m@ by
-- threading the effectful state through.
--
-- * An inspector that is able to view some value within the
-- effectful state if the effectful state contains any values.
--
A @'Polysemy . Internal . Union . Weaving'@ provides these components ,
-- hence the name 'ThroughWeavingToFinal'.
--
@since 1.2.0.0
type ThroughWeavingToFinal m z a =
forall f
. Functor f
=> f ()
-> (forall x. f (z x) -> m (f x))
-> (forall x. f x -> Maybe x)
-> m (f a)
-----------------------------------------------------------------------------
-- | An effect for embedding higher-order actions in the final target monad
-- of the effect stack.
--
-- This is very useful for writing interpreters that interpret higher-order
-- effects in terms of the final monad.
--
-- 'Final' is more powerful than 'Embed', but is also less flexible
to interpret ( compare ' Polysemy . ' with ' finalToFinal ' ) .
-- If you only need the power of 'embed', then you should use 'Embed' instead.
--
-- /Beware/: 'Final' actions are interpreted as actions of the final monad,
-- and the effectful state visible to
-- 'withWeavingToFinal' \/ 'withStrategicToFinal'
\/ ' interpretFinal '
-- is that of /all interpreters run in order to produce the final monad/.
--
This means that any interpreter built using ' Final ' will /not/
-- respect local/global state semantics based on the order of
-- interpreters run. You should signal interpreters that make use of
-- 'Final' by adding a @-'Final'@ suffix to the names of these.
--
State semantics of effects that are /not/
-- interpreted in terms of the final monad will always
-- appear local to effects that are interpreted in terms of the final monad.
--
State semantics between effects that are interpreted in terms of the final monad
-- depend on the final monad. For example, if the final monad is a monad transformer
-- stack, then state semantics will depend on the order monad transformers are stacked.
--
@since 1.2.0.0
newtype Final m z a where
WithWeavingToFinal
:: ThroughWeavingToFinal m z a
-> Final m z a
makeSem_ ''Final
-----------------------------------------------------------------------------
-- | Allows for embedding higher-order actions of the final monad
by providing the means of explicitly threading effects through @'Sem ' r@
-- to the final monad.
--
-- Consider using 'withStrategicToFinal' instead,
-- which provides a more user-friendly interface, but is also slightly weaker.
--
-- You are discouraged from using 'withWeavingToFinal' directly
-- in application code, as it ties your application code directly to
-- the final monad.
--
@since 1.2.0.0
withWeavingToFinal
:: forall m r a
. Member (Final m) r
=> ThroughWeavingToFinal m (Sem r) a
-> Sem r a
-----------------------------------------------------------------------------
-- | 'withWeavingToFinal' admits an implementation of 'embed'.
--
-- Just like 'embed', you are discouraged from using this in application code.
--
@since 1.2.0.0
embedFinal :: (Member (Final m) r, Functor m) => m a -> Sem r a
embedFinal m = withWeavingToFinal $ \s _ _ -> (<$ s) <$> m
# INLINE embedFinal #
-----------------------------------------------------------------------------
-- | Allows for embedding higher-order actions of the final monad
by providing the means of explicitly threading effects through @'Sem ' r@
-- to the final monad. This is done through the use of the 'Strategic'
-- environment, which provides 'runS' and 'bindS'.
--
-- You are discouraged from using 'withStrategicToFinal' in application code,
-- as it ties your application code directly to the final monad.
--
@since 1.2.0.0
withStrategicToFinal :: Member (Final m) r
=> Strategic m (Sem r) a
-> Sem r a
withStrategicToFinal strat = withWeavingToFinal (runStrategy strat)
# INLINE withStrategicToFinal #
------------------------------------------------------------------------------
-- | Like 'interpretH', but may be used to
-- interpret higher-order effects in terms of the final monad.
--
-- 'interpretFinal' requires less boilerplate than using 'interpretH'
-- together with 'withStrategicToFinal' \/ 'withWeavingToFinal',
-- but is also less powerful.
-- 'interpretFinal' does not provide any means of executing actions
of @'Sem ' r@ as you interpret each action , and the provided interpreter
-- is automatically recursively used to process higher-order occurences of
@'Sem ' ( e ' : to @'Sem ' r@.
--
-- If you need greater control of how the effect is interpreted,
use ' interpretH ' together with ' withStrategicToFinal ' \/
-- 'withWeavingToFinal' instead.
--
-- /Beware/: Effects that aren't interpreted in terms of the final
-- monad will have local state semantics in regards to effects
-- interpreted using 'interpretFinal'. See 'Final'.
--
@since 1.2.0.0
interpretFinal
:: forall m e r a
. Member (Final m) r
=> (forall x n. e n x -> Strategic m n x)
-- ^ A natural transformation from the handled effect to the final monad.
-> Sem (e ': r) a
-> Sem r a
interpretFinal n =
let
go :: Sem (e ': r) x -> Sem r x
go = hoistSem $ \u -> case decomp u of
Right (Weaving e s wv ex ins) ->
injWeaving $
Weaving
(WithWeavingToFinal (runStrategy (n e)))
s
(go . wv)
ex
ins
Left g -> hoist go g
# INLINE go #
in
go
# INLINE interpretFinal #
------------------------------------------------------------------------------
| Lower a ' Sem ' containing only a single lifted , final ' Monad ' into that
-- monad.
--
-- If you also need to process an @'Embed' m@ effect, use this together with
-- 'embedToFinal'.
--
@since 1.2.0.0
runFinal :: Monad m => Sem '[Final m] a -> m a
runFinal = usingSem $ \u -> case extract u of
Weaving (WithWeavingToFinal wav) s wv ex ins ->
ex <$> wav s (runFinal . wv) ins
# INLINE runFinal #
------------------------------------------------------------------------------
| Given natural transformations between @m1@ and @m2@ , run a @'Final ' m1@
-- effect by transforming it into a @'Final' m2@ effect.
--
@since 1.2.0.0
finalToFinal :: forall m1 m2 r a
. Member (Final m2) r
=> (forall x. m1 x -> m2 x)
-> (forall x. m2 x -> m1 x)
-> Sem (Final m1 ': r) a
-> Sem r a
finalToFinal to from =
let
go :: Sem (Final m1 ': r) x -> Sem r x
go = hoistSem $ \u -> case decomp u of
Right (Weaving (WithWeavingToFinal wav) s wv ex ins) ->
injWeaving $
Weaving
(WithWeavingToFinal $ \s' wv' ins' ->
to $ wav s' (from . wv') ins'
)
s
(go . wv)
ex
ins
Left g -> hoist go g
# INLINE go #
in
go
# INLINE finalToFinal #
------------------------------------------------------------------------------
-- | Transform an @'Embed' m@ effect into a @'Final' m@ effect
--
@since 1.2.0.0
embedToFinal :: (Member (Final m) r, Functor m)
=> Sem (Embed m ': r) a
-> Sem r a
embedToFinal = interpret $ \(Embed m) -> embedFinal m
# INLINE embedToFinal #
| null | https://raw.githubusercontent.com/Simre1/haskell-game/272a0674157aedc7b0e0ee00da8d3a464903dc67/polysemy/src/Polysemy/Final.hs | haskell | * Effect
* Actions
* Combinators for Interpreting to the Final Monad
* Strategy
| Strategy is a domain-specific language very similar to @Tactics@
effects are threaded down to the final monad.
Much like @Tactics@, computations can be run and threaded
may use 'pureS'. In addition, 'liftS' may be used to
lift actions of the final monad.
Unlike @Tactics@, the final return value within a 'Strategic'
must be a monadic value of the target monad
with the functorial state wrapped inside of it.
* Interpretations
* Interpretations for Other Effects
---------------------------------------------------------------------------
| This represents a function which produces
an action of the final monad @m@ given:
* The initial effectful state at the moment the action
is to be executed.
threading the effectful state through.
* An inspector that is able to view some value within the
effectful state if the effectful state contains any values.
hence the name 'ThroughWeavingToFinal'.
---------------------------------------------------------------------------
| An effect for embedding higher-order actions in the final target monad
of the effect stack.
This is very useful for writing interpreters that interpret higher-order
effects in terms of the final monad.
'Final' is more powerful than 'Embed', but is also less flexible
If you only need the power of 'embed', then you should use 'Embed' instead.
/Beware/: 'Final' actions are interpreted as actions of the final monad,
and the effectful state visible to
'withWeavingToFinal' \/ 'withStrategicToFinal'
is that of /all interpreters run in order to produce the final monad/.
respect local/global state semantics based on the order of
interpreters run. You should signal interpreters that make use of
'Final' by adding a @-'Final'@ suffix to the names of these.
interpreted in terms of the final monad will always
appear local to effects that are interpreted in terms of the final monad.
depend on the final monad. For example, if the final monad is a monad transformer
stack, then state semantics will depend on the order monad transformers are stacked.
---------------------------------------------------------------------------
| Allows for embedding higher-order actions of the final monad
to the final monad.
Consider using 'withStrategicToFinal' instead,
which provides a more user-friendly interface, but is also slightly weaker.
You are discouraged from using 'withWeavingToFinal' directly
in application code, as it ties your application code directly to
the final monad.
---------------------------------------------------------------------------
| 'withWeavingToFinal' admits an implementation of 'embed'.
Just like 'embed', you are discouraged from using this in application code.
---------------------------------------------------------------------------
| Allows for embedding higher-order actions of the final monad
to the final monad. This is done through the use of the 'Strategic'
environment, which provides 'runS' and 'bindS'.
You are discouraged from using 'withStrategicToFinal' in application code,
as it ties your application code directly to the final monad.
----------------------------------------------------------------------------
| Like 'interpretH', but may be used to
interpret higher-order effects in terms of the final monad.
'interpretFinal' requires less boilerplate than using 'interpretH'
together with 'withStrategicToFinal' \/ 'withWeavingToFinal',
but is also less powerful.
'interpretFinal' does not provide any means of executing actions
is automatically recursively used to process higher-order occurences of
If you need greater control of how the effect is interpreted,
'withWeavingToFinal' instead.
/Beware/: Effects that aren't interpreted in terms of the final
monad will have local state semantics in regards to effects
interpreted using 'interpretFinal'. See 'Final'.
^ A natural transformation from the handled effect to the final monad.
----------------------------------------------------------------------------
monad.
If you also need to process an @'Embed' m@ effect, use this together with
'embedToFinal'.
----------------------------------------------------------------------------
effect by transforming it into a @'Final' m2@ effect.
----------------------------------------------------------------------------
| Transform an @'Embed' m@ effect into a @'Final' m@ effect
| # LANGUAGE TemplateHaskell #
module Polysemy.Final
(
Final(..)
, ThroughWeavingToFinal
, withWeavingToFinal
, withStrategicToFinal
, embedFinal
, interpretFinal
( see ' Polysemy . Tactical ' ) , and is used to describe how higher - order
through the use of ' runS ' and ' bindS ' , and first - order constructors
, Strategic
, WithStrategy
, pureS
, liftS
, runS
, bindS
, getInspectorS
, getInitialStateS
, runFinal
, finalToFinal
, embedToFinal
) where
import Polysemy.Internal
import Polysemy.Internal.Combinators
import Polysemy.Internal.Union
import Polysemy.Internal.Strategy
import Polysemy.Internal.TH.Effect
* A way to convert @z@ ( which is typically @'Sem ' r@ ) to @m@ by
A @'Polysemy . Internal . Union . Weaving'@ provides these components ,
@since 1.2.0.0
type ThroughWeavingToFinal m z a =
forall f
. Functor f
=> f ()
-> (forall x. f (z x) -> m (f x))
-> (forall x. f x -> Maybe x)
-> m (f a)
to interpret ( compare ' Polysemy . ' with ' finalToFinal ' ) .
\/ ' interpretFinal '
This means that any interpreter built using ' Final ' will /not/
State semantics of effects that are /not/
State semantics between effects that are interpreted in terms of the final monad
@since 1.2.0.0
newtype Final m z a where
WithWeavingToFinal
:: ThroughWeavingToFinal m z a
-> Final m z a
makeSem_ ''Final
by providing the means of explicitly threading effects through @'Sem ' r@
@since 1.2.0.0
withWeavingToFinal
:: forall m r a
. Member (Final m) r
=> ThroughWeavingToFinal m (Sem r) a
-> Sem r a
@since 1.2.0.0
embedFinal :: (Member (Final m) r, Functor m) => m a -> Sem r a
embedFinal m = withWeavingToFinal $ \s _ _ -> (<$ s) <$> m
# INLINE embedFinal #
by providing the means of explicitly threading effects through @'Sem ' r@
@since 1.2.0.0
withStrategicToFinal :: Member (Final m) r
=> Strategic m (Sem r) a
-> Sem r a
withStrategicToFinal strat = withWeavingToFinal (runStrategy strat)
# INLINE withStrategicToFinal #
of @'Sem ' r@ as you interpret each action , and the provided interpreter
@'Sem ' ( e ' : to @'Sem ' r@.
use ' interpretH ' together with ' withStrategicToFinal ' \/
@since 1.2.0.0
interpretFinal
:: forall m e r a
. Member (Final m) r
=> (forall x n. e n x -> Strategic m n x)
-> Sem (e ': r) a
-> Sem r a
interpretFinal n =
let
go :: Sem (e ': r) x -> Sem r x
go = hoistSem $ \u -> case decomp u of
Right (Weaving e s wv ex ins) ->
injWeaving $
Weaving
(WithWeavingToFinal (runStrategy (n e)))
s
(go . wv)
ex
ins
Left g -> hoist go g
# INLINE go #
in
go
# INLINE interpretFinal #
| Lower a ' Sem ' containing only a single lifted , final ' Monad ' into that
@since 1.2.0.0
runFinal :: Monad m => Sem '[Final m] a -> m a
runFinal = usingSem $ \u -> case extract u of
Weaving (WithWeavingToFinal wav) s wv ex ins ->
ex <$> wav s (runFinal . wv) ins
# INLINE runFinal #
| Given natural transformations between @m1@ and @m2@ , run a @'Final ' m1@
@since 1.2.0.0
finalToFinal :: forall m1 m2 r a
. Member (Final m2) r
=> (forall x. m1 x -> m2 x)
-> (forall x. m2 x -> m1 x)
-> Sem (Final m1 ': r) a
-> Sem r a
finalToFinal to from =
let
go :: Sem (Final m1 ': r) x -> Sem r x
go = hoistSem $ \u -> case decomp u of
Right (Weaving (WithWeavingToFinal wav) s wv ex ins) ->
injWeaving $
Weaving
(WithWeavingToFinal $ \s' wv' ins' ->
to $ wav s' (from . wv') ins'
)
s
(go . wv)
ex
ins
Left g -> hoist go g
# INLINE go #
in
go
# INLINE finalToFinal #
@since 1.2.0.0
embedToFinal :: (Member (Final m) r, Functor m)
=> Sem (Embed m ': r) a
-> Sem r a
embedToFinal = interpret $ \(Embed m) -> embedFinal m
# INLINE embedToFinal #
|
1b8fbafac595fc498c345cbb56c2bbf71da5f9b91f4adeae6a2717c6e1ec8bdb | mitchellwrosen/repld | Main.hs | module Main where
import qualified Repld.Main
main :: IO ()
main =
Repld.Main.repld
| null | https://raw.githubusercontent.com/mitchellwrosen/repld/100bd424e1b0320b5246647abeec3e60582ec39c/app/repld/Main.hs | haskell | module Main where
import qualified Repld.Main
main :: IO ()
main =
Repld.Main.repld
| |
8bebfb08462f695135c0fd27c1f20f15572d262da8bdd3eed8dc5d4766391b90 | S8A/htdp-exercises | ex389.rkt | The first three lines of this file were inserted by . They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname ex389) (read-case-sensitive #t) (teachpacks ((lib "batch-io.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "batch-io.rkt" "teachpack" "2htdp")) #f)))
(define-struct phone-record [name number])
A PhoneRecord is a structure :
( make - phone - record String String )
[ List - of String ] [ List - of String ] - > [ List - of PhoneRecord ]
Combines two equally long lists , of names and phone numbers respectively .
; Assumes that the corresponding list items belong to the same person.
(define (zip names phones)
(cond
[(empty? names) '()]
[(cons? names)
(cons (make-phone-record (first names) (first phones))
(zip (rest names) (rest phones)))]))
(check-expect (zip '() '()) '())
(check-expect (zip '("Amber" "Bob" "Carol" "Dave")
'("04141623701" "04167623782" "04122276523" "04143284334"))
(list (make-phone-record "Amber" "04141623701")
(make-phone-record "Bob" "04167623782")
(make-phone-record "Carol" "04122276523")
(make-phone-record "Dave" "04143284334")))
| null | https://raw.githubusercontent.com/S8A/htdp-exercises/578e49834a9513f29ef81b7589b28081c5e0b69f/ex389.rkt | racket | about the language level of this file in a form that our tools can easily process.
Assumes that the corresponding list items belong to the same person. | The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname ex389) (read-case-sensitive #t) (teachpacks ((lib "batch-io.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "batch-io.rkt" "teachpack" "2htdp")) #f)))
(define-struct phone-record [name number])
A PhoneRecord is a structure :
( make - phone - record String String )
[ List - of String ] [ List - of String ] - > [ List - of PhoneRecord ]
Combines two equally long lists , of names and phone numbers respectively .
(define (zip names phones)
(cond
[(empty? names) '()]
[(cons? names)
(cons (make-phone-record (first names) (first phones))
(zip (rest names) (rest phones)))]))
(check-expect (zip '() '()) '())
(check-expect (zip '("Amber" "Bob" "Carol" "Dave")
'("04141623701" "04167623782" "04122276523" "04143284334"))
(list (make-phone-record "Amber" "04141623701")
(make-phone-record "Bob" "04167623782")
(make-phone-record "Carol" "04122276523")
(make-phone-record "Dave" "04143284334")))
|
1bb848d36ccfc9d2f3e2d679905c601b9d19be117f60d904e7527d8da3a45e04 | fluree/db | template.cljc | (ns fluree.db.query.sql.template
(:require [clojure.string :as str]
[clojure.walk :refer [postwalk]]))
#?(:clj (set! *warn-on-reflection* true))
(defn capitalize-first
"Capitalizes the first letter (and only the first letter) of `s`"
[s]
(if (<= (count s) 1)
(str/upper-case s)
(-> (subs s 0 1)
str/upper-case
(str (subs s 1)))))
(defn combine-str
"Combines `s1` and `s2` by concatenating `s1` with the result of capitalizing
the first character of `s2`"
[s1 s2]
(->> s2
capitalize-first
(str s1)))
(defn normalize
"Formats `s` by removing any '/' and capitalizing the following character for
each '/' removed"
[s]
(reduce combine-str (str/split s #"/")))
(defn build-var
"Formats `s` as a var by prepending '?', filtering out '/', and lowerCamelCasing
the remaining string"
[s]
(->> s
normalize
(str "?")))
(defn build-predicate
"Formats the collection string `c` and the field string `f` by joining them
with a '/'"
[c f]
(str c "/" f))
(defn predicate?
"Returns true if `s` is a predicate string"
[s]
(and s
(str/includes? s "/")))
(defn build-fn-call
"Formats `terms` as a function call"
([fst sec]
(build-fn-call [fst sec]))
([terms]
(str "(" (str/join " " terms) ")")))
(defn template-for
[kw]
(str "@<" kw ">"))
(defn fill-in
[tmpl-str tmpl v]
(str/replace tmpl-str tmpl v))
(def collection
"Template for representing flake collections"
(template-for :collection))
(def collection-var
"Template for storing flake subjects as variables"
(build-var collection))
(defn fill-in-collection
"Fills in the known collection name `coll-name` wherever the collection template
appears in `tmpl-str`"
[coll-name tmpl-data]
(postwalk (fn [c]
(if (string? c)
(fill-in c collection coll-name)
c))
tmpl-data))
(def field
"Template for represent collection fields"
(template-for :field))
(def field-var
"Template for storing flake fields as variables"
(build-var field))
(defn field->predicate-template
"Build a flake predicate template string from the collection template and the
known field value `f`"
[f]
(build-predicate collection f))
(def predicate
"Template for representing flake predicates with both collection and field
missing"
(build-predicate collection field))
| null | https://raw.githubusercontent.com/fluree/db/70c49dfc3898945d3ab9a64beb798c1f1b2382e4/src/fluree/db/query/sql/template.cljc | clojure | (ns fluree.db.query.sql.template
(:require [clojure.string :as str]
[clojure.walk :refer [postwalk]]))
#?(:clj (set! *warn-on-reflection* true))
(defn capitalize-first
"Capitalizes the first letter (and only the first letter) of `s`"
[s]
(if (<= (count s) 1)
(str/upper-case s)
(-> (subs s 0 1)
str/upper-case
(str (subs s 1)))))
(defn combine-str
"Combines `s1` and `s2` by concatenating `s1` with the result of capitalizing
the first character of `s2`"
[s1 s2]
(->> s2
capitalize-first
(str s1)))
(defn normalize
"Formats `s` by removing any '/' and capitalizing the following character for
each '/' removed"
[s]
(reduce combine-str (str/split s #"/")))
(defn build-var
"Formats `s` as a var by prepending '?', filtering out '/', and lowerCamelCasing
the remaining string"
[s]
(->> s
normalize
(str "?")))
(defn build-predicate
"Formats the collection string `c` and the field string `f` by joining them
with a '/'"
[c f]
(str c "/" f))
(defn predicate?
"Returns true if `s` is a predicate string"
[s]
(and s
(str/includes? s "/")))
(defn build-fn-call
"Formats `terms` as a function call"
([fst sec]
(build-fn-call [fst sec]))
([terms]
(str "(" (str/join " " terms) ")")))
(defn template-for
[kw]
(str "@<" kw ">"))
(defn fill-in
[tmpl-str tmpl v]
(str/replace tmpl-str tmpl v))
(def collection
"Template for representing flake collections"
(template-for :collection))
(def collection-var
"Template for storing flake subjects as variables"
(build-var collection))
(defn fill-in-collection
"Fills in the known collection name `coll-name` wherever the collection template
appears in `tmpl-str`"
[coll-name tmpl-data]
(postwalk (fn [c]
(if (string? c)
(fill-in c collection coll-name)
c))
tmpl-data))
(def field
"Template for represent collection fields"
(template-for :field))
(def field-var
"Template for storing flake fields as variables"
(build-var field))
(defn field->predicate-template
"Build a flake predicate template string from the collection template and the
known field value `f`"
[f]
(build-predicate collection f))
(def predicate
"Template for representing flake predicates with both collection and field
missing"
(build-predicate collection field))
| |
48cb2358e021d792b2d883e7f924526fa1825bdf5440d055ba24a904484de1f5 | clojure-emacs/refactor-nrepl | fs_test.clj | (ns refactor-nrepl.fs-test
(:require
[clojure.java.io :as io]
[clojure.test :refer [deftest is]])
(:import
(java.io File)))
(require '[refactor-nrepl.fs])
(deftest extensions-are-disabled
(is (try
(-> "project.clj" File. .toPath io/file)
false
(catch Exception e
(assert (-> e
.getMessage
#{"No implementation of method: :as-file of protocol: #'clojure.java.io/Coercions found for class: sun.nio.fs.UnixPath"}))
true))))
| null | https://raw.githubusercontent.com/clojure-emacs/refactor-nrepl/0e7d45d0dc10baf85c63298b309e06a0c696d854/test/refactor_nrepl/fs_test.clj | clojure | (ns refactor-nrepl.fs-test
(:require
[clojure.java.io :as io]
[clojure.test :refer [deftest is]])
(:import
(java.io File)))
(require '[refactor-nrepl.fs])
(deftest extensions-are-disabled
(is (try
(-> "project.clj" File. .toPath io/file)
false
(catch Exception e
(assert (-> e
.getMessage
#{"No implementation of method: :as-file of protocol: #'clojure.java.io/Coercions found for class: sun.nio.fs.UnixPath"}))
true))))
| |
85aa0eba04d2a0eafc1b51ed99482de75ec72d708bbb8ef629de66a37531e6f2 | Clozure/dpf | application.lisp | (in-package "CCL")
(defclass cocoa-ui-object (ui-object)
())
(defclass cocoa-application (application)
((standalone-p :initform nil :accessor cocoa-application-standalone-p)))
(defparameter *cocoa-application*
(make-instance 'cocoa-application
:ui-object (make-instance 'cocoa-ui-object)))
(defmethod application-error ((a cocoa-application) condition error-pointer)
(break-loop-handle-error condition error-pointer))
(defmethod parse-application-arguments ((a cocoa-application))
(values nil nil nil nil))
(defmethod toplevel-function ((a cocoa-application) init-file)
(declare (ignore init-file))
(setf (cocoa-application-standalone-p a) t)
(prepare-cocoa-application a)
(start-cocoa-application a))
(defmethod prepare-cocoa-application ((a cocoa-application))
(call-in-initial-process #'(lambda ()
(setq *nsapp* (load-cocoa-application a))
(initialize-user-interface a))))
(defun install-menus ()
(let* ((main-menu (make-instance ns:ns-menu :with-title #@"MainMenu"))
(item nil)
(app-menu (make-instance ns:ns-menu :with-title #@"Apple")))
(setq item (#/addItemWithTitle:action:keyEquivalent: app-menu
#@"Quit"
(objc:@selector
#/terminate:)
#@"q"))
(#/setTarget: item *nsapp*)
(setq item (#/addItemWithTitle:action:keyEquivalent: main-menu
#@"Apple" +null-ptr+
#@""))
(#/setSubmenu:forItem: main-menu app-menu item)
(#/setMainMenu: *nsapp* main-menu)
(#/release main-menu)
(#/release app-menu)))
(defmethod initialize-user-interface ((a cocoa-application))
(with-autorelease-pool
(let* ((bundle (#/mainBundle ns:ns-bundle))
(info (#/infoDictionary bundle))
(mainnibname (#/objectForKey: info #@"NSMainNibFile")))
(when (%null-ptr-p mainnibname)
(install-menus)))))
(defmethod load-cocoa-application ((a cocoa-application))
(with-autorelease-pool
(let* ((bundle (#/mainBundle ns:ns-bundle))
(info (#/infoDictionary bundle))
(classname (#/objectForKey: info #@"NSPrincipalClass"))
(mainnibname (#/objectForKey: info #@"NSMainNibFile"))
(progname (#/objectForKey: info #@"CFBundleName")))
(when (%null-ptr-p classname)
(setq classname #@"NSApplication"))
(unless (%null-ptr-p progname)
(#/setProcessName: (#/processInfo ns:ns-process-info) progname))
(let* ((appclass (#_NSClassFromString classname))
(app (#/sharedApplication appclass)))
(when (%null-ptr-p app)
(error "Could not create shared instance of ~s" (%get-cfstring
classname)))
(unless (%null-ptr-p mainnibname)
(#/loadNibNamed:owner: ns:ns-bundle mainnibname app))
app))))
(defun become-foreground-application ()
(rlet ((psn #>ProcessSerialNumber))
(#_GetCurrentProcess psn)
(#_TransformProcessType psn #$kProcessTransformToForegroundApplication)))
(defun event-loop ()
(loop
(with-simple-restart (abort "Process the next event")
(#/run *nsapp*))))
(defun run-event-loop ()
(%set-toplevel nil)
(assert (eq *current-process* *initial-process*))
(change-class *initial-process* 'cocoa-event-process)
(setf (process-name *initial-process*) "Cocoa event loop")
(with-process-whostate ("Active")
(event-loop)))
;; After the lisp starts up, it creates a listener thread. The
initial thead then goes to sleep , waking up about 3 times a second
;; to do some housekeeping tasks.
;;
Because most of Cocoa needs to run on the initial thread , we
;; interrupt the initial thread, and use %set-toplevel and toplevel
;; (which are basically process-preset and process-reset for the
initial process ) to make it start running the Cocoa event loop . We
;; create a new thread to do the housekeeping.
(defmethod start-cocoa-application ((a cocoa-application))
(flet ((startup ()
(with-standard-initial-bindings
(process-run-function "housekeeping" #'housekeeping-loop)
(become-foreground-application)
(run-event-loop))))
(process-interrupt *initial-process*
#'(lambda ()
(%set-toplevel #'startup)
(toplevel)))))
| null | https://raw.githubusercontent.com/Clozure/dpf/174ae4ed065b66329df34b8bc1ba28ae7f48c806/application.lisp | lisp | After the lisp starts up, it creates a listener thread. The
to do some housekeeping tasks.
interrupt the initial thread, and use %set-toplevel and toplevel
(which are basically process-preset and process-reset for the
create a new thread to do the housekeeping. | (in-package "CCL")
(defclass cocoa-ui-object (ui-object)
())
(defclass cocoa-application (application)
((standalone-p :initform nil :accessor cocoa-application-standalone-p)))
(defparameter *cocoa-application*
(make-instance 'cocoa-application
:ui-object (make-instance 'cocoa-ui-object)))
(defmethod application-error ((a cocoa-application) condition error-pointer)
(break-loop-handle-error condition error-pointer))
(defmethod parse-application-arguments ((a cocoa-application))
(values nil nil nil nil))
(defmethod toplevel-function ((a cocoa-application) init-file)
(declare (ignore init-file))
(setf (cocoa-application-standalone-p a) t)
(prepare-cocoa-application a)
(start-cocoa-application a))
(defmethod prepare-cocoa-application ((a cocoa-application))
(call-in-initial-process #'(lambda ()
(setq *nsapp* (load-cocoa-application a))
(initialize-user-interface a))))
(defun install-menus ()
(let* ((main-menu (make-instance ns:ns-menu :with-title #@"MainMenu"))
(item nil)
(app-menu (make-instance ns:ns-menu :with-title #@"Apple")))
(setq item (#/addItemWithTitle:action:keyEquivalent: app-menu
#@"Quit"
(objc:@selector
#/terminate:)
#@"q"))
(#/setTarget: item *nsapp*)
(setq item (#/addItemWithTitle:action:keyEquivalent: main-menu
#@"Apple" +null-ptr+
#@""))
(#/setSubmenu:forItem: main-menu app-menu item)
(#/setMainMenu: *nsapp* main-menu)
(#/release main-menu)
(#/release app-menu)))
(defmethod initialize-user-interface ((a cocoa-application))
(with-autorelease-pool
(let* ((bundle (#/mainBundle ns:ns-bundle))
(info (#/infoDictionary bundle))
(mainnibname (#/objectForKey: info #@"NSMainNibFile")))
(when (%null-ptr-p mainnibname)
(install-menus)))))
(defmethod load-cocoa-application ((a cocoa-application))
(with-autorelease-pool
(let* ((bundle (#/mainBundle ns:ns-bundle))
(info (#/infoDictionary bundle))
(classname (#/objectForKey: info #@"NSPrincipalClass"))
(mainnibname (#/objectForKey: info #@"NSMainNibFile"))
(progname (#/objectForKey: info #@"CFBundleName")))
(when (%null-ptr-p classname)
(setq classname #@"NSApplication"))
(unless (%null-ptr-p progname)
(#/setProcessName: (#/processInfo ns:ns-process-info) progname))
(let* ((appclass (#_NSClassFromString classname))
(app (#/sharedApplication appclass)))
(when (%null-ptr-p app)
(error "Could not create shared instance of ~s" (%get-cfstring
classname)))
(unless (%null-ptr-p mainnibname)
(#/loadNibNamed:owner: ns:ns-bundle mainnibname app))
app))))
(defun become-foreground-application ()
(rlet ((psn #>ProcessSerialNumber))
(#_GetCurrentProcess psn)
(#_TransformProcessType psn #$kProcessTransformToForegroundApplication)))
(defun event-loop ()
(loop
(with-simple-restart (abort "Process the next event")
(#/run *nsapp*))))
(defun run-event-loop ()
(%set-toplevel nil)
(assert (eq *current-process* *initial-process*))
(change-class *initial-process* 'cocoa-event-process)
(setf (process-name *initial-process*) "Cocoa event loop")
(with-process-whostate ("Active")
(event-loop)))
initial thead then goes to sleep , waking up about 3 times a second
Because most of Cocoa needs to run on the initial thread , we
initial process ) to make it start running the Cocoa event loop . We
(defmethod start-cocoa-application ((a cocoa-application))
(flet ((startup ()
(with-standard-initial-bindings
(process-run-function "housekeeping" #'housekeeping-loop)
(become-foreground-application)
(run-event-loop))))
(process-interrupt *initial-process*
#'(lambda ()
(%set-toplevel #'startup)
(toplevel)))))
|
c0707f92cf5c3e0fe61e375965bc2c0fed14ca68b995db06b487c04db7920ae7 | borgeby/jarl | comparison_test.cljc | (ns jarl.builtins.comparison-test
(:require [test.utils :refer [testing-builtin]]
#?(:clj [clojure.test :refer [deftest]]
:cljs [cljs.test :refer [deftest]])))
(deftest builtin-equal-test
(testing-builtin "equal"
; numbers
[1 1] true
[1 1.0] true
[-3.334 -3.3340000] true
[3.00000000000001 3] false
[3 "3"] false
; strings
["a" "a"] true
["a" "b"] false
["å" "å"] true
["🇸🇪" "🇸🇪"] true
["foo bar baz\t" "foo bar baz\t"] true
; objects
[{"foo" "bar"} {"foo" "bar"}] true
[{"foo" "bar"} {"foo" "bar" "bar" "baz"}] false
[{"foo" "bar" "bar" "baz"} {"bar" "baz" "foo" "bar"}] true
[{"foo" ["bar" 1]} {"foo" ["bar" 1]}] true
[{"foo" 1} {"foo" 1.0}] true
; arrays
[["foo" "bar"] ["foo" "bar"]] true
[["bar" "foo"] ["foo" "bar"]] false
[["fåäö" "båäör"] ["fåäö" "båäör"]] true
[["a" 1 [2] "b"] ["a" 1 [2] "b"]] true
; booleans
[true true] true
[false false] true
[true false] false
; null
[nil nil] true
[nil " "] false))
(deftest builtin-neq-test
(testing-builtin "neq"
[1 2] true
[1 1] false
[1 1.0] false
[-3.334 -3.3340000] false
; strings
["a" "a"] false
["a" "A"] true
["å" "å"] false
["🇸🇪" "🇸🇪"] false
["foo bar baz\t" "foo bar baz\t"] false
; objects
[{"foo" "bar"} {"foo" "bar"}] false
[{"foo" ["bar" 1]} {"foo" ["bar" 1]}] false
; arrays
[["foo" "bar"] ["foo" "bar"]] false
[["bar" "foo"] ["foo" "bar"]] true
[["fåäö" "båäör"] ["fåäö" "båäör"]] false
[["a" 1 [2] "b"] ["a" 1 [2] "b"]] false
; booleans
[true true] false
[false false] false
[true false] true
; null
[nil nil] false
[nil " "] true))
; bigint
#?(:clj
(deftest builtin-neq-bigint-test
(testing-builtin "neq"
[28857836529306024611913 28857836529306024611912] true)))
(deftest builtin-lt-test
(testing-builtin "lt"
[1 1] false
[1.001 1.001] false
[1.001 1.002] true
[2 1] false
[1 2] true
[1.9 2] true
[-2 2] true
; strings
["a" "a"] false
["b" "a"] false
["a" "b"] true
; objects
[{"foo" "bar"} {"foo" "bar"}] false
[{"foo" 1} {"foo" 2}] true
[{"foo" 1} {"foo" 1 "bar" 2}] false
[{"foo" {"x" 1}} {"foo" {"x" 2}}] true
[{"foo" [1 2]} {"foo" [1 2 3]}] true
; objects-different-keys
[{"foo" 1} {"bar" 2}] false
; arrays
[["foo" "bar"] ["foo" "bar"]] false
[["a" "b"] ["a" "c"]] true
[[1 2 3] [1 2 4]] true
[[1 2 3] [1 2 "a"]] true
[[1 2 3] [1 2 3 -100]] true
[[[1 2]] [[1 3]]] true
; sets
[#{1} #{1}] false
[#{1} #{2}] true
[#{1 2} #{3}] true
[#{100} #{1 10001}] false
[#{{"x" 1}} #{{"x" 2}}] true
; booleans
[true true] false
[true false] false
[false true] true
[false 0] true
[true 0] true
; null
[nil nil] false
[nil 1] true
[nil ""] true
[nil false] true))
(deftest builtin-gt-test
(testing-builtin "gt"
[1 1] false
[1.001 1.001] false
[1.001 1.002] false
[2 1] true
[1 2] false
[1.9 2] false
[-2 2] false
; strings
["a" "a"] false
["b" "a"] true
["a" "b"] false
; objects
[{"foo" "bar"} {"foo" "bar"}] false
[{"foo" 1} {"foo" 2}] false
[{"foo" 1} {"foo" 1 "bar" 2}] true
[{"foo" {"x" 1}} {"foo" {"x" 2}}] false
[{"foo" [1 2]} {"foo" [1 2 3]}] false
; objects-different-keys
[{"foo" 1} {"bar" 2}] true
; arrays
[["foo" "bar"] ["foo" "bar"]] false
[["a" "b"] ["a" "c"]] false
[[1 2 3] [1 2 4]] false
[[1 2 3] [1 2 "a"]] false
[[1 2 3] [1 2 3 -100]] false
[[[1 2]] [[1 3]]] false
; sets
[#{1} #{1}] false
[#{1} #{2}] false
[#{1 2} #{3}] false
[#{100} #{1 10001}] true
[#{{"x" 1}} #{{"x" 2}}] false
; booleans
[true true] false
[true false] true
[false true] false
[false 0] false
[true 0] false
; null
[nil nil] false
[nil 1] false
[nil ""] false
[nil false] false))
; These are already tested by virtue of rego-compare and the tests above
; Just sanity checking here..
(deftest builtin-lte-test
(testing-builtin "lte"
[1 1] true
[1 2] true
[2 1] false))
(deftest builtin-gte-test
(testing-builtin "gte"
[1 1] true
[1 2] false
[2 1] true))
| null | https://raw.githubusercontent.com/borgeby/jarl/2659afc6c72afb961cb1e98b779beb2b0b5d79c6/core/src/test/cljc/jarl/builtins/comparison_test.cljc | clojure | numbers
strings
objects
arrays
booleans
null
strings
objects
arrays
booleans
null
bigint
strings
objects
objects-different-keys
arrays
sets
booleans
null
strings
objects
objects-different-keys
arrays
sets
booleans
null
These are already tested by virtue of rego-compare and the tests above
Just sanity checking here.. | (ns jarl.builtins.comparison-test
(:require [test.utils :refer [testing-builtin]]
#?(:clj [clojure.test :refer [deftest]]
:cljs [cljs.test :refer [deftest]])))
(deftest builtin-equal-test
(testing-builtin "equal"
[1 1] true
[1 1.0] true
[-3.334 -3.3340000] true
[3.00000000000001 3] false
[3 "3"] false
["a" "a"] true
["a" "b"] false
["å" "å"] true
["🇸🇪" "🇸🇪"] true
["foo bar baz\t" "foo bar baz\t"] true
[{"foo" "bar"} {"foo" "bar"}] true
[{"foo" "bar"} {"foo" "bar" "bar" "baz"}] false
[{"foo" "bar" "bar" "baz"} {"bar" "baz" "foo" "bar"}] true
[{"foo" ["bar" 1]} {"foo" ["bar" 1]}] true
[{"foo" 1} {"foo" 1.0}] true
[["foo" "bar"] ["foo" "bar"]] true
[["bar" "foo"] ["foo" "bar"]] false
[["fåäö" "båäör"] ["fåäö" "båäör"]] true
[["a" 1 [2] "b"] ["a" 1 [2] "b"]] true
[true true] true
[false false] true
[true false] false
[nil nil] true
[nil " "] false))
(deftest builtin-neq-test
(testing-builtin "neq"
[1 2] true
[1 1] false
[1 1.0] false
[-3.334 -3.3340000] false
["a" "a"] false
["a" "A"] true
["å" "å"] false
["🇸🇪" "🇸🇪"] false
["foo bar baz\t" "foo bar baz\t"] false
[{"foo" "bar"} {"foo" "bar"}] false
[{"foo" ["bar" 1]} {"foo" ["bar" 1]}] false
[["foo" "bar"] ["foo" "bar"]] false
[["bar" "foo"] ["foo" "bar"]] true
[["fåäö" "båäör"] ["fåäö" "båäör"]] false
[["a" 1 [2] "b"] ["a" 1 [2] "b"]] false
[true true] false
[false false] false
[true false] true
[nil nil] false
[nil " "] true))
#?(:clj
(deftest builtin-neq-bigint-test
(testing-builtin "neq"
[28857836529306024611913 28857836529306024611912] true)))
(deftest builtin-lt-test
(testing-builtin "lt"
[1 1] false
[1.001 1.001] false
[1.001 1.002] true
[2 1] false
[1 2] true
[1.9 2] true
[-2 2] true
["a" "a"] false
["b" "a"] false
["a" "b"] true
[{"foo" "bar"} {"foo" "bar"}] false
[{"foo" 1} {"foo" 2}] true
[{"foo" 1} {"foo" 1 "bar" 2}] false
[{"foo" {"x" 1}} {"foo" {"x" 2}}] true
[{"foo" [1 2]} {"foo" [1 2 3]}] true
[{"foo" 1} {"bar" 2}] false
[["foo" "bar"] ["foo" "bar"]] false
[["a" "b"] ["a" "c"]] true
[[1 2 3] [1 2 4]] true
[[1 2 3] [1 2 "a"]] true
[[1 2 3] [1 2 3 -100]] true
[[[1 2]] [[1 3]]] true
[#{1} #{1}] false
[#{1} #{2}] true
[#{1 2} #{3}] true
[#{100} #{1 10001}] false
[#{{"x" 1}} #{{"x" 2}}] true
[true true] false
[true false] false
[false true] true
[false 0] true
[true 0] true
[nil nil] false
[nil 1] true
[nil ""] true
[nil false] true))
(deftest builtin-gt-test
(testing-builtin "gt"
[1 1] false
[1.001 1.001] false
[1.001 1.002] false
[2 1] true
[1 2] false
[1.9 2] false
[-2 2] false
["a" "a"] false
["b" "a"] true
["a" "b"] false
[{"foo" "bar"} {"foo" "bar"}] false
[{"foo" 1} {"foo" 2}] false
[{"foo" 1} {"foo" 1 "bar" 2}] true
[{"foo" {"x" 1}} {"foo" {"x" 2}}] false
[{"foo" [1 2]} {"foo" [1 2 3]}] false
[{"foo" 1} {"bar" 2}] true
[["foo" "bar"] ["foo" "bar"]] false
[["a" "b"] ["a" "c"]] false
[[1 2 3] [1 2 4]] false
[[1 2 3] [1 2 "a"]] false
[[1 2 3] [1 2 3 -100]] false
[[[1 2]] [[1 3]]] false
[#{1} #{1}] false
[#{1} #{2}] false
[#{1 2} #{3}] false
[#{100} #{1 10001}] true
[#{{"x" 1}} #{{"x" 2}}] false
[true true] false
[true false] true
[false true] false
[false 0] false
[true 0] false
[nil nil] false
[nil 1] false
[nil ""] false
[nil false] false))
(deftest builtin-lte-test
(testing-builtin "lte"
[1 1] true
[1 2] true
[2 1] false))
(deftest builtin-gte-test
(testing-builtin "gte"
[1 1] true
[1 2] false
[2 1] true))
|
b6ee10ec054491d048c3e110e0efd73c43b5dd31102f2efcce643e30817e8a71 | tarides/ocaml-platform-installer | binary_package.mli | (** Make a binary package out of a package built in the {!Sandbox_switch}.
Package definitions and source archives are stored in {!Binary_repo}. *)
open Bos
type full_name
val binary_name :
ocaml_version:string ->
name:string ->
ver:string ->
ocaml_version_dependent:bool ->
full_name
val to_string : full_name -> string
val name : full_name -> string
val ver : full_name -> string
val package : full_name -> Package.full_name
val version_is_binary : string -> bool
(** Tell from the version if the package is a binary package. *)
type binary_pkg = Package.Install_file.t * Package.Opam_file.t
val make_binary_package :
ocaml_version:string option ->
arch:string ->
os_distribution:string ->
prefix:Fpath.t ->
files:Fpath.t list ->
archive_path:Fpath.t ->
full_name ->
name:string ->
(binary_pkg, 'e) OS.result
(** Make a binary package from the result of installing a package in the sandbox
switch. *)
| null | https://raw.githubusercontent.com/tarides/ocaml-platform-installer/9aefc34f4aeac47b7ae1431718161eabbbb35e94/src/lib/binary_repo/binary_package.mli | ocaml | * Make a binary package out of a package built in the {!Sandbox_switch}.
Package definitions and source archives are stored in {!Binary_repo}.
* Tell from the version if the package is a binary package.
* Make a binary package from the result of installing a package in the sandbox
switch. |
open Bos
type full_name
val binary_name :
ocaml_version:string ->
name:string ->
ver:string ->
ocaml_version_dependent:bool ->
full_name
val to_string : full_name -> string
val name : full_name -> string
val ver : full_name -> string
val package : full_name -> Package.full_name
val version_is_binary : string -> bool
type binary_pkg = Package.Install_file.t * Package.Opam_file.t
val make_binary_package :
ocaml_version:string option ->
arch:string ->
os_distribution:string ->
prefix:Fpath.t ->
files:Fpath.t list ->
archive_path:Fpath.t ->
full_name ->
name:string ->
(binary_pkg, 'e) OS.result
|
13accdf8fefa2cad2af53fa00ef3814f6d32386e036d1786f510b1427477be65 | TerrorJack/ghc-alter | Exts.hs | # LANGUAGE Unsafe #
# LANGUAGE MagicHash , UnboxedTuples , TypeFamilies , DeriveDataTypeable ,
MultiParamTypeClasses , FlexibleInstances , NoImplicitPrelude #
MultiParamTypeClasses, FlexibleInstances, NoImplicitPrelude #-}
-----------------------------------------------------------------------------
-- |
Module : GHC.Exts
Copyright : ( c ) The University of Glasgow 2002
-- License : see libraries/base/LICENSE
--
-- Maintainer :
-- Stability : internal
Portability : non - portable ( GHC Extensions )
--
GHC Extensions : this is the Approved Way to get at GHC - specific extensions .
--
-- Note: no other base module should import this module.
-----------------------------------------------------------------------------
module GHC.Exts
(
-- * Representations of some basic types
Int(..),Word(..),Float(..),Double(..),
Char(..),
Ptr(..), FunPtr(..),
-- * The maximum tuple size
maxTupleSize,
-- * Primitive operations
module GHC.Prim,
shiftL#, shiftRL#, iShiftL#, iShiftRA#, iShiftRL#,
uncheckedShiftL64#, uncheckedShiftRL64#,
uncheckedIShiftL64#, uncheckedIShiftRA64#,
isTrue#,
-- * Fusion
build, augment,
-- * Overloaded string literals
IsString(..),
-- * Debugging
breakpoint, breakpointCond,
-- * Ids with special behaviour
lazy, inline, oneShot,
-- * Running 'RealWorld' state transformers
runRW#,
-- * Safe coercions
--
-- | These are available from the /Trustworthy/ module "Data.Coerce" as well
--
-- @since 4.7.0.0
Data.Coerce.coerce, Data.Coerce.Coercible,
-- * Equality
type (~~),
-- * Representation polymorphism
GHC.Prim.TYPE, RuntimeRep(..), VecCount(..), VecElem(..),
-- * Transform comprehensions
Down(..), groupWith, sortWith, the,
-- * Event logging
traceEvent,
* SpecConstr annotations
SpecConstrAnnotation(..),
-- * The call stack
currentCallStack,
* The Constraint kind
Constraint,
-- * The Any type
Any,
-- * Overloaded lists
IsList(..)
) where
import GHC.Prim hiding ( coerce, TYPE )
import qualified GHC.Prim
import GHC.Base hiding ( coerce )
import GHC.Word
import GHC.Int
import GHC.Ptr
import GHC.Stack
import qualified Data.Coerce
import Data.String
import Data.OldList
import Data.Data
import Data.Ord
import Data.Version ( Version(..), makeVersion )
import qualified Debug.Trace
XXX This should really be in Data . Tuple , where the definitions are
maxTupleSize :: Int
maxTupleSize = 62
-- | 'the' ensures that all the elements of the list are identical
-- and then returns that unique element
the :: Eq a => [a] -> a
the (x:xs)
| all (x ==) xs = x
| otherwise = errorWithoutStackTrace "GHC.Exts.the: non-identical elements"
the [] = errorWithoutStackTrace "GHC.Exts.the: empty list"
-- | The 'sortWith' function sorts a list of elements using the
-- user supplied function to project something out of each element
sortWith :: Ord b => (a -> b) -> [a] -> [a]
sortWith f = sortBy (\x y -> compare (f x) (f y))
-- | The 'groupWith' function uses the user supplied function which
projects an element out of every list element in order to first sort the
-- input list and then to form groups by equality on these projected elements
{-# INLINE groupWith #-}
groupWith :: Ord b => (a -> b) -> [a] -> [[a]]
groupWith f xs = build (\c n -> groupByFB c n (\x y -> f x == f y) (sortWith f xs))
See Note [ Inline FB functions ] in GHC.List
groupByFB :: ([a] -> lst -> lst) -> lst -> (a -> a -> Bool) -> [a] -> lst
groupByFB c n eq xs0 = groupByFBCore xs0
where groupByFBCore [] = n
groupByFBCore (x:xs) = c (x:ys) (groupByFBCore zs)
where (ys, zs) = span (eq x) xs
-- -----------------------------------------------------------------------------
-- tracing
traceEvent :: String -> IO ()
traceEvent = Debug.Trace.traceEventIO
deprecated in 7.4
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* SpecConstr annotation *
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* SpecConstr annotation *
* *
********************************************************************** -}
Annotating a type with NoSpecConstr will make SpecConstr
-- not specialise for arguments of that type.
This data type is defined here , rather than in the SpecConstr module
-- itself, so that importing it doesn't force stupidly linking the
entire ghc package at runtime
data SpecConstrAnnotation = NoSpecConstr | ForceSpecConstr
deriving( Data, Eq )
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* The IsList class *
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* The IsList class *
* *
********************************************************************** -}
| The ' IsList ' class and its methods are intended to be used in
-- conjunction with the OverloadedLists extension.
--
-- @since 4.7.0.0
class IsList l where
-- | The 'Item' type function returns the type of items of the structure
-- @l@.
type Item l
-- | The 'fromList' function constructs the structure @l@ from the given
-- list of @Item l@
fromList :: [Item l] -> l
-- | The 'fromListN' function takes the input list's length as a hint. Its
-- behaviour should be equivalent to 'fromList'. The hint can be used to
-- construct the structure @l@ more efficiently compared to 'fromList'. If
-- the given hint does not equal to the input list's length the behaviour of
-- 'fromListN' is not specified.
fromListN :: Int -> [Item l] -> l
fromListN _ = fromList
| The ' toList ' function extracts a list of @Item l@ from the structure @l@.
-- It should satisfy fromList . toList = id.
toList :: l -> [Item l]
| @since 4.7.0.0
instance IsList [a] where
type (Item [a]) = a
fromList = id
toList = id
| @since 4.8.0.0
instance IsList Version where
type (Item Version) = Int
fromList = makeVersion
toList = versionBranch
| Be aware that ' fromList . toList = i d ' only for unfrozen ' CallStack 's ,
-- since 'toList' removes frozenness information.
--
@since 4.9.0.0
instance IsList CallStack where
type (Item CallStack) = (String, SrcLoc)
fromList = fromCallSiteList
toList = getCallStack
| null | https://raw.githubusercontent.com/TerrorJack/ghc-alter/db736f34095eef416b7e077f9b26fc03aa78c311/ghc-alter/boot-lib/base/GHC/Exts.hs | haskell | ---------------------------------------------------------------------------
|
License : see libraries/base/LICENSE
Maintainer :
Stability : internal
Note: no other base module should import this module.
---------------------------------------------------------------------------
* Representations of some basic types
* The maximum tuple size
* Primitive operations
* Fusion
* Overloaded string literals
* Debugging
* Ids with special behaviour
* Running 'RealWorld' state transformers
* Safe coercions
| These are available from the /Trustworthy/ module "Data.Coerce" as well
@since 4.7.0.0
* Equality
* Representation polymorphism
* Transform comprehensions
* Event logging
* The call stack
* The Any type
* Overloaded lists
| 'the' ensures that all the elements of the list are identical
and then returns that unique element
| The 'sortWith' function sorts a list of elements using the
user supplied function to project something out of each element
| The 'groupWith' function uses the user supplied function which
input list and then to form groups by equality on these projected elements
# INLINE groupWith #
-----------------------------------------------------------------------------
tracing
not specialise for arguments of that type.
itself, so that importing it doesn't force stupidly linking the
conjunction with the OverloadedLists extension.
@since 4.7.0.0
| The 'Item' type function returns the type of items of the structure
@l@.
| The 'fromList' function constructs the structure @l@ from the given
list of @Item l@
| The 'fromListN' function takes the input list's length as a hint. Its
behaviour should be equivalent to 'fromList'. The hint can be used to
construct the structure @l@ more efficiently compared to 'fromList'. If
the given hint does not equal to the input list's length the behaviour of
'fromListN' is not specified.
It should satisfy fromList . toList = id.
since 'toList' removes frozenness information.
| # LANGUAGE Unsafe #
# LANGUAGE MagicHash , UnboxedTuples , TypeFamilies , DeriveDataTypeable ,
MultiParamTypeClasses , FlexibleInstances , NoImplicitPrelude #
MultiParamTypeClasses, FlexibleInstances, NoImplicitPrelude #-}
Module : GHC.Exts
Copyright : ( c ) The University of Glasgow 2002
Portability : non - portable ( GHC Extensions )
GHC Extensions : this is the Approved Way to get at GHC - specific extensions .
module GHC.Exts
(
Int(..),Word(..),Float(..),Double(..),
Char(..),
Ptr(..), FunPtr(..),
maxTupleSize,
module GHC.Prim,
shiftL#, shiftRL#, iShiftL#, iShiftRA#, iShiftRL#,
uncheckedShiftL64#, uncheckedShiftRL64#,
uncheckedIShiftL64#, uncheckedIShiftRA64#,
isTrue#,
build, augment,
IsString(..),
breakpoint, breakpointCond,
lazy, inline, oneShot,
runRW#,
Data.Coerce.coerce, Data.Coerce.Coercible,
type (~~),
GHC.Prim.TYPE, RuntimeRep(..), VecCount(..), VecElem(..),
Down(..), groupWith, sortWith, the,
traceEvent,
* SpecConstr annotations
SpecConstrAnnotation(..),
currentCallStack,
* The Constraint kind
Constraint,
Any,
IsList(..)
) where
import GHC.Prim hiding ( coerce, TYPE )
import qualified GHC.Prim
import GHC.Base hiding ( coerce )
import GHC.Word
import GHC.Int
import GHC.Ptr
import GHC.Stack
import qualified Data.Coerce
import Data.String
import Data.OldList
import Data.Data
import Data.Ord
import Data.Version ( Version(..), makeVersion )
import qualified Debug.Trace
XXX This should really be in Data . Tuple , where the definitions are
maxTupleSize :: Int
maxTupleSize = 62
the :: Eq a => [a] -> a
the (x:xs)
| all (x ==) xs = x
| otherwise = errorWithoutStackTrace "GHC.Exts.the: non-identical elements"
the [] = errorWithoutStackTrace "GHC.Exts.the: empty list"
sortWith :: Ord b => (a -> b) -> [a] -> [a]
sortWith f = sortBy (\x y -> compare (f x) (f y))
projects an element out of every list element in order to first sort the
groupWith :: Ord b => (a -> b) -> [a] -> [[a]]
groupWith f xs = build (\c n -> groupByFB c n (\x y -> f x == f y) (sortWith f xs))
See Note [ Inline FB functions ] in GHC.List
groupByFB :: ([a] -> lst -> lst) -> lst -> (a -> a -> Bool) -> [a] -> lst
groupByFB c n eq xs0 = groupByFBCore xs0
where groupByFBCore [] = n
groupByFBCore (x:xs) = c (x:ys) (groupByFBCore zs)
where (ys, zs) = span (eq x) xs
traceEvent :: String -> IO ()
traceEvent = Debug.Trace.traceEventIO
deprecated in 7.4
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* SpecConstr annotation *
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* SpecConstr annotation *
* *
********************************************************************** -}
Annotating a type with NoSpecConstr will make SpecConstr
This data type is defined here , rather than in the SpecConstr module
entire ghc package at runtime
data SpecConstrAnnotation = NoSpecConstr | ForceSpecConstr
deriving( Data, Eq )
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* The IsList class *
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* The IsList class *
* *
********************************************************************** -}
| The ' IsList ' class and its methods are intended to be used in
class IsList l where
type Item l
fromList :: [Item l] -> l
fromListN :: Int -> [Item l] -> l
fromListN _ = fromList
| The ' toList ' function extracts a list of @Item l@ from the structure @l@.
toList :: l -> [Item l]
| @since 4.7.0.0
instance IsList [a] where
type (Item [a]) = a
fromList = id
toList = id
| @since 4.8.0.0
instance IsList Version where
type (Item Version) = Int
fromList = makeVersion
toList = versionBranch
| Be aware that ' fromList . toList = i d ' only for unfrozen ' CallStack 's ,
@since 4.9.0.0
instance IsList CallStack where
type (Item CallStack) = (String, SrcLoc)
fromList = fromCallSiteList
toList = getCallStack
|
bb3502f024d90154f354c547bb58ca889c9add137cd1d6baad046795335bbbff | binaryage/chromex | chrome_event_subscription.cljs | (ns chromex.chrome-event-subscription
(:require [chromex.protocols.chrome-event-channel :refer [IChromeEventChannel]]
[chromex.protocols.chrome-event-subscription :refer [IChromeEventSubscription]]
[oops.core :refer [oapply! ocall!]]))
; exception handlers, see
(declare ^:dynamic *subscribe-called-while-subscribed*)
(declare ^:dynamic *unsubscribe-called-while-not-subscribed*)
; -- ChromeEventSubscription ------------------------------------------------------------------------------------------------
(deftype ChromeEventSubscription [chrome-event listener chan ^:mutable subscribed-count]
IChromeEventSubscription
(subscribe! [this]
(chromex.protocols.chrome-event-subscription/subscribe! this nil))
(subscribe! [this extra-args]
{:pre [(or (nil? extra-args) (seq? extra-args))]}
(if-not (= subscribed-count 0)
(*subscribe-called-while-subscribed* this)
(do
(when (satisfies? IChromeEventChannel chan)
(chromex.protocols.chrome-event-channel/register! chan this))
(set! subscribed-count (inc subscribed-count))
(oapply! chrome-event "addListener" (cons listener extra-args))))) ; see #filtered or 'Registering event listeners' at
(unsubscribe! [this]
(if-not (= subscribed-count 1)
(*unsubscribe-called-while-not-subscribed* this)
(do
(set! subscribed-count (dec subscribed-count))
(ocall! chrome-event "removeListener" listener)
(if (satisfies? IChromeEventChannel chan)
(chromex.protocols.chrome-event-channel/unregister! chan this))))))
; -- constructor ------------------------------------------------------------------------------------------------------------
(defn make-chrome-event-subscription [chrome-event listener chan]
{:pre [chrome-event listener chan]}
(ChromeEventSubscription. chrome-event listener chan 0))
; -- default exception handlers ---------------------------------------------------------------------------------------------
(defn ^:dynamic *subscribe-called-while-subscribed* [_chrome-event-subscription]
(assert false "ChromeEventSubscription: subscribe called while already subscribed"))
(defn ^:dynamic *unsubscribe-called-while-not-subscribed* [_chrome-event-subscription]
(assert false "ChromeEventSubscription: unsubscribe called while not subscribed"))
| null | https://raw.githubusercontent.com/binaryage/chromex/33834ba5dd4f4238a3c51f99caa0416f30c308c5/src/lib/chromex/chrome_event_subscription.cljs | clojure | exception handlers, see
-- ChromeEventSubscription ------------------------------------------------------------------------------------------------
see #filtered or 'Registering event listeners' at
-- constructor ------------------------------------------------------------------------------------------------------------
-- default exception handlers --------------------------------------------------------------------------------------------- | (ns chromex.chrome-event-subscription
(:require [chromex.protocols.chrome-event-channel :refer [IChromeEventChannel]]
[chromex.protocols.chrome-event-subscription :refer [IChromeEventSubscription]]
[oops.core :refer [oapply! ocall!]]))
(declare ^:dynamic *subscribe-called-while-subscribed*)
(declare ^:dynamic *unsubscribe-called-while-not-subscribed*)
(deftype ChromeEventSubscription [chrome-event listener chan ^:mutable subscribed-count]
IChromeEventSubscription
(subscribe! [this]
(chromex.protocols.chrome-event-subscription/subscribe! this nil))
(subscribe! [this extra-args]
{:pre [(or (nil? extra-args) (seq? extra-args))]}
(if-not (= subscribed-count 0)
(*subscribe-called-while-subscribed* this)
(do
(when (satisfies? IChromeEventChannel chan)
(chromex.protocols.chrome-event-channel/register! chan this))
(set! subscribed-count (inc subscribed-count))
(unsubscribe! [this]
(if-not (= subscribed-count 1)
(*unsubscribe-called-while-not-subscribed* this)
(do
(set! subscribed-count (dec subscribed-count))
(ocall! chrome-event "removeListener" listener)
(if (satisfies? IChromeEventChannel chan)
(chromex.protocols.chrome-event-channel/unregister! chan this))))))
(defn make-chrome-event-subscription [chrome-event listener chan]
{:pre [chrome-event listener chan]}
(ChromeEventSubscription. chrome-event listener chan 0))
(defn ^:dynamic *subscribe-called-while-subscribed* [_chrome-event-subscription]
(assert false "ChromeEventSubscription: subscribe called while already subscribed"))
(defn ^:dynamic *unsubscribe-called-while-not-subscribed* [_chrome-event-subscription]
(assert false "ChromeEventSubscription: unsubscribe called while not subscribed"))
|
3efaf0cc79b80309b3a36a757e1dad69d3859901078dc771931c5795be2057c1 | funcool/yetti | websocket.clj | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
;;
Copyright © < >
(ns yetti.websocket
(:require
[clojure.string :as str]
[yetti.request :as req]
[yetti.util :as util])
(:import
clojure.lang.IFn
io.undertow.server.HttpServerExchange
io.undertow.websockets.WebSocketConnectionCallback
io.undertow.websockets.WebSocketProtocolHandshakeHandler
io.undertow.websockets.core.AbstractReceiveListener
io.undertow.websockets.core.BufferedBinaryMessage
io.undertow.websockets.core.BufferedTextMessage
io.undertow.websockets.core.CloseMessage
io.undertow.websockets.core.WebSocketCallback
io.undertow.websockets.core.WebSocketChannel
io.undertow.websockets.core.WebSocketUtils
io.undertow.websockets.core.WebSockets
io.undertow.websockets.extensions.PerMessageDeflateHandshake
io.undertow.websockets.spi.WebSocketHttpExchange
java.nio.ByteBuffer
java.util.concurrent.CompletionException
java.util.concurrent.CompletableFuture
org.xnio.Pooled
yetti.util.WebSocketListenerWrapper))
(set! *warn-on-reflection* true)
(defprotocol IWebSocket
(send! [this msg] [this msg cb])
(ping! [this msg] [this msg cb])
(pong! [this msg] [this msg cb])
(close! [this] [this status-code reason])
(remote-addr [this])
(idle-timeout! [this ms])
(connected? [this]))
(defprotocol IWebSocketSend
(-send! [x ws] [x ws cb] "How to encode content sent to the WebSocket clients"))
(defprotocol IWebSocketPing
(-ping! [x ws] [x ws cb] "How to encode bytes sent with a ping"))
(defprotocol IWebSocketPong
(-pong! [x ws] [x ws cb] "How to encode bytes sent with a pong"))
(def ^:private no-op (constantly nil))
(defn- fn->callback
[cb]
(reify WebSocketCallback
(complete [_ _ _]
(cb nil))
(onError [_ _ _ cause]
(cb cause))))
(defn- cf->callback
[^CompletableFuture ft]
(reify WebSocketCallback
(complete [_ _ _]
(.complete ft nil))
(onError [_ _ _ cause]
(.completeExceptionally ft cause))))
(defn- await-ft!
"Await completion of CompletableFuture and unwraps
CompletionException in case of exception is raised."
[^CompletableFuture ft]
(try
(.get ft)
(catch CompletionException cause
(if-let [cause' (.getCause cause)]
(throw cause')
(throw cause)))))
(extend-protocol IWebSocketSend
(Class/forName "[B")
(-send!
([ba channel]
(-send! (ByteBuffer/wrap ba) channel))
([ba channel cb]
(-send! (ByteBuffer/wrap ba) channel cb)))
ByteBuffer
(-send!
([bb channel]
(let [ft (CompletableFuture.)]
(WebSockets/sendBinary ^ByteBuffer bb
^WebSocketChannel channel
^WebSocketCallback (cf->callback ft))
(await-ft! ft)))
([bb channel cb]
(WebSockets/sendBinary ^ByteBuffer bb
^WebSocketChannel channel
^WebSocketCallback (fn->callback cb))))
String
(-send!
([s channel]
(let [ft (CompletableFuture.)]
(WebSockets/sendText ^String s
^WebSocketChannel channel
^WebSocketCallback (cf->callback ft))
(await-ft! ft)))
([s channel cb]
(WebSockets/sendText ^String s
^WebSocketChannel channel
^WebSocketCallback (fn->callback cb)))))
(extend-protocol IWebSocketPing
(Class/forName "[B")
(-ping!
([ba channel] (-ping! (ByteBuffer/wrap ba) channel))
([ba channel cb] (-ping! (ByteBuffer/wrap ba) channel cb)))
String
(-ping!
([s channel] (-ping! (WebSocketUtils/fromUtf8String s) channel))
([s channel cb] (-ping! (WebSocketUtils/fromUtf8String s) channel cb)))
ByteBuffer
(-ping!
([bb channel]
(let [ft (CompletableFuture.)]
(WebSockets/sendPing ^ByteBuffer bb
^WebSocketChannel channel
^WebSocketCallback (cf->callback ft))
(await-ft! ft)))
([bb channel cb]
(WebSockets/sendPing ^ByteBuffer bb
^WebSocketChannel channel
^WebSocketCallback (fn->callback cb)))))
(extend-protocol IWebSocketPong
(Class/forName "[B")
(-pong!
([ba channel] (-pong! (ByteBuffer/wrap ba) channel))
([ba channel cb] (-pong! (ByteBuffer/wrap ba) channel cb)))
String
(-pong!
([s channel] (-pong! (WebSocketUtils/fromUtf8String s) channel))
([s channel cb] (-pong! (WebSocketUtils/fromUtf8String s) channel cb)))
ByteBuffer
(-pong!
([bb channel]
(let [ft (CompletableFuture.)]
(WebSockets/sendPong ^ByteBuffer bb
^WebSocketChannel channel
^WebSocketCallback (cf->callback ft))
(await-ft! ft)))
([bb channel cb]
(WebSockets/sendPong ^ByteBuffer bb
^WebSocketChannel channel
^WebSocketCallback (fn->callback cb)))))
(extend-protocol IWebSocket
WebSocketChannel
(send!
([this msg] (-send! msg this))
([this msg cb] (-send! msg this cb)))
(ping!
([this msg] (-ping! msg this))
([this msg cb] (-ping! msg this cb)))
(pong!
([this msg] (-pong! msg this))
([this msg cb] (-pong! msg this cb)))
(close! [this]
(.. this (close)))
(close! [this code reason]
(.setCloseCode this code)
(.setCloseReason this reason)
(.sendClose this)
(.close this))
(remote-addr [this]
(.. this (getDestinationAddress)))
(idle-timeout! [this ms]
(if (integer? ms)
(.. this (setIdleTimeout ^long ms))
(.. this (setIdleTimeout ^long (inst-ms ms)))))
(connected? [this]
(. this (isOpen))))
(defn on-close!
"Adds on-close task to the websocket channel. Returns `channel`
instance."
[^WebSocketChannel channel callback]
(.addCloseTask channel
(reify org.xnio.ChannelListener
(handleEvent [_ event]
(try
(callback event)
(catch Throwable cause)))))
channel)
(defn upgrade-request?
"Checks if a request is a websocket upgrade request."
[request]
(let [upgrade (req/get-header request "upgrade")
connection (req/get-header request "connection")]
(and upgrade
connection
(str/includes? (str/lower-case upgrade) "websocket")
(str/includes? (str/lower-case connection) "upgrade"))))
(defn- create-websocket-receiver
[{:keys [on-error on-text on-close on-bytes on-ping on-pong]}]
(WebSocketListenerWrapper. on-text
on-bytes
on-ping
on-pong
on-error
on-close))
(defn create-websocket-connecton-callback
^WebSocketConnectionCallback
[on-connect {:keys [:websocket/idle-timeout]}]
(reify WebSocketConnectionCallback
(onConnect [_ exchange channel]
(some->> idle-timeout long (.setIdleTimeout channel))
(let [setter (.getReceiveSetter ^WebSocketChannel channel)
handlers (on-connect exchange channel)]
(when-let [on-open (:on-open handlers)]
(on-open channel))
(.set setter (create-websocket-receiver handlers))
(.resumeReceives ^WebSocketChannel channel)))))
(defn upgrade-response
[^HttpServerExchange exchange on-connect options]
(let [callback (create-websocket-connecton-callback on-connect options)
handler (WebSocketProtocolHandshakeHandler. callback)]
(.addExtension handler (PerMessageDeflateHandshake. false 6))
(.handleRequest handler exchange)))
(defn upgrade
"Returns a websocket upgrade response."
[request handler]
{::upgrade (fn [^WebSocketHttpExchange exchange ^WebSocketChannel channel]
(-> request
(assoc ::exchange exchange)
(assoc ::channel channel)
(dissoc :body)
(handler)))})
| null | https://raw.githubusercontent.com/funcool/yetti/e2d25dbaab4450c3f617e50d95bcdf8445c9274d/src/yetti/websocket.clj | clojure | 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 © < >
(ns yetti.websocket
(:require
[clojure.string :as str]
[yetti.request :as req]
[yetti.util :as util])
(:import
clojure.lang.IFn
io.undertow.server.HttpServerExchange
io.undertow.websockets.WebSocketConnectionCallback
io.undertow.websockets.WebSocketProtocolHandshakeHandler
io.undertow.websockets.core.AbstractReceiveListener
io.undertow.websockets.core.BufferedBinaryMessage
io.undertow.websockets.core.BufferedTextMessage
io.undertow.websockets.core.CloseMessage
io.undertow.websockets.core.WebSocketCallback
io.undertow.websockets.core.WebSocketChannel
io.undertow.websockets.core.WebSocketUtils
io.undertow.websockets.core.WebSockets
io.undertow.websockets.extensions.PerMessageDeflateHandshake
io.undertow.websockets.spi.WebSocketHttpExchange
java.nio.ByteBuffer
java.util.concurrent.CompletionException
java.util.concurrent.CompletableFuture
org.xnio.Pooled
yetti.util.WebSocketListenerWrapper))
(set! *warn-on-reflection* true)
(defprotocol IWebSocket
(send! [this msg] [this msg cb])
(ping! [this msg] [this msg cb])
(pong! [this msg] [this msg cb])
(close! [this] [this status-code reason])
(remote-addr [this])
(idle-timeout! [this ms])
(connected? [this]))
(defprotocol IWebSocketSend
(-send! [x ws] [x ws cb] "How to encode content sent to the WebSocket clients"))
(defprotocol IWebSocketPing
(-ping! [x ws] [x ws cb] "How to encode bytes sent with a ping"))
(defprotocol IWebSocketPong
(-pong! [x ws] [x ws cb] "How to encode bytes sent with a pong"))
(def ^:private no-op (constantly nil))
(defn- fn->callback
[cb]
(reify WebSocketCallback
(complete [_ _ _]
(cb nil))
(onError [_ _ _ cause]
(cb cause))))
(defn- cf->callback
[^CompletableFuture ft]
(reify WebSocketCallback
(complete [_ _ _]
(.complete ft nil))
(onError [_ _ _ cause]
(.completeExceptionally ft cause))))
(defn- await-ft!
"Await completion of CompletableFuture and unwraps
CompletionException in case of exception is raised."
[^CompletableFuture ft]
(try
(.get ft)
(catch CompletionException cause
(if-let [cause' (.getCause cause)]
(throw cause')
(throw cause)))))
(extend-protocol IWebSocketSend
(Class/forName "[B")
(-send!
([ba channel]
(-send! (ByteBuffer/wrap ba) channel))
([ba channel cb]
(-send! (ByteBuffer/wrap ba) channel cb)))
ByteBuffer
(-send!
([bb channel]
(let [ft (CompletableFuture.)]
(WebSockets/sendBinary ^ByteBuffer bb
^WebSocketChannel channel
^WebSocketCallback (cf->callback ft))
(await-ft! ft)))
([bb channel cb]
(WebSockets/sendBinary ^ByteBuffer bb
^WebSocketChannel channel
^WebSocketCallback (fn->callback cb))))
String
(-send!
([s channel]
(let [ft (CompletableFuture.)]
(WebSockets/sendText ^String s
^WebSocketChannel channel
^WebSocketCallback (cf->callback ft))
(await-ft! ft)))
([s channel cb]
(WebSockets/sendText ^String s
^WebSocketChannel channel
^WebSocketCallback (fn->callback cb)))))
(extend-protocol IWebSocketPing
(Class/forName "[B")
(-ping!
([ba channel] (-ping! (ByteBuffer/wrap ba) channel))
([ba channel cb] (-ping! (ByteBuffer/wrap ba) channel cb)))
String
(-ping!
([s channel] (-ping! (WebSocketUtils/fromUtf8String s) channel))
([s channel cb] (-ping! (WebSocketUtils/fromUtf8String s) channel cb)))
ByteBuffer
(-ping!
([bb channel]
(let [ft (CompletableFuture.)]
(WebSockets/sendPing ^ByteBuffer bb
^WebSocketChannel channel
^WebSocketCallback (cf->callback ft))
(await-ft! ft)))
([bb channel cb]
(WebSockets/sendPing ^ByteBuffer bb
^WebSocketChannel channel
^WebSocketCallback (fn->callback cb)))))
(extend-protocol IWebSocketPong
(Class/forName "[B")
(-pong!
([ba channel] (-pong! (ByteBuffer/wrap ba) channel))
([ba channel cb] (-pong! (ByteBuffer/wrap ba) channel cb)))
String
(-pong!
([s channel] (-pong! (WebSocketUtils/fromUtf8String s) channel))
([s channel cb] (-pong! (WebSocketUtils/fromUtf8String s) channel cb)))
ByteBuffer
(-pong!
([bb channel]
(let [ft (CompletableFuture.)]
(WebSockets/sendPong ^ByteBuffer bb
^WebSocketChannel channel
^WebSocketCallback (cf->callback ft))
(await-ft! ft)))
([bb channel cb]
(WebSockets/sendPong ^ByteBuffer bb
^WebSocketChannel channel
^WebSocketCallback (fn->callback cb)))))
(extend-protocol IWebSocket
WebSocketChannel
(send!
([this msg] (-send! msg this))
([this msg cb] (-send! msg this cb)))
(ping!
([this msg] (-ping! msg this))
([this msg cb] (-ping! msg this cb)))
(pong!
([this msg] (-pong! msg this))
([this msg cb] (-pong! msg this cb)))
(close! [this]
(.. this (close)))
(close! [this code reason]
(.setCloseCode this code)
(.setCloseReason this reason)
(.sendClose this)
(.close this))
(remote-addr [this]
(.. this (getDestinationAddress)))
(idle-timeout! [this ms]
(if (integer? ms)
(.. this (setIdleTimeout ^long ms))
(.. this (setIdleTimeout ^long (inst-ms ms)))))
(connected? [this]
(. this (isOpen))))
(defn on-close!
"Adds on-close task to the websocket channel. Returns `channel`
instance."
[^WebSocketChannel channel callback]
(.addCloseTask channel
(reify org.xnio.ChannelListener
(handleEvent [_ event]
(try
(callback event)
(catch Throwable cause)))))
channel)
(defn upgrade-request?
"Checks if a request is a websocket upgrade request."
[request]
(let [upgrade (req/get-header request "upgrade")
connection (req/get-header request "connection")]
(and upgrade
connection
(str/includes? (str/lower-case upgrade) "websocket")
(str/includes? (str/lower-case connection) "upgrade"))))
(defn- create-websocket-receiver
[{:keys [on-error on-text on-close on-bytes on-ping on-pong]}]
(WebSocketListenerWrapper. on-text
on-bytes
on-ping
on-pong
on-error
on-close))
(defn create-websocket-connecton-callback
^WebSocketConnectionCallback
[on-connect {:keys [:websocket/idle-timeout]}]
(reify WebSocketConnectionCallback
(onConnect [_ exchange channel]
(some->> idle-timeout long (.setIdleTimeout channel))
(let [setter (.getReceiveSetter ^WebSocketChannel channel)
handlers (on-connect exchange channel)]
(when-let [on-open (:on-open handlers)]
(on-open channel))
(.set setter (create-websocket-receiver handlers))
(.resumeReceives ^WebSocketChannel channel)))))
(defn upgrade-response
[^HttpServerExchange exchange on-connect options]
(let [callback (create-websocket-connecton-callback on-connect options)
handler (WebSocketProtocolHandshakeHandler. callback)]
(.addExtension handler (PerMessageDeflateHandshake. false 6))
(.handleRequest handler exchange)))
(defn upgrade
"Returns a websocket upgrade response."
[request handler]
{::upgrade (fn [^WebSocketHttpExchange exchange ^WebSocketChannel channel]
(-> request
(assoc ::exchange exchange)
(assoc ::channel channel)
(dissoc :body)
(handler)))})
| |
617085e59348eec36e6f90aefa96fdf5c25f134d274b41fc23097c14c9a1663f | janestreet/memtrace_viewer_with_deps | import.ml | module Incr = Incremental.Make ()
module Incr_map = Incr_map.Make (Incr)
module Var = Incr.Var
module Obs = Incr.Observer
module Bench = Core_bench.Bench
include Incr.Let_syntax
module Infix = struct
let ( := ) = Var.set
let ( ! ) = Var.value
end
| null | https://raw.githubusercontent.com/janestreet/memtrace_viewer_with_deps/5a9e1f927f5f8333e2d71c8d3ca03a45587422c4/vendor/incr_map/bench/src/import.ml | ocaml | module Incr = Incremental.Make ()
module Incr_map = Incr_map.Make (Incr)
module Var = Incr.Var
module Obs = Incr.Observer
module Bench = Core_bench.Bench
include Incr.Let_syntax
module Infix = struct
let ( := ) = Var.set
let ( ! ) = Var.value
end
| |
eead138993d3a66363e24c8a42ae4c550cbe6a49478cf701a45d05f53042c07c | nitrogen/NitrogenProject.com | tests_cookie.erl | -module(tests_cookie).
-include_lib("nitrogen_core/include/wf.hrl").
-compile(export_all).
main() ->
case wf:q("step") of
"1" -> step1_main();
"2" -> step2_main();
"3" -> step3_main();
"4" -> step4_main()
end,
#template{file="templates/grid.html"}.
step1_main() ->
InitialCookieVal = wf_utils:guid(),
wf:session(test_cookie_val, InitialCookieVal),
wf:cookie(test_cookie_val, InitialCookieVal),
wf_test:start(fun step1_tests/0).
step2_main() ->
wf_test:start(fun step2_tests/0).
step3_main() ->
wf_test:start(fun step3_tests/0).
step4_main() ->
InitialCookieVal = wf_utils:guid(),
OtherCookieVal = wf_utils:guid(),
wf:session(test_cookie_val, InitialCookieVal),
wf:cookie(test_cookie_val, InitialCookieVal, [{http_only, true}]),
wf:cookie(other_test_cookie_val, OtherCookieVal),
wf_test:start(fun() -> step4_tests(OtherCookieVal) end).
step1_tests() ->
%% Verify that the cookie works
?wf_test_auto(get_cookie, get_cookie_test()),
%% Now we set to the cookie to something else. Being inside a websocket
connection , this will force the system to use the # set_cookie { } action
%% rather than writing a cookie header to the response (which wouldn't make
%% sense after the websocket handshake).
?wf_test_auto(set_cookie, set_cookie_test([])).
get_cookie_test() ->
{
undefined,
fun verify_cookie_fun/0
}.
get_cookie_js_test(Cookie, ExpectedVal) ->
{
undefined,
" cname='" ++ wf:to_list(Cookie) ++ "';
var name = cname + '=';
var ca = document.cookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length,c.length);
}
}
return '';",
fun([ActualVal]) ->
ActualVal==ExpectedVal
end
}.
set_cookie_test(Opts) ->
{
fun() ->
NewVal = wf_utils:guid(),
wf:cookie(test_cookie_val, NewVal, Opts),
wf:session(test_cookie_val, NewVal)
end,
undefined
}.
step2_tests() ->
%% Makes sure cookie value is retained across multiple requests
?wf_test_auto(get_cookie, get_cookie_test()),
?wf_test_auto(delete_cookie, delete_cookie_test()).
step3_tests() ->
?wf_test_auto(check_deleted_cookie, check_deleted_cookie()).
step4_tests(OtherVal) ->
%% The HTTP cookie was set before the websocket, and we're in an HTTP
%% Request, so it should "just work"
?wf_test_auto(http_only_get_cookie, get_cookie_test()),
%% The other_test_cookie_val was set in the normal fashion, and so should
%% be readable by javascript.
?wf_test_js(non_http_only_get_cookie_js, get_cookie_js_test(other_test_cookie_val, OtherVal)),
%% However, the normal test_cookie_val was set with http_only, so it should
%% *not* be readable by javascript.
?wf_test_js(http_only_get_cookie_js, get_cookie_js_test(test_cookie_val, "")).
%% FIXME: http_only cookies cannot be set in javascript. So wf:cookie
%% called in a websocket postback *must* generate a separate HTTP request
%% to do so. For now, we'll comment this out.
? wf_test_auto(http_only_set_cookie_in_postback , , true } ] ) ) ,
%% NOTE: We have to comment this next test out because of a shortcoming
%% with setting cookies in a websocket postback. And that is that cookies set
%% in a postback don't change the cookies for the existing websocket
%% connection. Meaning that, when a postback sets a cookie and in a later
postback attemps wf : cookie/1 , the value will still be the non - current
%% cookie.
%%
%% A potential fix for this would be to add something like
wf : defer("Nitrogen.$restart_websocket ( ) " ) to the # set_cookie { } action ,
%% thereby ensuring that if a cookie is set, a new websocket connection is
%% established with the new cookie values.
%?wf_test_auto(http_only_get_cookie_in_postback, get_cookie_test()).
delete_cookie_test() ->
{
fun() -> wf:delete_cookie(test_cookie_val) end,
undefined
}.
check_deleted_cookie() ->
{
undefined,
fun() -> wf:cookie(test_cookie_val) == undefined end
}.
verify_cookie_fun() ->
ExpectedCookie = wf:session(test_cookie_val),
ActualCookie = wf:cookie(test_cookie_val),
case ExpectedCookie == ActualCookie of
true -> true;
false -> false
end.
| null | https://raw.githubusercontent.com/nitrogen/NitrogenProject.com/b4b3a0dbe17394608d2ee6eaa089e3ece1285075/src/tests/tests_cookie.erl | erlang | Verify that the cookie works
Now we set to the cookie to something else. Being inside a websocket
rather than writing a cookie header to the response (which wouldn't make
sense after the websocket handshake).
Makes sure cookie value is retained across multiple requests
The HTTP cookie was set before the websocket, and we're in an HTTP
Request, so it should "just work"
The other_test_cookie_val was set in the normal fashion, and so should
be readable by javascript.
However, the normal test_cookie_val was set with http_only, so it should
*not* be readable by javascript.
FIXME: http_only cookies cannot be set in javascript. So wf:cookie
called in a websocket postback *must* generate a separate HTTP request
to do so. For now, we'll comment this out.
NOTE: We have to comment this next test out because of a shortcoming
with setting cookies in a websocket postback. And that is that cookies set
in a postback don't change the cookies for the existing websocket
connection. Meaning that, when a postback sets a cookie and in a later
cookie.
A potential fix for this would be to add something like
thereby ensuring that if a cookie is set, a new websocket connection is
established with the new cookie values.
?wf_test_auto(http_only_get_cookie_in_postback, get_cookie_test()). | -module(tests_cookie).
-include_lib("nitrogen_core/include/wf.hrl").
-compile(export_all).
main() ->
case wf:q("step") of
"1" -> step1_main();
"2" -> step2_main();
"3" -> step3_main();
"4" -> step4_main()
end,
#template{file="templates/grid.html"}.
step1_main() ->
InitialCookieVal = wf_utils:guid(),
wf:session(test_cookie_val, InitialCookieVal),
wf:cookie(test_cookie_val, InitialCookieVal),
wf_test:start(fun step1_tests/0).
step2_main() ->
wf_test:start(fun step2_tests/0).
step3_main() ->
wf_test:start(fun step3_tests/0).
step4_main() ->
InitialCookieVal = wf_utils:guid(),
OtherCookieVal = wf_utils:guid(),
wf:session(test_cookie_val, InitialCookieVal),
wf:cookie(test_cookie_val, InitialCookieVal, [{http_only, true}]),
wf:cookie(other_test_cookie_val, OtherCookieVal),
wf_test:start(fun() -> step4_tests(OtherCookieVal) end).
step1_tests() ->
?wf_test_auto(get_cookie, get_cookie_test()),
connection , this will force the system to use the # set_cookie { } action
?wf_test_auto(set_cookie, set_cookie_test([])).
get_cookie_test() ->
{
undefined,
fun verify_cookie_fun/0
}.
get_cookie_js_test(Cookie, ExpectedVal) ->
{
undefined,
" cname='" ++ wf:to_list(Cookie) ++ "';
var name = cname + '=';
var ca = document.cookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length,c.length);
}
}
return '';",
fun([ActualVal]) ->
ActualVal==ExpectedVal
end
}.
set_cookie_test(Opts) ->
{
fun() ->
NewVal = wf_utils:guid(),
wf:cookie(test_cookie_val, NewVal, Opts),
wf:session(test_cookie_val, NewVal)
end,
undefined
}.
step2_tests() ->
?wf_test_auto(get_cookie, get_cookie_test()),
?wf_test_auto(delete_cookie, delete_cookie_test()).
step3_tests() ->
?wf_test_auto(check_deleted_cookie, check_deleted_cookie()).
step4_tests(OtherVal) ->
?wf_test_auto(http_only_get_cookie, get_cookie_test()),
?wf_test_js(non_http_only_get_cookie_js, get_cookie_js_test(other_test_cookie_val, OtherVal)),
?wf_test_js(http_only_get_cookie_js, get_cookie_js_test(test_cookie_val, "")).
? wf_test_auto(http_only_set_cookie_in_postback , , true } ] ) ) ,
postback attemps wf : cookie/1 , the value will still be the non - current
wf : defer("Nitrogen.$restart_websocket ( ) " ) to the # set_cookie { } action ,
delete_cookie_test() ->
{
fun() -> wf:delete_cookie(test_cookie_val) end,
undefined
}.
check_deleted_cookie() ->
{
undefined,
fun() -> wf:cookie(test_cookie_val) == undefined end
}.
verify_cookie_fun() ->
ExpectedCookie = wf:session(test_cookie_val),
ActualCookie = wf:cookie(test_cookie_val),
case ExpectedCookie == ActualCookie of
true -> true;
false -> false
end.
|
6315f15649304accc39a500552bc3ad449e5230893a56a74776dfe0724a390c1 | shamazmazum/similar-images | find-similar-prob.lisp | (in-package :similar-images)
(defconstant +hash-length+ 1024
"Length of a perceptual hash (in bits)")
(defconstant +number-of-bins+ 4
"Number of sets of bins for classification.")
(defconstant +bin-width+ 11
"A set of bins will have 2^+bin-width+ bins.")
(defgenerator make-random-gen (max)
"Make a generator of integer random numbers in the range [0, MAX]
without repetitions. When all numbers are returned, this generator
will return NIL."
(loop
with list = (loop for x below max collect x)
while list
for random = (nth (random (length list)) list)
do
(setq list (delete random list))
(yield random)))
(defun make-bin-classifier (n &optional (rnd (make-random-gen +hash-length+)))
"Return bin classifier which designates a bit-vector to one of 2^N
bins. RND is a random number generator."
(declare (type basic-generator rnd))
(let ((random-bit-indices (take n rnd)))
(lambda (vector)
(declare (optimize (speed 3)))
(loop
with acc fixnum = 0
for idx in random-bit-indices
for bit = (sbit vector idx)
do (setq acc (logior (ash acc 1) bit))
finally (return acc)))))
(defun make-bins-and-classifiers (n m)
"Make N bin sets where each set has 2^M places. Also make
corresponding bin classifiers."
(loop
with rnd-gen = (make-random-gen +hash-length+)
repeat n
collect (cons (make-bin-classifier m rnd-gen)
(make-array (ash 1 m) :initial-element nil))))
(defun classify-vector (bins-and-classifiers element
&key (key #'identity))
"Put an ELEMENT to one bin of each bin set. Bin sets and classifiers
are specified in BINS-AND-CLASSIFIERS argument."
(declare (optimize (speed 3))
(type function key))
(dolist (bin-and-classifier bins-and-classifiers)
(destructuring-bind (classifier . bin)
bin-and-classifier
(declare (type function classifier)
(type simple-vector bin))
(let ((bin-idx (funcall classifier
(funcall key element))))
(push element (svref bin bin-idx)))))
bins-and-classifiers)
(defun find-close-prob (bins-and-classifiers element
&key (key #'identity))
"Search bins for all elements which are close enough to ELEMENT."
(declare (optimize (speed 3))
(type function key))
(let (similar)
(dolist (bin-and-classifier bins-and-classifiers)
(destructuring-bind (classifier . bin)
bin-and-classifier
(declare (type function classifier)
(type simple-vector bin))
(dolist (entry
(let ((bin-idx
(funcall classifier
(funcall key element))))
(svref bin bin-idx)))
(let ((distance (hamming-distance
(funcall key entry)
(funcall key element))))
(declare (type fixnum distance))
(if (and (not (eq entry element))
(<= distance *threshold*))
(pushnew entry similar
:test #'equal
:key #'car))))))
similar))
(define-search-function find-similar-prob (directory)
"Return a list of sets of similar images for images in
@c(directory). If @c(recursive) is @c(T), all subdirectories of
@c(directory) are also scanned for images. If @c(remove-errored) is
@c(T) the pictures which cannot be read are removed. @c(Threshold) is
a sensitivity of algorithm. The bigger the value is the more different
pictures are considered similar.
This is a faster version of @c(find-similar). This algorithm is
probabilistic which means that close images are found only with a
certain degree of probability, e.g. if a distance between images is
45, there is about 2% chance that they will not be recognized as
similar."
(let ((images-and-hashes (collect-hashes directory))
(bins (make-bins-and-classifiers +number-of-bins+
+bin-width+)))
(log:info "Searching for similar images")
(mapc
(lambda (image-and-hash)
(classify-vector bins image-and-hash :key #'cdr))
images-and-hashes)
(loop
for image-and-hash in images-and-hashes
for similar = (find-close-prob bins image-and-hash :key #'cdr)
when similar
collect (mapcar #'car (cons image-and-hash similar)) into similars
finally (return (remove-duplicates similars :test #'set-equal-p)))))
| null | https://raw.githubusercontent.com/shamazmazum/similar-images/e606e7c21dd56bcd6a2b53d209754eff6c65ad66/src/find-similar-prob.lisp | lisp | (in-package :similar-images)
(defconstant +hash-length+ 1024
"Length of a perceptual hash (in bits)")
(defconstant +number-of-bins+ 4
"Number of sets of bins for classification.")
(defconstant +bin-width+ 11
"A set of bins will have 2^+bin-width+ bins.")
(defgenerator make-random-gen (max)
"Make a generator of integer random numbers in the range [0, MAX]
without repetitions. When all numbers are returned, this generator
will return NIL."
(loop
with list = (loop for x below max collect x)
while list
for random = (nth (random (length list)) list)
do
(setq list (delete random list))
(yield random)))
(defun make-bin-classifier (n &optional (rnd (make-random-gen +hash-length+)))
"Return bin classifier which designates a bit-vector to one of 2^N
bins. RND is a random number generator."
(declare (type basic-generator rnd))
(let ((random-bit-indices (take n rnd)))
(lambda (vector)
(declare (optimize (speed 3)))
(loop
with acc fixnum = 0
for idx in random-bit-indices
for bit = (sbit vector idx)
do (setq acc (logior (ash acc 1) bit))
finally (return acc)))))
(defun make-bins-and-classifiers (n m)
"Make N bin sets where each set has 2^M places. Also make
corresponding bin classifiers."
(loop
with rnd-gen = (make-random-gen +hash-length+)
repeat n
collect (cons (make-bin-classifier m rnd-gen)
(make-array (ash 1 m) :initial-element nil))))
(defun classify-vector (bins-and-classifiers element
&key (key #'identity))
"Put an ELEMENT to one bin of each bin set. Bin sets and classifiers
are specified in BINS-AND-CLASSIFIERS argument."
(declare (optimize (speed 3))
(type function key))
(dolist (bin-and-classifier bins-and-classifiers)
(destructuring-bind (classifier . bin)
bin-and-classifier
(declare (type function classifier)
(type simple-vector bin))
(let ((bin-idx (funcall classifier
(funcall key element))))
(push element (svref bin bin-idx)))))
bins-and-classifiers)
(defun find-close-prob (bins-and-classifiers element
&key (key #'identity))
"Search bins for all elements which are close enough to ELEMENT."
(declare (optimize (speed 3))
(type function key))
(let (similar)
(dolist (bin-and-classifier bins-and-classifiers)
(destructuring-bind (classifier . bin)
bin-and-classifier
(declare (type function classifier)
(type simple-vector bin))
(dolist (entry
(let ((bin-idx
(funcall classifier
(funcall key element))))
(svref bin bin-idx)))
(let ((distance (hamming-distance
(funcall key entry)
(funcall key element))))
(declare (type fixnum distance))
(if (and (not (eq entry element))
(<= distance *threshold*))
(pushnew entry similar
:test #'equal
:key #'car))))))
similar))
(define-search-function find-similar-prob (directory)
"Return a list of sets of similar images for images in
@c(directory). If @c(recursive) is @c(T), all subdirectories of
@c(directory) are also scanned for images. If @c(remove-errored) is
@c(T) the pictures which cannot be read are removed. @c(Threshold) is
a sensitivity of algorithm. The bigger the value is the more different
pictures are considered similar.
This is a faster version of @c(find-similar). This algorithm is
probabilistic which means that close images are found only with a
certain degree of probability, e.g. if a distance between images is
45, there is about 2% chance that they will not be recognized as
similar."
(let ((images-and-hashes (collect-hashes directory))
(bins (make-bins-and-classifiers +number-of-bins+
+bin-width+)))
(log:info "Searching for similar images")
(mapc
(lambda (image-and-hash)
(classify-vector bins image-and-hash :key #'cdr))
images-and-hashes)
(loop
for image-and-hash in images-and-hashes
for similar = (find-close-prob bins image-and-hash :key #'cdr)
when similar
collect (mapcar #'car (cons image-and-hash similar)) into similars
finally (return (remove-duplicates similars :test #'set-equal-p)))))
| |
05d368e7db28bb290e3cedfb2aff9545faa129daed5e0c6fbf0044fc95dcf743 | metabase/metabase | setup_test.clj | (ns ^:mb/once metabase.api.setup-test
"Tests for /api/setup endpoints."
(:require
[clojure.core.async :as a]
[clojure.spec.alpha :as s]
[clojure.test :refer :all]
[medley.core :as m]
[metabase.analytics.snowplow-test :as snowplow-test]
[metabase.api.setup :as api.setup]
[metabase.email :as email]
[metabase.events :as events]
[metabase.http-client :as client]
[metabase.integrations.slack :as slack]
[metabase.models :refer [Activity Database Table User]]
[metabase.models.setting :as setting]
[metabase.models.setting.cache-test :as setting.cache-test]
[metabase.public-settings :as public-settings]
[metabase.setup :as setup]
[metabase.test :as mt]
[metabase.test.fixtures :as fixtures]
[metabase.util :as u]
[metabase.util.schema :as su]
[schema.core :as schema]
[toucan.db :as db]))
(set! *warn-on-reflection* true)
;; make sure the default test users are created before running these tests, otherwise we're going to run into issues
;; if it attempts to delete this user and it is the only admin test user
(use-fixtures :once (fixtures/initialize :test-users :events))
(defn- wait-for-result
"Call thunk up to 10 times, until it returns a truthy value. Wait 50ms between tries. Useful for waiting for something
asynchronous to happen."
[thunk]
(loop [tries 10]
(or (thunk)
(when (pos? tries)
(Thread/sleep 50)
(recur (dec tries))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | POST /setup |
;;; +----------------------------------------------------------------------------------------------------------------+
(defn- do-with-setup* [request-body thunk]
(try
(mt/discard-setting-changes [site-name site-locale anon-tracking-enabled admin-email]
(thunk))
(finally
(db/delete! User :email (get-in request-body [:user :email]))
(when-let [invited (get-in request-body [:invite :name])]
(db/delete! User :email invited))
(when-let [db-name (get-in request-body [:database :name])]
(db/delete! Database :name db-name)))))
(defn- default-setup-input []
{:token (setup/create-token!)
:prefs {:site_name "Metabase Test"}
:user {:first_name (mt/random-name)
:last_name (mt/random-name)
:email (mt/random-email)
:password "anythingUP12!!"}})
(defn- do-with-setup [request-body thunk]
(let [request-body (merge-with merge (default-setup-input) request-body)]
(do-with-setup*
request-body
(fn []
(with-redefs [api.setup/*allow-api-setup-after-first-user-is-created* true]
(testing "API response should return a Session UUID"
(is (schema= {:id (schema/pred mt/is-uuid-string? "UUID string")}
(client/client :post 200 "setup" request-body))))
;; reset our setup token
(setup/create-token!)
(thunk))))))
(defmacro ^:private with-setup [request-body & body]
`(do-with-setup ~request-body (fn [] ~@body)))
(deftest create-superuser-test
(testing "POST /api/setup"
(testing "Check that we can create a new superuser via setup-token"
(let [email (mt/random-email)]
(with-setup {:user {:email email}}
(testing "new User should be created"
(is (db/exists? User :email email)))
(testing "Creating a new admin user should set the `admin-email` Setting"
(is (= email
(public-settings/admin-email))))
(testing "Should record :user-joined Activity (#12933)"
(let [user-id (u/the-id (db/select-one-id User :email email))]
(is (schema= {:topic (schema/eq :user-joined)
:model_id (schema/eq user-id)
:user_id (schema/eq user-id)
:model (schema/eq "user")
schema/Keyword schema/Any}
(wait-for-result #(db/select-one Activity :topic "user-joined", :user_id user-id)))))))))))
(deftest invite-user-test
(testing "POST /api/setup"
(testing "Check that a second admin can be created during setup, and that an invite email is sent successfully and
a Snowplow analytics event is sent"
(mt/with-fake-inbox
(snowplow-test/with-fake-snowplow-collector
(let [email (mt/random-email)
first-name (mt/random-name)
last-name (mt/random-name)
invitor-first-name (mt/random-name)]
(with-setup {:invite {:email email, :first_name first-name, :last_name last-name}
:user {:first_name invitor-first-name}
:site_name "Metabase"}
(let [invited-user (db/select-one User :email email)]
(is (= (:first_name invited-user) first-name))
(is (= (:last_name invited-user) last-name))
(is (:is_superuser invited-user))
(is (partial= [{:data {"event" "invite_sent",
"invited_user_id" (u/the-id invited-user)
"source" "setup"}}]
(filter #(= (get-in % [:data "event"]) "invite_sent")
(snowplow-test/pop-event-data-and-user-id!))))
(is (mt/received-email-body?
email
(re-pattern (str invitor-first-name " could use your help setting up Metabase.*"))))))))))
(testing "No second user is created if email is not set up"
(mt/with-temporary-setting-values [email-smtp-host nil]
(let [email (mt/random-email)
first-name (mt/random-name)
last-name (mt/random-name)]
(with-setup {:invite {:email email, :first_name first-name, :last_name last-name}}
(is (not (db/exists? User :email email)))))))))
(deftest setup-settings-test
(testing "POST /api/setup"
(testing "check that we can set various Settings during setup"
(doseq [[setting-name {:keys [k vs]}] {:site-name
{:k "site_name"
:vs {"Cam's Metabase" "Cam's Metabase"}}
:anon-tracking-enabled
{:k "allow_tracking"
:vs {"TRUE" true
"true" true
true true
nil true
"FALSE" false
"false" false
false false}}
:site-locale
{:k "site_locale"
:vs {nil "en" ; `en` is the default
"es" "es"
"ES" "es"
"es-mx" "es_MX"
"es_MX" "es_MX"}}}
[v expected] vs]
(testing (format "Set Setting %s to %s" (pr-str setting-name) (pr-str v))
(with-setup {:prefs {k v}}
(testing "should be set"
(is (= expected
(setting/get setting-name))))))))))
(deftest create-database-test
(testing "POST /api/setup"
(testing "Check that we can Create a Database when we set up MB (#10135)"
(doseq [[k {:keys [default]}] {:is_on_demand {:default false}
:is_full_sync {:default true}
:auto_run_queries {:default true}}
v [true false nil]]
(let [db-name (mt/random-name)]
(with-setup {:database {:engine "h2"
:name db-name
:details {:db "file:/home/hansen/Downloads/Metabase/longnames.db",
:ssl true}
k v}}
(testing "Database should be created"
(is (= true
(db/exists? Database :name db-name))))
(testing (format "should be able to set %s to %s (default: %s) during creation" k (pr-str v) default)
(is (= (if (some? v) v default)
(db/select-one-field k Database :name db-name))))))))
(testing "Setup should trigger sync right away for the newly created Database (#12826)"
(let [db-name (mt/random-name)]
(mt/with-open-channels [chan (a/chan)]
(events/subscribe-to-topics! #{:database-create} chan)
(with-setup {:database {:engine "h2"
:name db-name
:details (:details (mt/db))}}
(testing ":database-create events should have been fired"
(is (schema= {:topic (schema/eq :database-create)
:item {:id su/IntGreaterThanZero
:name (schema/eq db-name)
schema/Keyword schema/Any}}
(mt/wait-for-result chan 100))))
(testing "Database should be synced"
(let [db (db/select-one Database :name db-name)]
(assert (some? db))
(is (= 4
(wait-for-result (fn []
(let [cnt (db/count Table :db_id (u/the-id db))]
(when (= cnt 4)
cnt))))))))))))
(testing "error conditions"
(testing "should throw Exception if driver is invalid"
(is (= {:errors {:database {:engine "Cannot create Database: cannot find driver my-fake-driver."}}}
(with-redefs [api.setup/*allow-api-setup-after-first-user-is-created* true]
(client/client :post 400 "setup" (assoc (default-setup-input)
:database {:engine "my-fake-driver"
:name (mt/random-name)
:details {}})))))))))
(s/def ::setup!-args
(s/cat :expected-status (s/? integer?)
:f any?
:args (s/* any?)))
(defn- setup!
{:arglists '([expected-status? f & args])}
[& args]
(let [parsed (s/conform ::setup!-args args)]
(when (= parsed ::s/invalid)
(throw (ex-info (str "Invalid setup! args: " (s/explain-str ::setup!-args args))
(s/explain-data ::setup!-args args))))
(let [{:keys [expected-status f args]} parsed
body {:token (setup/create-token!)
:prefs {:site_name "Metabase Test"}
:user {:first_name (mt/random-name)
:last_name (mt/random-name)
:email (mt/random-email)
:password "anythingUP12!!"}}
body (apply f body args)]
(do-with-setup* body #(client/client :post (or expected-status 400) "setup" body)))))
(deftest setup-validation-test
(testing "POST /api/setup validation"
(testing ":token"
(testing "missing"
(is (= {:errors {:token "Token does not match the setup token."}}
(setup! dissoc :token))))
(testing "incorrect"
(is (= {:errors {:token "Token does not match the setup token."}}
(setup! assoc :token "foobar")))))
(testing "site name"
(is (= {:errors {:site_name "value must be a non-blank string."}}
(setup! m/dissoc-in [:prefs :site_name]))))
(testing "site locale"
(testing "invalid format"
(is (schema= {:errors {:site_locale #".*must be a valid two-letter ISO language or language-country code.*"}}
(setup! assoc-in [:prefs :site_locale] "eng-USA"))))
(testing "non-existent locale"
(is (schema= {:errors {:site_locale #".*must be a valid two-letter ISO language or language-country code.*"}}
(setup! assoc-in [:prefs :site_locale] "en-EN")))))
(testing "user"
(with-redefs [api.setup/*allow-api-setup-after-first-user-is-created* true]
(testing "first name may be nil"
(is (:id (setup! 200 m/dissoc-in [:user :first_name])))
(is (:id (setup! 200 assoc-in [:user :first_name] nil))))
(testing "last name may be nil"
(is (:id (setup! 200 m/dissoc-in [:user :last_name])))
(is (:id (setup! 200 assoc-in [:user :last_name] nil)))))
(testing "email"
(testing "missing"
(is (= {:errors {:email "value must be a valid email address."}}
(setup! m/dissoc-in [:user :email]))))
(testing "invalid"
(is (= {:errors {:email "value must be a valid email address."}}
(setup! assoc-in [:user :email] "anything")))))
(testing "password"
(testing "missing"
(is (= {:errors {:password "password is too common."}}
(setup! m/dissoc-in [:user :password]))))
(testing "invalid"
(is (= {:errors {:password "password is too common."}}
(setup! assoc-in [:user :password] "anything"))))))))
(deftest setup-with-empty-cache-test
(testing "POST /api/setup"
;; I have seen this fail randomly, no idea why
(testing "Make sure setup completes successfully if Settings cache needs to be restored"
(setting.cache-test/reset-last-update-check!)
(setting.cache-test/clear-cache!)
(let [db-name (mt/random-name)]
(with-setup {:database {:engine "h2", :name db-name}}
(is (db/exists? Database :name db-name)))))))
(deftest has-user-setup-setting-test
(testing "has-user-setup is true iff there are 1 or more users"
(let [user-count (db/count User)]
(if (zero? user-count)
(is (not (setup/has-user-setup)))
(is (setup/has-user-setup))))))
(deftest create-superuser-only-once-test
(testing "POST /api/setup"
(testing "Check that we cannot create a new superuser via setup-token when a user exists"
(let [token (setup/create-token!)
body {:token token
:prefs {:site_locale "es_MX"
:site_name (mt/random-name)}
:user {:first_name (mt/random-name)
:last_name (mt/random-name)
:email (mt/random-email)
:password "p@ssword1"}}
has-user-setup (atom false)]
(with-redefs [setup/has-user-setup (fn [] @has-user-setup)]
(is (not (setup/has-user-setup)))
(mt/discard-setting-changes [site-name site-locale anon-tracking-enabled admin-email]
(is (schema= {:id client/UUIDString}
(client/client :post 200 "setup" body))))
In the non - test context , this is ' set ' iff there is one or more users , and does n't have to be toggled
(reset! has-user-setup true)
(is (setup/has-user-setup))
;; use do-with-setup* to delete the random user that was created
(do-with-setup* body
#(is (= "The /api/setup route can only be used to create the first user, however a user currently exists."
(client/client :post 403 "setup" (assoc-in body [:user :email] (mt/random-email)))))))))))
(deftest transaction-test
(testing "POST /api/setup/"
(testing "should run in a transaction -- if something fails, all changes should be rolled back"
(let [user-email (mt/random-email)
setup-token (setup/create-token!)
site-name (mt/random-name)
db-name (mt/random-name)
body {:token setup-token
:prefs {:site_locale "es_MX"
:site_name site-name}
:database {:engine "h2"
:name db-name}
:user {:first_name (mt/random-name)
:last_name (mt/random-name)
:email user-email
:password "p@ssword1"}}]
(do-with-setup*
body
(fn []
(with-redefs [api.setup/*allow-api-setup-after-first-user-is-created* true
api.setup/setup-set-settings! (let [orig @#'api.setup/setup-set-settings!]
(fn [& args]
(apply orig args)
(throw (ex-info "Oops!" {}))))]
(is (schema= {:message (schema/eq "Oops!"), schema/Keyword schema/Any}
(client/client :post 500 "setup" body))))
(testing "New user shouldn't exist"
(is (= false
(db/exists? User :email user-email))))
(testing "New DB shouldn't exist"
TODO -- we should also be deleting relevant sync tasks for the DB , but this does n't matter too much
;; for right now.
(is (= false
(db/exists? Database :engine "h2", :name db-name))))
(testing "Settings should not be changed"
(is (not= site-name
(public-settings/site-name)))
(is (= "en"
(public-settings/site-locale))))
(testing "Setup token should still be set"
(is (= setup-token
(setup/setup-token))))))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | POST /api/setup/validate |
;;; +----------------------------------------------------------------------------------------------------------------+
(deftest validate-setup-test
(testing "POST /api/setup/validate"
(testing "Should validate token"
(is (= {:errors {:token "Token does not match the setup token."}}
(client/client :post 400 "setup/validate" {})))
(is (= {:errors {:token "Token does not match the setup token."}}
(client/client :post 400 "setup/validate" {:token "foobar"})))
;; make sure we have a valid setup token
(setup/create-token!)
(is (= {:errors {:engine "value must be a valid database engine."}}
(client/client :post 400 "setup/validate" {:token (setup/setup-token)}))))
(testing "should validate that database connection works"
(is (= {:errors {:db "check your connection string"},
:message "Database cannot be found."}
(client/client :post 400 "setup/validate" {:token (setup/setup-token)
:details {:engine "h2"
:details {:db "file"}}}))))
(testing "should return 204 no content if everything is valid"
(is (= nil
(client/client :post 204 "setup/validate" {:token (setup/setup-token)
:details {:engine "h2"
:details (:details (mt/db))}}))))))
;;; +----------------------------------------------------------------------------------------------------------------+
| GET /api / setup / admin_checklist |
;;; +----------------------------------------------------------------------------------------------------------------+
;; basic sanity check
(deftest admin-checklist-test
(testing "GET /api/setup/admin_checklist"
(with-redefs [db/exists? (constantly true)
db/count (constantly 5)
email/email-configured? (constantly true)
slack/slack-configured? (constantly false)]
(is (= [{:name "Get connected"
:tasks [{:title "Add a database"
:completed true
:triggered true
:is_next_step false}
{:title "Set up email"
:completed true
:triggered true
:is_next_step false}
{:title "Set Slack credentials"
:completed false
:triggered true
:is_next_step true}
{:title "Invite team members"
:completed true
:triggered true
:is_next_step false}]}
{:name "Curate your data"
:tasks [{:title "Hide irrelevant tables"
:completed true
:triggered false
:is_next_step false}
{:title "Organize questions"
:completed true
:triggered false
:is_next_step false}
{:title "Create metrics"
:completed true
:triggered false
:is_next_step false}
{:title "Create segments"
:completed true
:triggered false
:is_next_step false}]}]
(for [{group-name :name, tasks :tasks} (mt/user-http-request :crowberto :get 200 "setup/admin_checklist")]
{:name (str group-name)
:tasks (for [task tasks]
(-> (select-keys task [:title :completed :triggered :is_next_step])
(update :title str)))}))))
(testing "require superusers"
(is (= "You don't have permissions to do that."
(mt/user-http-request :rasta :get 403 "setup/admin_checklist"))))))
(deftest user-defaults-test
(testing "with no user defaults configured"
(mt/with-temp-env-var-value [mb-user-defaults nil]
(is (= "Not found." (client/client :get "setup/user_defaults")))))
(testing "with defaults containing no token"
(mt/with-temp-env-var-value [mb-user-defaults "{}"]
(is (= "Not found." (client/client :get "setup/user_defaults")))))
(testing "with valid configuration"
(mt/with-temp-env-var-value [mb-user-defaults "{\"token\":\"123456\",\"email\":\"\"}"]
(testing "with mismatched token"
(is (= "You don't have permissions to do that." (client/client :get "setup/user_defaults?token=987654"))))
(testing "with valid token"
(is (= {:email ""} (client/client :get "setup/user_defaults?token=123456")))))))
| null | https://raw.githubusercontent.com/metabase/metabase/7e3048bf73f6cb7527579446166d054292166163/test/metabase/api/setup_test.clj | clojure | make sure the default test users are created before running these tests, otherwise we're going to run into issues
if it attempts to delete this user and it is the only admin test user
+----------------------------------------------------------------------------------------------------------------+
| POST /setup |
+----------------------------------------------------------------------------------------------------------------+
reset our setup token
`en` is the default
I have seen this fail randomly, no idea why
use do-with-setup* to delete the random user that was created
for right now.
+----------------------------------------------------------------------------------------------------------------+
| POST /api/setup/validate |
+----------------------------------------------------------------------------------------------------------------+
make sure we have a valid setup token
+----------------------------------------------------------------------------------------------------------------+
+----------------------------------------------------------------------------------------------------------------+
basic sanity check | (ns ^:mb/once metabase.api.setup-test
"Tests for /api/setup endpoints."
(:require
[clojure.core.async :as a]
[clojure.spec.alpha :as s]
[clojure.test :refer :all]
[medley.core :as m]
[metabase.analytics.snowplow-test :as snowplow-test]
[metabase.api.setup :as api.setup]
[metabase.email :as email]
[metabase.events :as events]
[metabase.http-client :as client]
[metabase.integrations.slack :as slack]
[metabase.models :refer [Activity Database Table User]]
[metabase.models.setting :as setting]
[metabase.models.setting.cache-test :as setting.cache-test]
[metabase.public-settings :as public-settings]
[metabase.setup :as setup]
[metabase.test :as mt]
[metabase.test.fixtures :as fixtures]
[metabase.util :as u]
[metabase.util.schema :as su]
[schema.core :as schema]
[toucan.db :as db]))
(set! *warn-on-reflection* true)
(use-fixtures :once (fixtures/initialize :test-users :events))
(defn- wait-for-result
"Call thunk up to 10 times, until it returns a truthy value. Wait 50ms between tries. Useful for waiting for something
asynchronous to happen."
[thunk]
(loop [tries 10]
(or (thunk)
(when (pos? tries)
(Thread/sleep 50)
(recur (dec tries))))))
(defn- do-with-setup* [request-body thunk]
(try
(mt/discard-setting-changes [site-name site-locale anon-tracking-enabled admin-email]
(thunk))
(finally
(db/delete! User :email (get-in request-body [:user :email]))
(when-let [invited (get-in request-body [:invite :name])]
(db/delete! User :email invited))
(when-let [db-name (get-in request-body [:database :name])]
(db/delete! Database :name db-name)))))
(defn- default-setup-input []
{:token (setup/create-token!)
:prefs {:site_name "Metabase Test"}
:user {:first_name (mt/random-name)
:last_name (mt/random-name)
:email (mt/random-email)
:password "anythingUP12!!"}})
(defn- do-with-setup [request-body thunk]
(let [request-body (merge-with merge (default-setup-input) request-body)]
(do-with-setup*
request-body
(fn []
(with-redefs [api.setup/*allow-api-setup-after-first-user-is-created* true]
(testing "API response should return a Session UUID"
(is (schema= {:id (schema/pred mt/is-uuid-string? "UUID string")}
(client/client :post 200 "setup" request-body))))
(setup/create-token!)
(thunk))))))
(defmacro ^:private with-setup [request-body & body]
`(do-with-setup ~request-body (fn [] ~@body)))
(deftest create-superuser-test
(testing "POST /api/setup"
(testing "Check that we can create a new superuser via setup-token"
(let [email (mt/random-email)]
(with-setup {:user {:email email}}
(testing "new User should be created"
(is (db/exists? User :email email)))
(testing "Creating a new admin user should set the `admin-email` Setting"
(is (= email
(public-settings/admin-email))))
(testing "Should record :user-joined Activity (#12933)"
(let [user-id (u/the-id (db/select-one-id User :email email))]
(is (schema= {:topic (schema/eq :user-joined)
:model_id (schema/eq user-id)
:user_id (schema/eq user-id)
:model (schema/eq "user")
schema/Keyword schema/Any}
(wait-for-result #(db/select-one Activity :topic "user-joined", :user_id user-id)))))))))))
(deftest invite-user-test
(testing "POST /api/setup"
(testing "Check that a second admin can be created during setup, and that an invite email is sent successfully and
a Snowplow analytics event is sent"
(mt/with-fake-inbox
(snowplow-test/with-fake-snowplow-collector
(let [email (mt/random-email)
first-name (mt/random-name)
last-name (mt/random-name)
invitor-first-name (mt/random-name)]
(with-setup {:invite {:email email, :first_name first-name, :last_name last-name}
:user {:first_name invitor-first-name}
:site_name "Metabase"}
(let [invited-user (db/select-one User :email email)]
(is (= (:first_name invited-user) first-name))
(is (= (:last_name invited-user) last-name))
(is (:is_superuser invited-user))
(is (partial= [{:data {"event" "invite_sent",
"invited_user_id" (u/the-id invited-user)
"source" "setup"}}]
(filter #(= (get-in % [:data "event"]) "invite_sent")
(snowplow-test/pop-event-data-and-user-id!))))
(is (mt/received-email-body?
email
(re-pattern (str invitor-first-name " could use your help setting up Metabase.*"))))))))))
(testing "No second user is created if email is not set up"
(mt/with-temporary-setting-values [email-smtp-host nil]
(let [email (mt/random-email)
first-name (mt/random-name)
last-name (mt/random-name)]
(with-setup {:invite {:email email, :first_name first-name, :last_name last-name}}
(is (not (db/exists? User :email email)))))))))
(deftest setup-settings-test
(testing "POST /api/setup"
(testing "check that we can set various Settings during setup"
(doseq [[setting-name {:keys [k vs]}] {:site-name
{:k "site_name"
:vs {"Cam's Metabase" "Cam's Metabase"}}
:anon-tracking-enabled
{:k "allow_tracking"
:vs {"TRUE" true
"true" true
true true
nil true
"FALSE" false
"false" false
false false}}
:site-locale
{:k "site_locale"
"es" "es"
"ES" "es"
"es-mx" "es_MX"
"es_MX" "es_MX"}}}
[v expected] vs]
(testing (format "Set Setting %s to %s" (pr-str setting-name) (pr-str v))
(with-setup {:prefs {k v}}
(testing "should be set"
(is (= expected
(setting/get setting-name))))))))))
(deftest create-database-test
(testing "POST /api/setup"
(testing "Check that we can Create a Database when we set up MB (#10135)"
(doseq [[k {:keys [default]}] {:is_on_demand {:default false}
:is_full_sync {:default true}
:auto_run_queries {:default true}}
v [true false nil]]
(let [db-name (mt/random-name)]
(with-setup {:database {:engine "h2"
:name db-name
:details {:db "file:/home/hansen/Downloads/Metabase/longnames.db",
:ssl true}
k v}}
(testing "Database should be created"
(is (= true
(db/exists? Database :name db-name))))
(testing (format "should be able to set %s to %s (default: %s) during creation" k (pr-str v) default)
(is (= (if (some? v) v default)
(db/select-one-field k Database :name db-name))))))))
(testing "Setup should trigger sync right away for the newly created Database (#12826)"
(let [db-name (mt/random-name)]
(mt/with-open-channels [chan (a/chan)]
(events/subscribe-to-topics! #{:database-create} chan)
(with-setup {:database {:engine "h2"
:name db-name
:details (:details (mt/db))}}
(testing ":database-create events should have been fired"
(is (schema= {:topic (schema/eq :database-create)
:item {:id su/IntGreaterThanZero
:name (schema/eq db-name)
schema/Keyword schema/Any}}
(mt/wait-for-result chan 100))))
(testing "Database should be synced"
(let [db (db/select-one Database :name db-name)]
(assert (some? db))
(is (= 4
(wait-for-result (fn []
(let [cnt (db/count Table :db_id (u/the-id db))]
(when (= cnt 4)
cnt))))))))))))
(testing "error conditions"
(testing "should throw Exception if driver is invalid"
(is (= {:errors {:database {:engine "Cannot create Database: cannot find driver my-fake-driver."}}}
(with-redefs [api.setup/*allow-api-setup-after-first-user-is-created* true]
(client/client :post 400 "setup" (assoc (default-setup-input)
:database {:engine "my-fake-driver"
:name (mt/random-name)
:details {}})))))))))
(s/def ::setup!-args
(s/cat :expected-status (s/? integer?)
:f any?
:args (s/* any?)))
(defn- setup!
{:arglists '([expected-status? f & args])}
[& args]
(let [parsed (s/conform ::setup!-args args)]
(when (= parsed ::s/invalid)
(throw (ex-info (str "Invalid setup! args: " (s/explain-str ::setup!-args args))
(s/explain-data ::setup!-args args))))
(let [{:keys [expected-status f args]} parsed
body {:token (setup/create-token!)
:prefs {:site_name "Metabase Test"}
:user {:first_name (mt/random-name)
:last_name (mt/random-name)
:email (mt/random-email)
:password "anythingUP12!!"}}
body (apply f body args)]
(do-with-setup* body #(client/client :post (or expected-status 400) "setup" body)))))
(deftest setup-validation-test
(testing "POST /api/setup validation"
(testing ":token"
(testing "missing"
(is (= {:errors {:token "Token does not match the setup token."}}
(setup! dissoc :token))))
(testing "incorrect"
(is (= {:errors {:token "Token does not match the setup token."}}
(setup! assoc :token "foobar")))))
(testing "site name"
(is (= {:errors {:site_name "value must be a non-blank string."}}
(setup! m/dissoc-in [:prefs :site_name]))))
(testing "site locale"
(testing "invalid format"
(is (schema= {:errors {:site_locale #".*must be a valid two-letter ISO language or language-country code.*"}}
(setup! assoc-in [:prefs :site_locale] "eng-USA"))))
(testing "non-existent locale"
(is (schema= {:errors {:site_locale #".*must be a valid two-letter ISO language or language-country code.*"}}
(setup! assoc-in [:prefs :site_locale] "en-EN")))))
(testing "user"
(with-redefs [api.setup/*allow-api-setup-after-first-user-is-created* true]
(testing "first name may be nil"
(is (:id (setup! 200 m/dissoc-in [:user :first_name])))
(is (:id (setup! 200 assoc-in [:user :first_name] nil))))
(testing "last name may be nil"
(is (:id (setup! 200 m/dissoc-in [:user :last_name])))
(is (:id (setup! 200 assoc-in [:user :last_name] nil)))))
(testing "email"
(testing "missing"
(is (= {:errors {:email "value must be a valid email address."}}
(setup! m/dissoc-in [:user :email]))))
(testing "invalid"
(is (= {:errors {:email "value must be a valid email address."}}
(setup! assoc-in [:user :email] "anything")))))
(testing "password"
(testing "missing"
(is (= {:errors {:password "password is too common."}}
(setup! m/dissoc-in [:user :password]))))
(testing "invalid"
(is (= {:errors {:password "password is too common."}}
(setup! assoc-in [:user :password] "anything"))))))))
(deftest setup-with-empty-cache-test
(testing "POST /api/setup"
(testing "Make sure setup completes successfully if Settings cache needs to be restored"
(setting.cache-test/reset-last-update-check!)
(setting.cache-test/clear-cache!)
(let [db-name (mt/random-name)]
(with-setup {:database {:engine "h2", :name db-name}}
(is (db/exists? Database :name db-name)))))))
(deftest has-user-setup-setting-test
(testing "has-user-setup is true iff there are 1 or more users"
(let [user-count (db/count User)]
(if (zero? user-count)
(is (not (setup/has-user-setup)))
(is (setup/has-user-setup))))))
(deftest create-superuser-only-once-test
(testing "POST /api/setup"
(testing "Check that we cannot create a new superuser via setup-token when a user exists"
(let [token (setup/create-token!)
body {:token token
:prefs {:site_locale "es_MX"
:site_name (mt/random-name)}
:user {:first_name (mt/random-name)
:last_name (mt/random-name)
:email (mt/random-email)
:password "p@ssword1"}}
has-user-setup (atom false)]
(with-redefs [setup/has-user-setup (fn [] @has-user-setup)]
(is (not (setup/has-user-setup)))
(mt/discard-setting-changes [site-name site-locale anon-tracking-enabled admin-email]
(is (schema= {:id client/UUIDString}
(client/client :post 200 "setup" body))))
In the non - test context , this is ' set ' iff there is one or more users , and does n't have to be toggled
(reset! has-user-setup true)
(is (setup/has-user-setup))
(do-with-setup* body
#(is (= "The /api/setup route can only be used to create the first user, however a user currently exists."
(client/client :post 403 "setup" (assoc-in body [:user :email] (mt/random-email)))))))))))
(deftest transaction-test
(testing "POST /api/setup/"
(testing "should run in a transaction -- if something fails, all changes should be rolled back"
(let [user-email (mt/random-email)
setup-token (setup/create-token!)
site-name (mt/random-name)
db-name (mt/random-name)
body {:token setup-token
:prefs {:site_locale "es_MX"
:site_name site-name}
:database {:engine "h2"
:name db-name}
:user {:first_name (mt/random-name)
:last_name (mt/random-name)
:email user-email
:password "p@ssword1"}}]
(do-with-setup*
body
(fn []
(with-redefs [api.setup/*allow-api-setup-after-first-user-is-created* true
api.setup/setup-set-settings! (let [orig @#'api.setup/setup-set-settings!]
(fn [& args]
(apply orig args)
(throw (ex-info "Oops!" {}))))]
(is (schema= {:message (schema/eq "Oops!"), schema/Keyword schema/Any}
(client/client :post 500 "setup" body))))
(testing "New user shouldn't exist"
(is (= false
(db/exists? User :email user-email))))
(testing "New DB shouldn't exist"
TODO -- we should also be deleting relevant sync tasks for the DB , but this does n't matter too much
(is (= false
(db/exists? Database :engine "h2", :name db-name))))
(testing "Settings should not be changed"
(is (not= site-name
(public-settings/site-name)))
(is (= "en"
(public-settings/site-locale))))
(testing "Setup token should still be set"
(is (= setup-token
(setup/setup-token))))))))))
(deftest validate-setup-test
(testing "POST /api/setup/validate"
(testing "Should validate token"
(is (= {:errors {:token "Token does not match the setup token."}}
(client/client :post 400 "setup/validate" {})))
(is (= {:errors {:token "Token does not match the setup token."}}
(client/client :post 400 "setup/validate" {:token "foobar"})))
(setup/create-token!)
(is (= {:errors {:engine "value must be a valid database engine."}}
(client/client :post 400 "setup/validate" {:token (setup/setup-token)}))))
(testing "should validate that database connection works"
(is (= {:errors {:db "check your connection string"},
:message "Database cannot be found."}
(client/client :post 400 "setup/validate" {:token (setup/setup-token)
:details {:engine "h2"
:details {:db "file"}}}))))
(testing "should return 204 no content if everything is valid"
(is (= nil
(client/client :post 204 "setup/validate" {:token (setup/setup-token)
:details {:engine "h2"
:details (:details (mt/db))}}))))))
| GET /api / setup / admin_checklist |
(deftest admin-checklist-test
(testing "GET /api/setup/admin_checklist"
(with-redefs [db/exists? (constantly true)
db/count (constantly 5)
email/email-configured? (constantly true)
slack/slack-configured? (constantly false)]
(is (= [{:name "Get connected"
:tasks [{:title "Add a database"
:completed true
:triggered true
:is_next_step false}
{:title "Set up email"
:completed true
:triggered true
:is_next_step false}
{:title "Set Slack credentials"
:completed false
:triggered true
:is_next_step true}
{:title "Invite team members"
:completed true
:triggered true
:is_next_step false}]}
{:name "Curate your data"
:tasks [{:title "Hide irrelevant tables"
:completed true
:triggered false
:is_next_step false}
{:title "Organize questions"
:completed true
:triggered false
:is_next_step false}
{:title "Create metrics"
:completed true
:triggered false
:is_next_step false}
{:title "Create segments"
:completed true
:triggered false
:is_next_step false}]}]
(for [{group-name :name, tasks :tasks} (mt/user-http-request :crowberto :get 200 "setup/admin_checklist")]
{:name (str group-name)
:tasks (for [task tasks]
(-> (select-keys task [:title :completed :triggered :is_next_step])
(update :title str)))}))))
(testing "require superusers"
(is (= "You don't have permissions to do that."
(mt/user-http-request :rasta :get 403 "setup/admin_checklist"))))))
(deftest user-defaults-test
(testing "with no user defaults configured"
(mt/with-temp-env-var-value [mb-user-defaults nil]
(is (= "Not found." (client/client :get "setup/user_defaults")))))
(testing "with defaults containing no token"
(mt/with-temp-env-var-value [mb-user-defaults "{}"]
(is (= "Not found." (client/client :get "setup/user_defaults")))))
(testing "with valid configuration"
(mt/with-temp-env-var-value [mb-user-defaults "{\"token\":\"123456\",\"email\":\"\"}"]
(testing "with mismatched token"
(is (= "You don't have permissions to do that." (client/client :get "setup/user_defaults?token=987654"))))
(testing "with valid token"
(is (= {:email ""} (client/client :get "setup/user_defaults?token=123456")))))))
|
0195367cedd50da4a46461b5b64bff034f881b06fdd5eff323572a74e06b6bb0 | binaryage/chromex | omnibox.clj | (ns chromex.ext.omnibox
"The omnibox API allows you to register a keyword with Google Chrome's address bar, which is also known as the omnibox.
* available since Chrome 36
* "
(:refer-clojure :only [defmacro defn apply declare meta let partial])
(:require [chromex.wrapgen :refer [gen-wrap-helper]]
[chromex.callgen :refer [gen-call-helper gen-tap-all-events-call]]))
(declare api-table)
(declare gen-call)
-- functions --------------------------------------------------------------------------------------------------------------
(defmacro set-default-suggestion
"Sets the description and styling for the default suggestion. The default suggestion is the text that is displayed in the
first suggestion row underneath the URL bar.
|suggestion| - A partial SuggestResult object, without the 'content' parameter.
#method-setDefaultSuggestion."
([suggestion] (gen-call :function ::set-default-suggestion &form suggestion)))
; -- events -----------------------------------------------------------------------------------------------------------------
;
; docs: /#tapping-events
(defmacro tap-on-input-started-events
"User has started a keyword input session by typing the extension's keyword. This is guaranteed to be sent exactly once per
input session, and before any onInputChanged events.
Events will be put on the |channel| with signature [::on-input-started []].
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onInputStarted."
([channel & args] (apply gen-call :event ::on-input-started &form channel args)))
(defmacro tap-on-input-changed-events
"User has changed what is typed into the omnibox.
Events will be put on the |channel| with signature [::on-input-changed [text suggest]] where:
|text| - #property-onInputChanged-text.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onInputChanged."
([channel & args] (apply gen-call :event ::on-input-changed &form channel args)))
(defmacro tap-on-input-entered-events
"User has accepted what is typed into the omnibox.
Events will be put on the |channel| with signature [::on-input-entered [text disposition]] where:
|text| - #property-onInputEntered-text.
|disposition| - #property-onInputEntered-disposition.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onInputEntered."
([channel & args] (apply gen-call :event ::on-input-entered &form channel args)))
(defmacro tap-on-input-cancelled-events
"User has ended the keyword input session without accepting the input.
Events will be put on the |channel| with signature [::on-input-cancelled []].
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onInputCancelled."
([channel & args] (apply gen-call :event ::on-input-cancelled &form channel args)))
(defmacro tap-on-delete-suggestion-events
"User has deleted a suggested result.
Events will be put on the |channel| with signature [::on-delete-suggestion [text]] where:
|text| - Text of the deleted suggestion.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onDeleteSuggestion."
([channel & args] (apply gen-call :event ::on-delete-suggestion &form channel args)))
; -- convenience ------------------------------------------------------------------------------------------------------------
(defmacro tap-all-events
"Taps all valid non-deprecated events in chromex.ext.omnibox namespace."
[chan]
(gen-tap-all-events-call api-table (meta &form) chan))
; ---------------------------------------------------------------------------------------------------------------------------
; -- API TABLE --------------------------------------------------------------------------------------------------------------
; ---------------------------------------------------------------------------------------------------------------------------
(def api-table
{:namespace "chrome.omnibox",
:since "36",
:functions
[{:id ::set-default-suggestion, :name "setDefaultSuggestion", :params [{:name "suggestion", :type "object"}]}],
:events
[{:id ::on-input-started, :name "onInputStarted"}
{:id ::on-input-changed,
:name "onInputChanged",
:params [{:name "text", :type "string"} {:name "suggest", :type :callback}]}
{:id ::on-input-entered,
:name "onInputEntered",
:params [{:name "text", :type "string"} {:name "disposition", :type "omnibox.OnInputEnteredDisposition"}]}
{:id ::on-input-cancelled, :name "onInputCancelled"}
{:id ::on-delete-suggestion, :name "onDeleteSuggestion", :since "63", :params [{:name "text", :type "string"}]}]})
; -- helpers ----------------------------------------------------------------------------------------------------------------
; code generation for native API wrapper
(defmacro gen-wrap [kind item-id config & args]
(apply gen-wrap-helper api-table kind item-id config args))
; code generation for API call-site
(def gen-call (partial gen-call-helper api-table)) | null | https://raw.githubusercontent.com/binaryage/chromex/33834ba5dd4f4238a3c51f99caa0416f30c308c5/src/exts/chromex/ext/omnibox.clj | clojure | -- events -----------------------------------------------------------------------------------------------------------------
docs: /#tapping-events
-- convenience ------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------
-- API TABLE --------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------
-- helpers ----------------------------------------------------------------------------------------------------------------
code generation for native API wrapper
code generation for API call-site | (ns chromex.ext.omnibox
"The omnibox API allows you to register a keyword with Google Chrome's address bar, which is also known as the omnibox.
* available since Chrome 36
* "
(:refer-clojure :only [defmacro defn apply declare meta let partial])
(:require [chromex.wrapgen :refer [gen-wrap-helper]]
[chromex.callgen :refer [gen-call-helper gen-tap-all-events-call]]))
(declare api-table)
(declare gen-call)
-- functions --------------------------------------------------------------------------------------------------------------
(defmacro set-default-suggestion
"Sets the description and styling for the default suggestion. The default suggestion is the text that is displayed in the
first suggestion row underneath the URL bar.
|suggestion| - A partial SuggestResult object, without the 'content' parameter.
#method-setDefaultSuggestion."
([suggestion] (gen-call :function ::set-default-suggestion &form suggestion)))
(defmacro tap-on-input-started-events
"User has started a keyword input session by typing the extension's keyword. This is guaranteed to be sent exactly once per
input session, and before any onInputChanged events.
Events will be put on the |channel| with signature [::on-input-started []].
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onInputStarted."
([channel & args] (apply gen-call :event ::on-input-started &form channel args)))
(defmacro tap-on-input-changed-events
"User has changed what is typed into the omnibox.
Events will be put on the |channel| with signature [::on-input-changed [text suggest]] where:
|text| - #property-onInputChanged-text.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onInputChanged."
([channel & args] (apply gen-call :event ::on-input-changed &form channel args)))
(defmacro tap-on-input-entered-events
"User has accepted what is typed into the omnibox.
Events will be put on the |channel| with signature [::on-input-entered [text disposition]] where:
|text| - #property-onInputEntered-text.
|disposition| - #property-onInputEntered-disposition.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onInputEntered."
([channel & args] (apply gen-call :event ::on-input-entered &form channel args)))
(defmacro tap-on-input-cancelled-events
"User has ended the keyword input session without accepting the input.
Events will be put on the |channel| with signature [::on-input-cancelled []].
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onInputCancelled."
([channel & args] (apply gen-call :event ::on-input-cancelled &form channel args)))
(defmacro tap-on-delete-suggestion-events
"User has deleted a suggested result.
Events will be put on the |channel| with signature [::on-delete-suggestion [text]] where:
|text| - Text of the deleted suggestion.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onDeleteSuggestion."
([channel & args] (apply gen-call :event ::on-delete-suggestion &form channel args)))
(defmacro tap-all-events
"Taps all valid non-deprecated events in chromex.ext.omnibox namespace."
[chan]
(gen-tap-all-events-call api-table (meta &form) chan))
(def api-table
{:namespace "chrome.omnibox",
:since "36",
:functions
[{:id ::set-default-suggestion, :name "setDefaultSuggestion", :params [{:name "suggestion", :type "object"}]}],
:events
[{:id ::on-input-started, :name "onInputStarted"}
{:id ::on-input-changed,
:name "onInputChanged",
:params [{:name "text", :type "string"} {:name "suggest", :type :callback}]}
{:id ::on-input-entered,
:name "onInputEntered",
:params [{:name "text", :type "string"} {:name "disposition", :type "omnibox.OnInputEnteredDisposition"}]}
{:id ::on-input-cancelled, :name "onInputCancelled"}
{:id ::on-delete-suggestion, :name "onDeleteSuggestion", :since "63", :params [{:name "text", :type "string"}]}]})
(defmacro gen-wrap [kind item-id config & args]
(apply gen-wrap-helper api-table kind item-id config args))
(def gen-call (partial gen-call-helper api-table)) |
e24b09e4f664307d3ef5a4750cab6778928628b5eaf73ba7b5fcffc2dc6bd2ad | LaurentMazare/ocaml-dataframe | bool_array.mli | (* Immutable bool array. *)
type t
val create : bool -> len:int -> t
val get : t -> int -> bool
(* The number of elements of the array set to true. *)
val num_set : t -> int
(* The indexes for a given value. *)
val indexes : t -> value:bool -> int array
val length : t -> int
val mapi : t -> f:(int -> bool -> bool) -> t
val iteri : t -> f:(int -> bool -> unit) -> unit
module Mutable : sig
type immutable = t
type t
val create : bool -> len:int -> t
val get : t -> int -> bool
val set : t -> int -> bool -> unit
val length : t -> int
val finish : t -> immutable
end
| null | https://raw.githubusercontent.com/LaurentMazare/ocaml-dataframe/89bd3cb4035db505ac516303b04f4de7ffdff0be/src/dataframe/bool_array.mli | ocaml | Immutable bool array.
The number of elements of the array set to true.
The indexes for a given value. | type t
val create : bool -> len:int -> t
val get : t -> int -> bool
val num_set : t -> int
val indexes : t -> value:bool -> int array
val length : t -> int
val mapi : t -> f:(int -> bool -> bool) -> t
val iteri : t -> f:(int -> bool -> unit) -> unit
module Mutable : sig
type immutable = t
type t
val create : bool -> len:int -> t
val get : t -> int -> bool
val set : t -> int -> bool -> unit
val length : t -> int
val finish : t -> immutable
end
|
b83941776f4bb3c46a47b7ad92a09bd10b593d8235d1c44ecd2963e7ed234868 | z3z1ma/pipette | project.clj | (defproject pipette "0.4.5"
:description "Engine for processing new line delimited json emitted to stdout and sent via a pipe"
: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.3"]
[org.clojure/data.json "2.4.0"]
[org.clojure/java.jdbc "0.7.12"]
[org.clojure/tools.cli "1.0.206"]
[org.postgresql/postgresql "42.3.1"]
[com.github.seancorfield/next.jdbc "1.2.761"]
[com.github.seancorfield/honeysql "2.2.840"]
[io.forward/yaml "1.0.11"]
[metosin/jsonista "0.3.5"]]
:main pipette.core
:aot [pipette.core]
:uberjar-name "pipette.jar"
:repl-options {:init-ns pipette.core}
:profiles {:dev {:uberjar {:aot :all
:jvm-opts ["-Dclojure.compiler.direct-linking=true"]}
:plugins [[lein-shell "0.5.0"]
[autodoc/lein-autodoc "1.1.1"]
[autodoc "1.1.1"]]}}
:aliases {"native" ["shell"
"native-image"
"-jar" "./target/pipette.jar}"
"-H:Name=./target/pipette"]})
| null | https://raw.githubusercontent.com/z3z1ma/pipette/bf01b61c563a2f54e3688bf8579ef62ac22fbf9d/project.clj | clojure | (defproject pipette "0.4.5"
:description "Engine for processing new line delimited json emitted to stdout and sent via a pipe"
: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.3"]
[org.clojure/data.json "2.4.0"]
[org.clojure/java.jdbc "0.7.12"]
[org.clojure/tools.cli "1.0.206"]
[org.postgresql/postgresql "42.3.1"]
[com.github.seancorfield/next.jdbc "1.2.761"]
[com.github.seancorfield/honeysql "2.2.840"]
[io.forward/yaml "1.0.11"]
[metosin/jsonista "0.3.5"]]
:main pipette.core
:aot [pipette.core]
:uberjar-name "pipette.jar"
:repl-options {:init-ns pipette.core}
:profiles {:dev {:uberjar {:aot :all
:jvm-opts ["-Dclojure.compiler.direct-linking=true"]}
:plugins [[lein-shell "0.5.0"]
[autodoc/lein-autodoc "1.1.1"]
[autodoc "1.1.1"]]}}
:aliases {"native" ["shell"
"native-image"
"-jar" "./target/pipette.jar}"
"-H:Name=./target/pipette"]})
| |
f4d4907a48dff910b3e31d7227c415d7d7652d4b4477f56d0014f4fb568640c1 | linkfluence/inventory | inventory.clj | (ns com.linkfluence.inventory.api.inventory
(:require [compojure.core :refer :all]
[compojure.route :as route]
[clojure.tools.logging :as log]
;;import inventory handler
[com.linkfluence.inventory.core :as inventory]
[com.linkfluence.utils :as u]))
(defn put-events
([evs]
(put-events evs "Operation submitted"))
([evs msg]
(if-not (inventory/ro?)
(do
(doseq [ev evs]
(inventory/add-inventory-event ev))
(u/mk-resp 202 "success" {} msg))
(u/mk-resp 403 "error" {} "Read Only"))))
(defn put-event
([ev]
(put-event ev "Operation submitted"))
([ev msg]
(if-not (inventory/ro?)
(do
(inventory/add-inventory-event ev)
(u/mk-resp 202 "success" {} msg))
(u/mk-resp 403 "error" {} "Read Only"))))
(defn hide-event
[id hide type]
(if-not (inventory/ro?)
(if-let [resource (inventory/get-resource (keyword id) true)]
(do
(inventory/hide-event id hide type)
(u/mk-resp 202 "success" {} "hidden flag updated"))
(u/mk-resp 404 "error" {} "Resource not found"))
(u/mk-resp 403 "error" {} "Read Only")))
(defroutes INVENTORY
(GET "/fsync" [] (do
(future
(inventory/load-inventory)
(log/info "[FSYNC] received inventory update notfication"))
(u/mk-resp 202 "success" {} "Fsync submitted")))
(POST "/event" [event] (put-event event))
(POST "/events" [events] (put-events events))
;;view
(GET "/view" [] (u/mk-resp 200 "success" {:data (inventory/list-views)}))
(GET "/view/:id" [id] (if-let [view (inventory/get-view (keyword id))]
(u/mk-resp 200 "success" {:data view})
(u/mk-resp 404 "error" {} "Group not found")))
;;group
(GET "/group" [] (u/mk-resp 200 "success" {:data (inventory/list-groups)}))
(GET "/group/:id" [id] (if-let [group (inventory/get-group (keyword id))]
(u/mk-resp 200 "success" {:data group})
(u/mk-resp 404 "error" {} "Group not found")))
(DELETE "/group/:id" [id] (if-let [group (inventory/get-group (keyword id))]
(put-event {:type "group" :id (keyword id) :tags [] :delete true} "Deletion submitted")
(u/mk-resp 404 "error" {} "Group not found, deletion aborted")))
(POST "/group/:id/addtags" [id tags] (if (inventory/validate-tags tags)
(put-event {:type "group" :id (keyword id) :tags tags})
(u/mk-resp 400 "error" {:explanation (inventory/explain-tags tags)} "tag array is invalid")))
(POST "/group/:id/addresources" [id resources] (do (inventory/add-inventory-event {:type "group" :id (keyword id) :resources resources})
(u/mk-resp 200 "success" {} "Operation submitted")))
;;resource
(GET "/resource" [with-alias] (u/mk-resp 200 "success" {:data (inventory/get-resources [] with-alias)}))
(GET "/alias" [] (u/mk-resp 200 "success" {:data (inventory/get-aliases [])}))
(DELETE "/resource/:id" [id] (put-event {:type "resource" :id (keyword id) :delete true} "Deletion submitted"))
(DELETE "/alias/:id" [id] (put-event {:type "alias" :id (keyword id) :delete true} "Deletion submitted"))
(POST "/resource" [tags with-alias] (u/mk-resp 200 "success" {:data (inventory/get-resources tags with-alias)}))
(POST "/alias" [tags] (u/mk-resp 200 "success" {:data (inventory/get-aliases tags)}))
(POST "/exists/alias" [resource-id from-resource tags] (u/mk-resp 200 "success" {:data (inventory/alias-exists? resource-id from-resource tags)}))
(GET "/resource/:id" [id with-alias] (if-let [resource (inventory/get-resource (keyword id) with-alias)]
(u/mk-resp 200 "success" {:data resource})
(u/mk-resp 404 "error" {} "Resource not found")))
(GET "/resource/:id/aliases" [id] (u/mk-resp 200 "success" {:data (inventory/get-resource-aliases (keyword id))}))
(GET "/alias/:id" [id] (if-let [alias (inventory/get-alias (keyword id))]
(u/mk-resp 200 "success" {:data alias})
(u/mk-resp 404 "error" {} "Resource not found")))
(POST "/resource/:id/addtags" [id tags] (if (some? (inventory/get-resource (keyword id) false))
(if (inventory/validate-tags tags)
(put-event {:type "resource" :id (keyword id) :tags tags})
(u/mk-resp 400 "error" {:explanation (inventory/explain-tags tags)} "tag array is invalid"))
(u/mk-resp 404 "error" {} "Cannot add tags to non existent resource")))
(POST "/alias/:id/addtags" [id tags] (if (some? (inventory/get-alias (keyword id)))
(if (inventory/validate-tags tags)
(put-event {:type "alias" :id (keyword id) :tags tags})
(u/mk-resp 400 "error" {:explanation (inventory/explain-tags tags)} "tag array is invalid"))
(u/mk-resp 404 "error" {} "Cannot add tags to non existent alias")))
;;Resource hiding
(GET "/hidden/resource" [] (u/mk-resp 200 "success" {:data (inventory/get-hidden-resources)}))
(POST "/hidden/resource" [tags] (u/mk-resp 200 "success" {:data (inventory/get-hidden-resources tags)}))
(POST "/hide/resource/:id" [id] (hide-event id true "resource"))
(POST "/unhide/resource/:id" [id] (hide-event id false "resource"))
;;Resource hiding
(GET "/hidden/alias" [] (u/mk-resp 200 "success" {:data (inventory/get-hidden-aliases)}))
(POST "/hidden/alias" [tags] (u/mk-resp 200 "success" {:data (inventory/get-hidden-aliases tags)}))
(POST "/hide/alias/:id" [id] (hide-event id true "alias"))
(POST "/unhide/alias/:id" [id] (hide-event id false "alias"))
;;aggregation
(POST "/agg/tag/resource" [tags with-alias filters]
(u/mk-resp 200 "success" {:data (inventory/get-aggregated-resources tags with-alias filters)}))
(POST "/agg/tag/resource/:tag" [tag tags with-alias filters]
(u/mk-resp 200 "success"
{:data (inventory/get-tag-value-from-aggregated-resources
tag
tags
with-alias
(inventory/get-resources filters with-alias))}))
csv
(POST "/csv/tag/resource" [tags with-alias filters add-header]
(u/mk-resp 200 "success" {:data (inventory/get-csv-resources tags with-alias filters add-header)}))
;;tag
(GET "/tag/resource" [] (u/mk-resp 200 "success" {:data (inventory/get-resource-tags-list)}))
(GET "/tag/resource/:id" [id] (u/mk-resp 200 "success" {:data (inventory/get-tag-value-from-resources id)}))
(POST "/tag/resource/:id" [id tags with-alias] (u/mk-resp 200 "success" {:data (inventory/get-tag-value-from-resources id tags with-alias)}))
(GET "/tag/group/:id" [id] (u/mk-resp 200 "success" {:data (inventory/get-tag-value-from-groups id)}))
;;count
(GET "/count/resource" [] (u/mk-resp 200 "success" {:data {:count (inventory/count-resources)}}))
(POST "/count/resource" [tags] (u/mk-resp 200 "success" {:data {:count (inventory/count-resources tags)}}))
(GET "/count/group" [] (u/mk-resp 200 "success" {:data {:count (inventory/count-groups)}}))
(POST "/count/group" [tags] (u/mk-resp 200 "success" {:data {:count (inventory/count-groups tags)}}))
(GET "/stats/tag/resource/:tag" [tag] (u/mk-resp 200 "success" {:data (inventory/get-tags-stats-from-resources tag)}))
(POST "/stats/tag/resource/:tag" [tag tags] (u/mk-resp 200 "success" {:data (inventory/get-tags-stats-from-resources tag tags)}))
(GET "/save" [] (if-not (inventory/ro?)
(do (inventory/save-inventory)
(u/mk-resp 200 "success" {} "Operation submitted"))
(u/mk-resp 403 "error" {} "Read Only")))
(POST "/new/group" [name tags] (put-event {:type "group" :id (keyword name) :tags tags}))
(POST "/new/alias" [resource-id tags from-resource create-only] (put-event {:type "alias"
:resource-id (keyword resource-id)
:create-only (if-not (nil? create-only) create-only false)
:create true
:tags tags
:from-resource from-resource})))
| null | https://raw.githubusercontent.com/linkfluence/inventory/b69110494f8db210d14cc7093834c441440cd4e8/src/clj/com/linkfluence/inventory/api/inventory.clj | clojure | import inventory handler
view
group
resource
Resource hiding
Resource hiding
aggregation
tag
count | (ns com.linkfluence.inventory.api.inventory
(:require [compojure.core :refer :all]
[compojure.route :as route]
[clojure.tools.logging :as log]
[com.linkfluence.inventory.core :as inventory]
[com.linkfluence.utils :as u]))
(defn put-events
([evs]
(put-events evs "Operation submitted"))
([evs msg]
(if-not (inventory/ro?)
(do
(doseq [ev evs]
(inventory/add-inventory-event ev))
(u/mk-resp 202 "success" {} msg))
(u/mk-resp 403 "error" {} "Read Only"))))
(defn put-event
([ev]
(put-event ev "Operation submitted"))
([ev msg]
(if-not (inventory/ro?)
(do
(inventory/add-inventory-event ev)
(u/mk-resp 202 "success" {} msg))
(u/mk-resp 403 "error" {} "Read Only"))))
(defn hide-event
[id hide type]
(if-not (inventory/ro?)
(if-let [resource (inventory/get-resource (keyword id) true)]
(do
(inventory/hide-event id hide type)
(u/mk-resp 202 "success" {} "hidden flag updated"))
(u/mk-resp 404 "error" {} "Resource not found"))
(u/mk-resp 403 "error" {} "Read Only")))
(defroutes INVENTORY
(GET "/fsync" [] (do
(future
(inventory/load-inventory)
(log/info "[FSYNC] received inventory update notfication"))
(u/mk-resp 202 "success" {} "Fsync submitted")))
(POST "/event" [event] (put-event event))
(POST "/events" [events] (put-events events))
(GET "/view" [] (u/mk-resp 200 "success" {:data (inventory/list-views)}))
(GET "/view/:id" [id] (if-let [view (inventory/get-view (keyword id))]
(u/mk-resp 200 "success" {:data view})
(u/mk-resp 404 "error" {} "Group not found")))
(GET "/group" [] (u/mk-resp 200 "success" {:data (inventory/list-groups)}))
(GET "/group/:id" [id] (if-let [group (inventory/get-group (keyword id))]
(u/mk-resp 200 "success" {:data group})
(u/mk-resp 404 "error" {} "Group not found")))
(DELETE "/group/:id" [id] (if-let [group (inventory/get-group (keyword id))]
(put-event {:type "group" :id (keyword id) :tags [] :delete true} "Deletion submitted")
(u/mk-resp 404 "error" {} "Group not found, deletion aborted")))
(POST "/group/:id/addtags" [id tags] (if (inventory/validate-tags tags)
(put-event {:type "group" :id (keyword id) :tags tags})
(u/mk-resp 400 "error" {:explanation (inventory/explain-tags tags)} "tag array is invalid")))
(POST "/group/:id/addresources" [id resources] (do (inventory/add-inventory-event {:type "group" :id (keyword id) :resources resources})
(u/mk-resp 200 "success" {} "Operation submitted")))
(GET "/resource" [with-alias] (u/mk-resp 200 "success" {:data (inventory/get-resources [] with-alias)}))
(GET "/alias" [] (u/mk-resp 200 "success" {:data (inventory/get-aliases [])}))
(DELETE "/resource/:id" [id] (put-event {:type "resource" :id (keyword id) :delete true} "Deletion submitted"))
(DELETE "/alias/:id" [id] (put-event {:type "alias" :id (keyword id) :delete true} "Deletion submitted"))
(POST "/resource" [tags with-alias] (u/mk-resp 200 "success" {:data (inventory/get-resources tags with-alias)}))
(POST "/alias" [tags] (u/mk-resp 200 "success" {:data (inventory/get-aliases tags)}))
(POST "/exists/alias" [resource-id from-resource tags] (u/mk-resp 200 "success" {:data (inventory/alias-exists? resource-id from-resource tags)}))
(GET "/resource/:id" [id with-alias] (if-let [resource (inventory/get-resource (keyword id) with-alias)]
(u/mk-resp 200 "success" {:data resource})
(u/mk-resp 404 "error" {} "Resource not found")))
(GET "/resource/:id/aliases" [id] (u/mk-resp 200 "success" {:data (inventory/get-resource-aliases (keyword id))}))
(GET "/alias/:id" [id] (if-let [alias (inventory/get-alias (keyword id))]
(u/mk-resp 200 "success" {:data alias})
(u/mk-resp 404 "error" {} "Resource not found")))
(POST "/resource/:id/addtags" [id tags] (if (some? (inventory/get-resource (keyword id) false))
(if (inventory/validate-tags tags)
(put-event {:type "resource" :id (keyword id) :tags tags})
(u/mk-resp 400 "error" {:explanation (inventory/explain-tags tags)} "tag array is invalid"))
(u/mk-resp 404 "error" {} "Cannot add tags to non existent resource")))
(POST "/alias/:id/addtags" [id tags] (if (some? (inventory/get-alias (keyword id)))
(if (inventory/validate-tags tags)
(put-event {:type "alias" :id (keyword id) :tags tags})
(u/mk-resp 400 "error" {:explanation (inventory/explain-tags tags)} "tag array is invalid"))
(u/mk-resp 404 "error" {} "Cannot add tags to non existent alias")))
(GET "/hidden/resource" [] (u/mk-resp 200 "success" {:data (inventory/get-hidden-resources)}))
(POST "/hidden/resource" [tags] (u/mk-resp 200 "success" {:data (inventory/get-hidden-resources tags)}))
(POST "/hide/resource/:id" [id] (hide-event id true "resource"))
(POST "/unhide/resource/:id" [id] (hide-event id false "resource"))
(GET "/hidden/alias" [] (u/mk-resp 200 "success" {:data (inventory/get-hidden-aliases)}))
(POST "/hidden/alias" [tags] (u/mk-resp 200 "success" {:data (inventory/get-hidden-aliases tags)}))
(POST "/hide/alias/:id" [id] (hide-event id true "alias"))
(POST "/unhide/alias/:id" [id] (hide-event id false "alias"))
(POST "/agg/tag/resource" [tags with-alias filters]
(u/mk-resp 200 "success" {:data (inventory/get-aggregated-resources tags with-alias filters)}))
(POST "/agg/tag/resource/:tag" [tag tags with-alias filters]
(u/mk-resp 200 "success"
{:data (inventory/get-tag-value-from-aggregated-resources
tag
tags
with-alias
(inventory/get-resources filters with-alias))}))
csv
(POST "/csv/tag/resource" [tags with-alias filters add-header]
(u/mk-resp 200 "success" {:data (inventory/get-csv-resources tags with-alias filters add-header)}))
(GET "/tag/resource" [] (u/mk-resp 200 "success" {:data (inventory/get-resource-tags-list)}))
(GET "/tag/resource/:id" [id] (u/mk-resp 200 "success" {:data (inventory/get-tag-value-from-resources id)}))
(POST "/tag/resource/:id" [id tags with-alias] (u/mk-resp 200 "success" {:data (inventory/get-tag-value-from-resources id tags with-alias)}))
(GET "/tag/group/:id" [id] (u/mk-resp 200 "success" {:data (inventory/get-tag-value-from-groups id)}))
(GET "/count/resource" [] (u/mk-resp 200 "success" {:data {:count (inventory/count-resources)}}))
(POST "/count/resource" [tags] (u/mk-resp 200 "success" {:data {:count (inventory/count-resources tags)}}))
(GET "/count/group" [] (u/mk-resp 200 "success" {:data {:count (inventory/count-groups)}}))
(POST "/count/group" [tags] (u/mk-resp 200 "success" {:data {:count (inventory/count-groups tags)}}))
(GET "/stats/tag/resource/:tag" [tag] (u/mk-resp 200 "success" {:data (inventory/get-tags-stats-from-resources tag)}))
(POST "/stats/tag/resource/:tag" [tag tags] (u/mk-resp 200 "success" {:data (inventory/get-tags-stats-from-resources tag tags)}))
(GET "/save" [] (if-not (inventory/ro?)
(do (inventory/save-inventory)
(u/mk-resp 200 "success" {} "Operation submitted"))
(u/mk-resp 403 "error" {} "Read Only")))
(POST "/new/group" [name tags] (put-event {:type "group" :id (keyword name) :tags tags}))
(POST "/new/alias" [resource-id tags from-resource create-only] (put-event {:type "alias"
:resource-id (keyword resource-id)
:create-only (if-not (nil? create-only) create-only false)
:create true
:tags tags
:from-resource from-resource})))
|
a612835c5e47e40b5aeb728a09bbb7f23a419e4ffe7f0f5e128460a7e11ed775 | marksteele/cinched | cinched_crypto_field_rest_handler.erl | %%%-------------------------------------------------------------------
@author < >
( C ) 2016 ,
%%% @doc
Cinched Field REST API
%%% @end
Created : 24 Jan 2016 by < >
%%%-------------------------------------------------------------------
This file is provided to you under the Apache License ,
%% Version 2.0 (the "License"); you may not use this file
except in compliance with the License . You may obtain
%% a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either express or implied. See the License for the
%% specific language governing permissions and limitations
%% under the License.
-module(cinched_crypto_field_rest_handler).
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-endif.
-include("cinched.hrl").
%% Callbacks for REST API
-export([init/3, known_methods/2,
allowed_methods/2,
content_types_provided/2, is_authorized/2,
content_types_accepted/2]).
%% Custom functions
-export([encrypt/2, decrypt/2]).
-spec init(_,_,_) -> {'upgrade','protocol','cowboy_rest'}.
init(_Transport, _Req, _Args) ->
{upgrade, protocol, cowboy_rest}.
-spec known_methods(_,_) -> {[<<_:32>>,...],_,_}.
known_methods(Req, Ctx) ->
{[<<"POST">>], Req, Ctx}.
-spec allowed_methods(_,_) -> {[<<_:32>>,...],_,_}.
allowed_methods(Req, Ctx) ->
{[<<"POST">>], Req, Ctx}.
-spec is_authorized(_,_) -> {true,any(),any()}.
is_authorized(Req,Ctx) ->
{true, Req, Ctx}.
%% TODO: Save this state (the action) for the content types provided function
content_types_accepted(Req, Ctx) ->
case cowboy_req:binding(action, Req) of
{undefined,Req} ->
{halt,Req,{}};
{<<"encrypt">>,Req} ->
{[{{<<"application">>, <<"json">>, '*'}, encrypt}], Req, Ctx};
{<<"decrypt">>,Req} ->
{[{{<<"application">>, <<"json">>, '*'}, decrypt}], Req, Ctx}
end.
content_types_provided(Req, Ctx) ->
case cowboy_req:binding(action, Req) of
{undefined,Req} ->
{halt,Req,{}};
{<<"encrypt">>,Req} ->
{[{{<<"application">>, <<"json">>, '*'}, encrypt}], Req, Ctx};
{<<"decrypt">>,Req} ->
{[{{<<"application">>, <<"json">>, '*'}, decrypt}], Req, Ctx}
end.
-spec encrypt(_,_) -> {'true',_,{}}.
encrypt(Req0, _Ctx) ->
{ok, Body, Req1} = cowboy_req:body(Req0,[]),
{ok, DataKey} = case cowboy_req:header(<<"x-cinched-data-key">>, Req1) of
{undefined,Req2} ->
cinched:generate_data_key();
{KeyHeader,Req2} ->
{ok, binary_to_term(base64:decode(KeyHeader))}
end,
{FieldSpec, Req3} = cowboy_req:qs_val(<<"fields">>,Req2),
{ok, Filter} = parse_fields(FieldSpec),
{Time, Value} = timer:tc(
fun() ->
poolboy:transaction(
pb,
fun(Worker) ->
gen_server:call(Worker,{encrypt,DataKey,Body,Filter})
end
)
end
),
exometer:update([crypto_worker,encrypt,time],Time),
%% Gather logging data
{Peer,Port0} = cowboy_req:get(peer,Req3),
Port = integer_to_binary(Port0),
PeerIP = list_to_binary(inet_parse:ntoa(Peer)),
{ok,{Serial,PeerCN}} = cinched:get_cert_info_from_socket(cowboy_req:get(socket,Req3)),
{QueryString,Req4} = cowboy_req:qs(Req3),
{UserAgent,Req5} = cowboy_req:header(<<"user-agent">>,Req4),
{Metadata,Req6} = cowboy_req:header(<<"x-cinched-metadata">>,Req5),
case Value of
{ok, Response} ->
cinched_log:log([
{op,field_encrypt},
{status,ok},
{meta,Metadata},
{query_string,QueryString},
{user_agent,UserAgent},
{peer_ip,PeerIP},
{peer_port,Port},
{peer_cert_cn,PeerCN},
{peer_cert_serial,Serial}
]),
Req7 = cowboy_req:set_resp_header(
<<"x-cinched-data-key">>,
base64:encode(term_to_binary(DataKey)),
Req6
),
Req8 = cowboy_req:set_resp_header(
<<"x-cinched-crypto-period">>,
integer_to_binary(DataKey#cinched_key.crypto_period),
Req7
),
exometer:update([api,field,encrypt,ok],1),
{true, cowboy_req:set_resp_body(Response, Req8), {}};
{error,_Err} ->
cinched_log:log([
{op,field_encrypt},
{status,error},
{meta,Metadata},
{query_string,QueryString},
{user_agent,UserAgent},
{peer_ip,PeerIP},
{peer_port,Port},
{peer_cert_cn,PeerCN},
{peer_cert_serial,Serial}
]),
exometer:update([api,field,encrypt,error],1),
{false, Req6, {}}
end.
-spec decrypt(_,_) -> {'true',_,{}}.
decrypt(Req0, _Ctx) ->
{ok, Body, Req1} = cowboy_req:body(Req0,[]),
{ok, DataKey} = case cowboy_req:header(<<"x-cinched-data-key">>, Req1) of
{undefined,Req2} ->
throw("Error, missing data key");
{KeyHeader,Req2} ->
{ok, binary_to_term(base64:decode(KeyHeader))}
end,
{FieldSpec, Req3} = cowboy_req:qs_val(<<"fields">>,Req2),
{ok, Filter} = parse_fields(FieldSpec),
{Time, Value} = timer:tc(
fun() ->
poolboy:transaction(
pb,
fun(Worker) ->
gen_server:call(Worker,{decrypt,DataKey,Body,Filter})
end
)
end
),
exometer:update([crypto_worker,decrypt,time],Time),
%% Gather logging data
{Peer,Port0} = cowboy_req:get(peer,Req3),
Port = integer_to_binary(Port0),
PeerIP = list_to_binary(inet_parse:ntoa(Peer)),
{ok,{Serial,PeerCN}} = cinched:get_cert_info_from_socket(cowboy_req:get(socket,Req3)),
{QueryString,Req4} = cowboy_req:qs(Req3),
{UserAgent,Req5} = cowboy_req:header(<<"user-agent">>,Req4),
{Metadata,Req6} = cowboy_req:header(<<"x-cinched-metadata">>,Req5),
case Value of
{ok, Response} ->
cinched_log:log([
{op,field_decrypt},
{status,ok},
{meta,Metadata},
{query_string,QueryString},
{user_agent,UserAgent},
{peer_ip,PeerIP},
{peer_port,Port},
{peer_cert_cn,PeerCN},
{peer_cert_serial,Serial}
]),
exometer:update([api,field,decrypt,ok],1),
{true,cowboy_req:set_resp_body(Response,Req6), {}};
{error,_} ->
cinched_log:log([
{op,field_decrypt},
{status,error},
{meta,Metadata},
{query_string,QueryString},
{user_agent,UserAgent},
{peer_ip,PeerIP},
{peer_port,Port},
{peer_cert_cn,PeerCN},
{peer_cert_serial,Serial}
]),
exometer:update([api,field,decrypt,error],1),
{false, Req6, {}}
end.
Field format : ( foo , bar.baz , buz , argle.bargle.glop , foo.4.baz.buz ) )
-spec parse_fields(binary()) -> {ok, [integer()|binary()]}.
parse_fields(Fields) ->
{match, [Matched]} = re:run(Fields,<<"^\\((.+?)\\)$">>,[{capture,all_but_first,binary}]),
Spec = lists:foldl(
fun(X,Acc) ->
Acc ++ [
list_to_tuple(
[begin
try
binary_to_integer(Y)
catch
error:badarg ->
Y
end
end
|| Y <- binary:split(X,<<".">>,[global])]
)
]
end,
[],
binary:split(Matched,<<",">>,[global])),
{ok, Spec}.
-ifdef(TEST).
parse_fields_test() ->
?assertEqual({ok,[{<<"foo">>,<<"bar">>,<<"baz">>}]},parse_fields(<<"(foo.bar.baz)">>)),
?assertEqual({ok,[{<<"foo">>,<<"bar">>,<<"baz">>},{<<"baz">>,<<"buz">>}]},parse_fields(<<"(foo.bar.baz,baz.buz)">>)),
?assertEqual({ok,[{<<"foo">>,<<"bar">>,4}]},parse_fields(<<"(foo.bar.4)">>)),
?assertEqual({ok,[{1,<<"foo">>,<<"bar">>,4}]},parse_fields(<<"(1.foo.bar.4)">>)).
-endif.
| null | https://raw.githubusercontent.com/marksteele/cinched/5284d048c649128fa8929f6e85cdc4747d223427/src/cinched_crypto_field_rest_handler.erl | erlang | -------------------------------------------------------------------
@doc
@end
-------------------------------------------------------------------
Version 2.0 (the "License"); you may not use this file
a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
Callbacks for REST API
Custom functions
TODO: Save this state (the action) for the content types provided function
Gather logging data
Gather logging data | @author < >
( C ) 2016 ,
Cinched Field REST API
Created : 24 Jan 2016 by < >
This file is provided to you under the Apache License ,
except in compliance with the License . You may obtain
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
-module(cinched_crypto_field_rest_handler).
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-endif.
-include("cinched.hrl").
-export([init/3, known_methods/2,
allowed_methods/2,
content_types_provided/2, is_authorized/2,
content_types_accepted/2]).
-export([encrypt/2, decrypt/2]).
-spec init(_,_,_) -> {'upgrade','protocol','cowboy_rest'}.
init(_Transport, _Req, _Args) ->
{upgrade, protocol, cowboy_rest}.
-spec known_methods(_,_) -> {[<<_:32>>,...],_,_}.
known_methods(Req, Ctx) ->
{[<<"POST">>], Req, Ctx}.
-spec allowed_methods(_,_) -> {[<<_:32>>,...],_,_}.
allowed_methods(Req, Ctx) ->
{[<<"POST">>], Req, Ctx}.
-spec is_authorized(_,_) -> {true,any(),any()}.
is_authorized(Req,Ctx) ->
{true, Req, Ctx}.
content_types_accepted(Req, Ctx) ->
case cowboy_req:binding(action, Req) of
{undefined,Req} ->
{halt,Req,{}};
{<<"encrypt">>,Req} ->
{[{{<<"application">>, <<"json">>, '*'}, encrypt}], Req, Ctx};
{<<"decrypt">>,Req} ->
{[{{<<"application">>, <<"json">>, '*'}, decrypt}], Req, Ctx}
end.
content_types_provided(Req, Ctx) ->
case cowboy_req:binding(action, Req) of
{undefined,Req} ->
{halt,Req,{}};
{<<"encrypt">>,Req} ->
{[{{<<"application">>, <<"json">>, '*'}, encrypt}], Req, Ctx};
{<<"decrypt">>,Req} ->
{[{{<<"application">>, <<"json">>, '*'}, decrypt}], Req, Ctx}
end.
-spec encrypt(_,_) -> {'true',_,{}}.
encrypt(Req0, _Ctx) ->
{ok, Body, Req1} = cowboy_req:body(Req0,[]),
{ok, DataKey} = case cowboy_req:header(<<"x-cinched-data-key">>, Req1) of
{undefined,Req2} ->
cinched:generate_data_key();
{KeyHeader,Req2} ->
{ok, binary_to_term(base64:decode(KeyHeader))}
end,
{FieldSpec, Req3} = cowboy_req:qs_val(<<"fields">>,Req2),
{ok, Filter} = parse_fields(FieldSpec),
{Time, Value} = timer:tc(
fun() ->
poolboy:transaction(
pb,
fun(Worker) ->
gen_server:call(Worker,{encrypt,DataKey,Body,Filter})
end
)
end
),
exometer:update([crypto_worker,encrypt,time],Time),
{Peer,Port0} = cowboy_req:get(peer,Req3),
Port = integer_to_binary(Port0),
PeerIP = list_to_binary(inet_parse:ntoa(Peer)),
{ok,{Serial,PeerCN}} = cinched:get_cert_info_from_socket(cowboy_req:get(socket,Req3)),
{QueryString,Req4} = cowboy_req:qs(Req3),
{UserAgent,Req5} = cowboy_req:header(<<"user-agent">>,Req4),
{Metadata,Req6} = cowboy_req:header(<<"x-cinched-metadata">>,Req5),
case Value of
{ok, Response} ->
cinched_log:log([
{op,field_encrypt},
{status,ok},
{meta,Metadata},
{query_string,QueryString},
{user_agent,UserAgent},
{peer_ip,PeerIP},
{peer_port,Port},
{peer_cert_cn,PeerCN},
{peer_cert_serial,Serial}
]),
Req7 = cowboy_req:set_resp_header(
<<"x-cinched-data-key">>,
base64:encode(term_to_binary(DataKey)),
Req6
),
Req8 = cowboy_req:set_resp_header(
<<"x-cinched-crypto-period">>,
integer_to_binary(DataKey#cinched_key.crypto_period),
Req7
),
exometer:update([api,field,encrypt,ok],1),
{true, cowboy_req:set_resp_body(Response, Req8), {}};
{error,_Err} ->
cinched_log:log([
{op,field_encrypt},
{status,error},
{meta,Metadata},
{query_string,QueryString},
{user_agent,UserAgent},
{peer_ip,PeerIP},
{peer_port,Port},
{peer_cert_cn,PeerCN},
{peer_cert_serial,Serial}
]),
exometer:update([api,field,encrypt,error],1),
{false, Req6, {}}
end.
-spec decrypt(_,_) -> {'true',_,{}}.
decrypt(Req0, _Ctx) ->
{ok, Body, Req1} = cowboy_req:body(Req0,[]),
{ok, DataKey} = case cowboy_req:header(<<"x-cinched-data-key">>, Req1) of
{undefined,Req2} ->
throw("Error, missing data key");
{KeyHeader,Req2} ->
{ok, binary_to_term(base64:decode(KeyHeader))}
end,
{FieldSpec, Req3} = cowboy_req:qs_val(<<"fields">>,Req2),
{ok, Filter} = parse_fields(FieldSpec),
{Time, Value} = timer:tc(
fun() ->
poolboy:transaction(
pb,
fun(Worker) ->
gen_server:call(Worker,{decrypt,DataKey,Body,Filter})
end
)
end
),
exometer:update([crypto_worker,decrypt,time],Time),
{Peer,Port0} = cowboy_req:get(peer,Req3),
Port = integer_to_binary(Port0),
PeerIP = list_to_binary(inet_parse:ntoa(Peer)),
{ok,{Serial,PeerCN}} = cinched:get_cert_info_from_socket(cowboy_req:get(socket,Req3)),
{QueryString,Req4} = cowboy_req:qs(Req3),
{UserAgent,Req5} = cowboy_req:header(<<"user-agent">>,Req4),
{Metadata,Req6} = cowboy_req:header(<<"x-cinched-metadata">>,Req5),
case Value of
{ok, Response} ->
cinched_log:log([
{op,field_decrypt},
{status,ok},
{meta,Metadata},
{query_string,QueryString},
{user_agent,UserAgent},
{peer_ip,PeerIP},
{peer_port,Port},
{peer_cert_cn,PeerCN},
{peer_cert_serial,Serial}
]),
exometer:update([api,field,decrypt,ok],1),
{true,cowboy_req:set_resp_body(Response,Req6), {}};
{error,_} ->
cinched_log:log([
{op,field_decrypt},
{status,error},
{meta,Metadata},
{query_string,QueryString},
{user_agent,UserAgent},
{peer_ip,PeerIP},
{peer_port,Port},
{peer_cert_cn,PeerCN},
{peer_cert_serial,Serial}
]),
exometer:update([api,field,decrypt,error],1),
{false, Req6, {}}
end.
Field format : ( foo , bar.baz , buz , argle.bargle.glop , foo.4.baz.buz ) )
-spec parse_fields(binary()) -> {ok, [integer()|binary()]}.
parse_fields(Fields) ->
{match, [Matched]} = re:run(Fields,<<"^\\((.+?)\\)$">>,[{capture,all_but_first,binary}]),
Spec = lists:foldl(
fun(X,Acc) ->
Acc ++ [
list_to_tuple(
[begin
try
binary_to_integer(Y)
catch
error:badarg ->
Y
end
end
|| Y <- binary:split(X,<<".">>,[global])]
)
]
end,
[],
binary:split(Matched,<<",">>,[global])),
{ok, Spec}.
-ifdef(TEST).
parse_fields_test() ->
?assertEqual({ok,[{<<"foo">>,<<"bar">>,<<"baz">>}]},parse_fields(<<"(foo.bar.baz)">>)),
?assertEqual({ok,[{<<"foo">>,<<"bar">>,<<"baz">>},{<<"baz">>,<<"buz">>}]},parse_fields(<<"(foo.bar.baz,baz.buz)">>)),
?assertEqual({ok,[{<<"foo">>,<<"bar">>,4}]},parse_fields(<<"(foo.bar.4)">>)),
?assertEqual({ok,[{1,<<"foo">>,<<"bar">>,4}]},parse_fields(<<"(1.foo.bar.4)">>)).
-endif.
|
3c5867def9ff83a718e77cf698c59274198e16e9a147acc9e8323025f9d98469 | pusher/stronghold | StoredData.hs | {-# LANGUAGE GADTs #-}
# LANGUAGE DataKinds #
# LANGUAGE KindSignatures #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ScopedTypeVariables #
module StoredData where
{-
This module is responsible for defining the data that get stored in
zookeeper.
-}
import Control.Applicative ((<$>))
import Control.Monad (when)
import Control.Monad.Operational (Program, ProgramViewT (..), singleton, view)
import Control.Monad.Trans (lift)
import Control.Monad.Trans.Maybe (MaybeT(MaybeT), runMaybeT)
import Crypto.Hash.SHA1 (hash)
import Data.ByteString (ByteString)
import Data.HashMap.Strict (HashMap)
import Data.Hashable (Hashable)
import Data.Serialize (Serialize, decode, encode, get, put)
import Data.Text (Text)
import Data.Text.Encoding (decodeUtf8, encodeUtf8)
import Data.Time.Calendar (Day (ModifiedJulianDay), toModifiedJulianDay)
import Data.Time.Clock (DiffTime, UTCTime (UTCTime))
import Util (integerFromUTC)
import qualified Data.Aeson as Aeson
import qualified Data.ByteString.Base16 as Base16
import qualified Data.HashMap.Strict as HashMap
import qualified Data.Serialize as Serialize
type JSON = Aeson.Value
-- | timestamp, comment, author
data MetaInfo = MetaInfo UTCTime Text Text deriving Show
instance Aeson.ToJSON MetaInfo where
toJSON (MetaInfo ts comment author) =
Aeson.object [
("timestamp", Aeson.toJSON (integerFromUTC ts)),
("comment", Aeson.String comment),
("author", Aeson.String author)
]
data Tag =
JSONTag |
HierarchyTag |
HistoryTag
data STag :: Tag -> * where
JSONTag' :: STag JSONTag
HierarchyTag' :: STag HierarchyTag
HistoryTag' :: STag HistoryTag
class TagClass t where
tag :: STag t
instance TagClass JSONTag where
tag = JSONTag'
instance TagClass HierarchyTag where
tag = HierarchyTag'
instance TagClass HistoryTag where
tag = HistoryTag'
data TreeNode x k v = TreeNode (HashMap k v) x deriving Show
data ListNode x r = Nil | Cons x r deriving Show
data Data :: Tag -> * where
JSONData :: JSON -> Data JSONTag
HierarchyNode
:: TreeNode (Ref JSONTag) Text (Ref HierarchyTag)
-> Data HierarchyTag
HistoryNode
:: ListNode (MetaInfo, Ref HierarchyTag) (Ref HistoryTag)
-> Data HistoryTag
instance Show (Data t) where
show (JSONData json) = show json
show (HierarchyNode node) = show node
show (HistoryNode node) = show node
type JSONData = Data JSONTag
type HierarchyNode = Data HierarchyTag
type HistoryNode = Data HistoryTag
data Ref :: Tag -> * where
Ref :: ByteString -> Ref t
instance Eq (Ref t) where
(Ref a) == (Ref b) = a == b
instance Serialize UTCTime where
get = uncurry UTCTime <$> get
put (UTCTime day time) = put (day, time)
instance Serialize Day where
get = ModifiedJulianDay <$> get
put = put . toModifiedJulianDay
instance Serialize DiffTime where
get = fromRational <$> get
put = put . toRational
instance Serialize Aeson.Value where
put = put . Aeson.encode
get = maybe (fail "error parsing json") return =<< Aeson.decode <$> get
instance Serialize (Ref t) where
put (Ref x) = put x
get = Ref <$> get
instance (Eq k, Hashable k, Serialize k, Serialize v)
=> Serialize (HashMap k v) where
put = put . HashMap.toList
get = HashMap.fromList <$> get
instance (Eq k, Hashable k, Serialize k, Serialize v, Serialize x)
=> Serialize (TreeNode x k v) where
put (TreeNode l x) = put (l, x)
get = uncurry TreeNode <$> get
instance Serialize Text where
put = put . encodeUtf8
get = decodeUtf8 <$> get
instance (Serialize x, Serialize r) => Serialize (ListNode x r) where
put Nil = Serialize.putByteString "n"
put (Cons x xs) = do
Serialize.putByteString "c"
put (x, xs)
get = do
b <- Serialize.getBytes 1
if b == "n" then
return Nil
else if b == "c" then
uncurry Cons <$> get
else
fail "unknown listnode type"
instance Serialize MetaInfo where
put (MetaInfo a b c) = put (a, b, c)
get = (\(a, b, c) -> MetaInfo a b c) <$> get
instance TagClass t => Serialize (Data t) where
put (JSONData json) = do
Serialize.putByteString "1"
put json
put (HierarchyNode x) = do
Serialize.putByteString "2"
put x
put (HistoryNode x) = do
Serialize.putByteString "3"
put x
get = do
t <- Serialize.getBytes 1
case (tag :: STag t) of
JSONTag' -> do
when (t /= "1") $ fail "expected json tag"
JSONData <$> get
HierarchyTag' -> do
when (t /= "2") $ fail "expected hierarchy node tag"
HierarchyNode <$> get
HistoryTag' -> do
when (t /= "3") $ fail "expected history node tag"
HistoryNode <$> get
makeRef :: ByteString -> Ref t
makeRef r = Ref ((fst . Base16.decode) r)
unref :: Ref t -> ByteString
unref (Ref r) = Base16.encode r
instance Show (Ref t) where
show = show . unref
emptyObjectHash :: ByteString
emptyObjectHash = hash (encode (JSONData (Aeson.object [])))
-- Arguably, this should be inside the monad.
emptyObject :: Ref JSONTag -> Bool
emptyObject (Ref x) = x == emptyObjectHash
-- This defines the operations that are possible on the data in zookeeper
data StoreInstr a where
Store :: TagClass t => Data t -> StoreInstr (Ref t)
Load :: TagClass t => Ref t -> StoreInstr (Data t)
GetHead :: StoreInstr (Ref HistoryTag)
GetHeadBlockIfEq :: Ref HistoryTag -> StoreInstr (Ref HistoryTag)
UpdateHead :: Ref HistoryTag -> Ref HistoryTag -> StoreInstr Bool
CreateRef :: ByteString -> StoreInstr (Maybe (Ref HistoryTag))
type StoreOp a = Program StoreInstr a
store :: TagClass x => Data x -> StoreOp (Ref x)
store = singleton . Store
load :: TagClass x => Ref x -> StoreOp (Data x)
load = singleton . Load
getHead :: StoreOp (Ref HistoryTag)
getHead = singleton GetHead
getHeadBlockIfEq :: Ref HistoryTag -> StoreOp (Ref HistoryTag)
getHeadBlockIfEq = singleton . GetHeadBlockIfEq
updateHead :: Ref HistoryTag -> Ref HistoryTag -> StoreOp Bool
updateHead prev next = singleton $ UpdateHead prev next
createRef :: ByteString -> StoreOp (Maybe (Ref HistoryTag))
createRef = singleton . CreateRef
isRight :: Either a b -> Bool
isRight (Right _) = True
isRight _ = False
validHistoryNode :: ByteString -> Bool
validHistoryNode s = isRight (decode s :: Either String (Data HistoryTag))
| null | https://raw.githubusercontent.com/pusher/stronghold/b5ec314425d9492f881f46d14b78d76de7b9429b/src/StoredData.hs | haskell | # LANGUAGE GADTs #
# LANGUAGE OverloadedStrings #
This module is responsible for defining the data that get stored in
zookeeper.
| timestamp, comment, author
Arguably, this should be inside the monad.
This defines the operations that are possible on the data in zookeeper | # LANGUAGE DataKinds #
# LANGUAGE KindSignatures #
# LANGUAGE ScopedTypeVariables #
module StoredData where
import Control.Applicative ((<$>))
import Control.Monad (when)
import Control.Monad.Operational (Program, ProgramViewT (..), singleton, view)
import Control.Monad.Trans (lift)
import Control.Monad.Trans.Maybe (MaybeT(MaybeT), runMaybeT)
import Crypto.Hash.SHA1 (hash)
import Data.ByteString (ByteString)
import Data.HashMap.Strict (HashMap)
import Data.Hashable (Hashable)
import Data.Serialize (Serialize, decode, encode, get, put)
import Data.Text (Text)
import Data.Text.Encoding (decodeUtf8, encodeUtf8)
import Data.Time.Calendar (Day (ModifiedJulianDay), toModifiedJulianDay)
import Data.Time.Clock (DiffTime, UTCTime (UTCTime))
import Util (integerFromUTC)
import qualified Data.Aeson as Aeson
import qualified Data.ByteString.Base16 as Base16
import qualified Data.HashMap.Strict as HashMap
import qualified Data.Serialize as Serialize
type JSON = Aeson.Value
data MetaInfo = MetaInfo UTCTime Text Text deriving Show
instance Aeson.ToJSON MetaInfo where
toJSON (MetaInfo ts comment author) =
Aeson.object [
("timestamp", Aeson.toJSON (integerFromUTC ts)),
("comment", Aeson.String comment),
("author", Aeson.String author)
]
data Tag =
JSONTag |
HierarchyTag |
HistoryTag
data STag :: Tag -> * where
JSONTag' :: STag JSONTag
HierarchyTag' :: STag HierarchyTag
HistoryTag' :: STag HistoryTag
class TagClass t where
tag :: STag t
instance TagClass JSONTag where
tag = JSONTag'
instance TagClass HierarchyTag where
tag = HierarchyTag'
instance TagClass HistoryTag where
tag = HistoryTag'
data TreeNode x k v = TreeNode (HashMap k v) x deriving Show
data ListNode x r = Nil | Cons x r deriving Show
data Data :: Tag -> * where
JSONData :: JSON -> Data JSONTag
HierarchyNode
:: TreeNode (Ref JSONTag) Text (Ref HierarchyTag)
-> Data HierarchyTag
HistoryNode
:: ListNode (MetaInfo, Ref HierarchyTag) (Ref HistoryTag)
-> Data HistoryTag
instance Show (Data t) where
show (JSONData json) = show json
show (HierarchyNode node) = show node
show (HistoryNode node) = show node
type JSONData = Data JSONTag
type HierarchyNode = Data HierarchyTag
type HistoryNode = Data HistoryTag
data Ref :: Tag -> * where
Ref :: ByteString -> Ref t
instance Eq (Ref t) where
(Ref a) == (Ref b) = a == b
instance Serialize UTCTime where
get = uncurry UTCTime <$> get
put (UTCTime day time) = put (day, time)
instance Serialize Day where
get = ModifiedJulianDay <$> get
put = put . toModifiedJulianDay
instance Serialize DiffTime where
get = fromRational <$> get
put = put . toRational
instance Serialize Aeson.Value where
put = put . Aeson.encode
get = maybe (fail "error parsing json") return =<< Aeson.decode <$> get
instance Serialize (Ref t) where
put (Ref x) = put x
get = Ref <$> get
instance (Eq k, Hashable k, Serialize k, Serialize v)
=> Serialize (HashMap k v) where
put = put . HashMap.toList
get = HashMap.fromList <$> get
instance (Eq k, Hashable k, Serialize k, Serialize v, Serialize x)
=> Serialize (TreeNode x k v) where
put (TreeNode l x) = put (l, x)
get = uncurry TreeNode <$> get
instance Serialize Text where
put = put . encodeUtf8
get = decodeUtf8 <$> get
instance (Serialize x, Serialize r) => Serialize (ListNode x r) where
put Nil = Serialize.putByteString "n"
put (Cons x xs) = do
Serialize.putByteString "c"
put (x, xs)
get = do
b <- Serialize.getBytes 1
if b == "n" then
return Nil
else if b == "c" then
uncurry Cons <$> get
else
fail "unknown listnode type"
instance Serialize MetaInfo where
put (MetaInfo a b c) = put (a, b, c)
get = (\(a, b, c) -> MetaInfo a b c) <$> get
instance TagClass t => Serialize (Data t) where
put (JSONData json) = do
Serialize.putByteString "1"
put json
put (HierarchyNode x) = do
Serialize.putByteString "2"
put x
put (HistoryNode x) = do
Serialize.putByteString "3"
put x
get = do
t <- Serialize.getBytes 1
case (tag :: STag t) of
JSONTag' -> do
when (t /= "1") $ fail "expected json tag"
JSONData <$> get
HierarchyTag' -> do
when (t /= "2") $ fail "expected hierarchy node tag"
HierarchyNode <$> get
HistoryTag' -> do
when (t /= "3") $ fail "expected history node tag"
HistoryNode <$> get
makeRef :: ByteString -> Ref t
makeRef r = Ref ((fst . Base16.decode) r)
unref :: Ref t -> ByteString
unref (Ref r) = Base16.encode r
instance Show (Ref t) where
show = show . unref
emptyObjectHash :: ByteString
emptyObjectHash = hash (encode (JSONData (Aeson.object [])))
emptyObject :: Ref JSONTag -> Bool
emptyObject (Ref x) = x == emptyObjectHash
data StoreInstr a where
Store :: TagClass t => Data t -> StoreInstr (Ref t)
Load :: TagClass t => Ref t -> StoreInstr (Data t)
GetHead :: StoreInstr (Ref HistoryTag)
GetHeadBlockIfEq :: Ref HistoryTag -> StoreInstr (Ref HistoryTag)
UpdateHead :: Ref HistoryTag -> Ref HistoryTag -> StoreInstr Bool
CreateRef :: ByteString -> StoreInstr (Maybe (Ref HistoryTag))
type StoreOp a = Program StoreInstr a
store :: TagClass x => Data x -> StoreOp (Ref x)
store = singleton . Store
load :: TagClass x => Ref x -> StoreOp (Data x)
load = singleton . Load
getHead :: StoreOp (Ref HistoryTag)
getHead = singleton GetHead
getHeadBlockIfEq :: Ref HistoryTag -> StoreOp (Ref HistoryTag)
getHeadBlockIfEq = singleton . GetHeadBlockIfEq
updateHead :: Ref HistoryTag -> Ref HistoryTag -> StoreOp Bool
updateHead prev next = singleton $ UpdateHead prev next
createRef :: ByteString -> StoreOp (Maybe (Ref HistoryTag))
createRef = singleton . CreateRef
isRight :: Either a b -> Bool
isRight (Right _) = True
isRight _ = False
validHistoryNode :: ByteString -> Bool
validHistoryNode s = isRight (decode s :: Either String (Data HistoryTag))
|
4d4fe648488d39d3e9e7dec933a163f53a823ec196b60d801622c068b4ac9cea | drathier/elm-offline | Parse.hs | # OPTIONS_GHC -Wall #
module Parse.Parse
( program
)
where
import qualified Data.ByteString as B
import qualified AST.Source as Src
import qualified AST.Valid as Valid
import qualified Elm.Package as Pkg
import qualified Parse.Declaration as Decl
import qualified Parse.Module as Module
import qualified Parse.Primitives as P
import qualified Reporting.Error.Syntax as Error
import qualified Reporting.Result as Result
import qualified Validate
-- PROGRAM
program :: Pkg.Name -> B.ByteString -> Result.Result i w Error.Error Valid.Module
program pkg src =
let
bodyParser =
if Pkg.isKernel pkg then
chompDeclarations =<< chompInfixes []
else
chompDeclarations []
parser =
Module.module_ pkg bodyParser <* P.endOfFile
in
case P.run parser src of
Right modul ->
Validate.validate modul
Left syntaxError ->
Result.throw syntaxError
CHOMP DECLARATIONS
chompDeclarations :: [Src.Decl] -> P.Parser [Src.Decl]
chompDeclarations decls =
do (decl, _, pos) <- Decl.declaration
P.oneOf
[ do P.checkFreshLine pos
chompDeclarations (decl:decls)
, return (reverse (decl:decls))
]
chompInfixes :: [Src.Decl] -> P.Parser [Src.Decl]
chompInfixes decls =
P.oneOf
[ do decl <- Decl.infix_
chompInfixes (decl:decls)
, return decls
]
| null | https://raw.githubusercontent.com/drathier/elm-offline/f562198cac29f4cda15b69fde7e66edde89b34fa/compiler/src/Parse/Parse.hs | haskell | PROGRAM | # OPTIONS_GHC -Wall #
module Parse.Parse
( program
)
where
import qualified Data.ByteString as B
import qualified AST.Source as Src
import qualified AST.Valid as Valid
import qualified Elm.Package as Pkg
import qualified Parse.Declaration as Decl
import qualified Parse.Module as Module
import qualified Parse.Primitives as P
import qualified Reporting.Error.Syntax as Error
import qualified Reporting.Result as Result
import qualified Validate
program :: Pkg.Name -> B.ByteString -> Result.Result i w Error.Error Valid.Module
program pkg src =
let
bodyParser =
if Pkg.isKernel pkg then
chompDeclarations =<< chompInfixes []
else
chompDeclarations []
parser =
Module.module_ pkg bodyParser <* P.endOfFile
in
case P.run parser src of
Right modul ->
Validate.validate modul
Left syntaxError ->
Result.throw syntaxError
CHOMP DECLARATIONS
chompDeclarations :: [Src.Decl] -> P.Parser [Src.Decl]
chompDeclarations decls =
do (decl, _, pos) <- Decl.declaration
P.oneOf
[ do P.checkFreshLine pos
chompDeclarations (decl:decls)
, return (reverse (decl:decls))
]
chompInfixes :: [Src.Decl] -> P.Parser [Src.Decl]
chompInfixes decls =
P.oneOf
[ do decl <- Decl.infix_
chompInfixes (decl:decls)
, return decls
]
|
d691926738b41367e4c2558df85246d704eeb36316964e8854ba64485af1a55a | sheyll/b9-vm-image-builder | B9.hs | -- | B9 is a library and build tool with which one can create/convert different types
-- of VM images. Additionally installation steps - like installing software -
-- can be done in a LXC container, running on the disk images.
--
B9 allows to create and convert virtual machine image files as well as
related ISO and VFAT disk images for e.g. cloud - init configuration sources .
--
-- This module re-exports the modules needed to build a tool around the
-- library, e.g. see @src\/cli\/Main.hs@ as an example.
--
-- "B9.Artifact.Generator" is the module containing the basic data structure
used to describe a B9 build .
module B9
( b9Version,
b9VersionString,
runShowVersion,
runBuildArtifacts,
runFormatBuildFiles,
runPush,
runPull,
runRun,
runGcLocalRepoCache,
runGcRemoteRepoCache,
runListSharedImages,
runAddRepo,
runLookupLocalSharedImage,
module X,
)
where
import B9.Artifact.Content as X
import B9.Artifact.Content.AST as X
import B9.Artifact.Content.CloudConfigYaml as X
import B9.Artifact.Content.ErlTerms as X
import B9.Artifact.Content.ErlangPropList as X
import B9.Artifact.Content.Readable as X
import B9.Artifact.Content.StringTemplate as X
import B9.Artifact.Content.YamlObject as X
import B9.Artifact.Readable as X
import B9.Artifact.Readable.Interpreter as X
import B9.B9Config as X
import B9.B9Error as X
import B9.B9Exec as X
import B9.B9Logging as X
import B9.B9Monad as X
import B9.BuildInfo as X
import B9.DiskImageBuilder as X
import B9.DiskImages as X
import B9.Environment as X
import B9.ExecEnv as X
import B9.QCUtil as X
import B9.Repository as X
import B9.RepositoryIO as X
import B9.ShellScript as X
import B9.Text as X
import B9.Vm as X
import B9.VmBuilder as X
import Control.Applicative as X
import Control.Lens as X
( (%~),
(&),
(.~),
Lens,
(^.),
)
import Control.Monad as X
import Control.Monad.IO.Class as X
import Control.Monad.Reader as X
( ReaderT,
ask,
local,
)
import Data.Foldable (fold)
import Data.List as X
import Data.Maybe as X
import Data.Monoid as X
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Version as X
import Paths_b9 (version)
import System.Exit as X
( ExitCode (..),
exitWith,
)
import System.FilePath as X
( (<.>),
(</>),
replaceExtension,
takeDirectory,
takeFileName,
)
import System.IO.B9Extras as X
import Text.Printf as X
( printf,
)
import Text.Show.Pretty as X
( ppShow,
)
| Return the cabal package version of the B9 library .
b9Version :: Version
b9Version = version
| Return the cabal package version of the B9 library ,
-- formatted using `showVersion`.
b9VersionString :: String
b9VersionString = showVersion version
-- | Just print the 'b9VersionString'
runShowVersion :: MonadIO m => m ()
runShowVersion = liftIO $ putStrLn b9VersionString
-- | Execute the artifact generators defined in a list of text files.
Read the text files in the list and parse them as ' ArtifactGenerator 's
-- then 'mappend' them and apply 'buildArtifacts' to them.
runBuildArtifacts :: [FilePath] -> B9ConfigAction String
runBuildArtifacts buildFiles = do
generators <- mapM consult buildFiles
runB9 (buildArtifacts (mconcat generators))
| Read all text files and parse them as ' ArtifactGenerator 's .
-- Then overwrite the files with their contents but _pretty printed_
-- (i.e. formatted).
runFormatBuildFiles :: MonadIO m => [FilePath] -> m ()
runFormatBuildFiles buildFiles = liftIO $ do
generators <- mapM consult buildFiles
let generatorsFormatted = map ppShow (generators :: [ArtifactGenerator])
putStrLn `mapM_` generatorsFormatted
zipWithM_ writeFile buildFiles generatorsFormatted
-- | Upload a 'SharedImageName' to the default remote repository.
-- Note: The remote repository is specified in the 'B9Config'.
runPush :: SharedImageName -> B9ConfigAction ()
runPush name = localB9Config (keepTempDirs .~ False) $ runB9 $ do
conf <- getConfig
if isNothing (conf ^. repository)
then
errorExitL
"No repository specified! Use '-r' to specify a repo BEFORE 'push'."
else pushSharedImageLatestVersion name
-- | Either pull a list of available 'SharedImageName's from the remote
-- repository if 'Nothing' is passed as parameter, or pull the latest version
-- of the image from the remote repository. Note: The remote repository is
-- specified in the 'B9Config'.
runPull :: Maybe SharedImageName -> B9ConfigAction ()
runPull mName =
localB9Config
(keepTempDirs .~ False)
(runB9 (pullRemoteRepos >> maybePullImage))
where
maybePullImage =
mapM_
( \name -> pullLatestImage name >>= maybe (failPull name) (const (return ()))
)
mName
failPull name = errorExitL (printf "failed to pull: %s" (show name))
-- | Execute an interactive root shell in a running container from a
-- 'SharedImageName'.
runRun :: SharedImageName -> [String] -> B9ConfigAction String
runRun (SharedImageName name) cmdAndArgs =
localB9Config
((keepTempDirs .~ False) . (verbosity .~ Just LogTrace))
(runB9Interactive (buildArtifacts runCmdAndArgs))
where
runCmdAndArgs =
Artifact
(IID ("run-" ++ name))
( VmImages
[ImageTarget Transient (From name KeepSize) (MountPoint "/")]
( VmScript
X86_64
[SharedDirectory "." (MountPoint "/mnt/CWD")]
(Run (head cmdAndArgs') (tail cmdAndArgs'))
)
)
where
cmdAndArgs' = if null cmdAndArgs then ["/usr/bin/zsh"] else cmdAndArgs
-- | Delete all obsolete versions of all 'SharedImageName's.
runGcLocalRepoCache :: B9ConfigAction ()
runGcLocalRepoCache = localB9Config (keepTempDirs .~ False) (runB9 cleanLocalRepoCache)
TODO delete - too - many - revisions
-- | Clear the shared image cache for a remote. Note: The remote repository is
-- specified in the 'B9Config'.
runGcRemoteRepoCache :: B9ConfigAction ()
runGcRemoteRepoCache =
localB9Config
(keepTempDirs .~ False)
( runB9
( do
repos <- getSelectedRepos
cache <- getRepoCache
mapM_ (cleanRemoteRepo cache) repos
)
)
-- | Print a list of shared images cached locally or remotely, if a remote
-- repository was selected. Note: The remote repository is
-- specified in the 'B9Config'.
runListSharedImages :: B9ConfigAction (Set SharedImage)
runListSharedImages =
localB9Config
(keepTempDirs .~ False)
( runB9
( do
MkSelectedRemoteRepo remoteRepo <- getSelectedRemoteRepo
let repoPred = maybe (== Cache) ((==) . toRemoteRepository) remoteRepo
allRepos <- getRemoteRepos
if isNothing remoteRepo
then liftIO $ do
putStrLn "Showing local shared images only.\n"
putStrLn "To view the contents of a remote repo add"
putStrLn "the '-r' switch with one of the remote"
putStrLn "repository ids."
else
liftIO $
putStrLn
( "Showing shared images on: "
++ remoteRepoRepoId (fromJust remoteRepo)
)
unless (null allRepos) $ liftIO $ do
putStrLn "\nAvailable remote repositories:"
mapM_ (putStrLn . (" * " ++) . remoteRepoRepoId) allRepos
imgs <-
fold
. filterRepoImagesMap repoPred (const True)
<$> getSharedImages
if null imgs
then liftIO $ putStrLn "\n\nNO SHARED IMAGES\n"
else liftIO $ do
putStrLn ""
putStrLn $ prettyPrintSharedImages imgs
return imgs
)
)
| Check the SSH settings for a remote repository and add it to the user wide
B9 configuration file .
runAddRepo :: RemoteRepo -> B9ConfigAction ()
runAddRepo repo = do
repo' <- remoteRepoCheckSshPrivKey repo
modifyPermanentConfig
( Endo
( remoteRepos
%~ ( mappend (Set.singleton repo')
. Set.filter ((== remoteRepoRepoId repo') . remoteRepoRepoId)
)
)
)
-- | Find the most recent version of a 'SharedImageName' in the local image cache.
runLookupLocalSharedImage ::
SharedImageName -> B9ConfigAction (Maybe SharedImageBuildId)
runLookupLocalSharedImage n = runB9 $ do
traceL (printf "Searching for cached image: %s" (show n))
imgs <- lookupCachedImages n <$> getSharedImages
traceL "Candidate images: "
traceL (printf "%s\n" (prettyPrintSharedImages imgs))
let res = if null imgs then Nothing else Just (sharedImageBuildId (maximum imgs))
traceL (printf "Returning result: %s" (show res))
return res
| null | https://raw.githubusercontent.com/sheyll/b9-vm-image-builder/4d2af80d3be4decfce6c137ee284c961e3f4a396/src/lib/B9.hs | haskell | | B9 is a library and build tool with which one can create/convert different types
of VM images. Additionally installation steps - like installing software -
can be done in a LXC container, running on the disk images.
This module re-exports the modules needed to build a tool around the
library, e.g. see @src\/cli\/Main.hs@ as an example.
"B9.Artifact.Generator" is the module containing the basic data structure
formatted using `showVersion`.
| Just print the 'b9VersionString'
| Execute the artifact generators defined in a list of text files.
then 'mappend' them and apply 'buildArtifacts' to them.
Then overwrite the files with their contents but _pretty printed_
(i.e. formatted).
| Upload a 'SharedImageName' to the default remote repository.
Note: The remote repository is specified in the 'B9Config'.
| Either pull a list of available 'SharedImageName's from the remote
repository if 'Nothing' is passed as parameter, or pull the latest version
of the image from the remote repository. Note: The remote repository is
specified in the 'B9Config'.
| Execute an interactive root shell in a running container from a
'SharedImageName'.
| Delete all obsolete versions of all 'SharedImageName's.
| Clear the shared image cache for a remote. Note: The remote repository is
specified in the 'B9Config'.
| Print a list of shared images cached locally or remotely, if a remote
repository was selected. Note: The remote repository is
specified in the 'B9Config'.
| Find the most recent version of a 'SharedImageName' in the local image cache. | B9 allows to create and convert virtual machine image files as well as
related ISO and VFAT disk images for e.g. cloud - init configuration sources .
used to describe a B9 build .
module B9
( b9Version,
b9VersionString,
runShowVersion,
runBuildArtifacts,
runFormatBuildFiles,
runPush,
runPull,
runRun,
runGcLocalRepoCache,
runGcRemoteRepoCache,
runListSharedImages,
runAddRepo,
runLookupLocalSharedImage,
module X,
)
where
import B9.Artifact.Content as X
import B9.Artifact.Content.AST as X
import B9.Artifact.Content.CloudConfigYaml as X
import B9.Artifact.Content.ErlTerms as X
import B9.Artifact.Content.ErlangPropList as X
import B9.Artifact.Content.Readable as X
import B9.Artifact.Content.StringTemplate as X
import B9.Artifact.Content.YamlObject as X
import B9.Artifact.Readable as X
import B9.Artifact.Readable.Interpreter as X
import B9.B9Config as X
import B9.B9Error as X
import B9.B9Exec as X
import B9.B9Logging as X
import B9.B9Monad as X
import B9.BuildInfo as X
import B9.DiskImageBuilder as X
import B9.DiskImages as X
import B9.Environment as X
import B9.ExecEnv as X
import B9.QCUtil as X
import B9.Repository as X
import B9.RepositoryIO as X
import B9.ShellScript as X
import B9.Text as X
import B9.Vm as X
import B9.VmBuilder as X
import Control.Applicative as X
import Control.Lens as X
( (%~),
(&),
(.~),
Lens,
(^.),
)
import Control.Monad as X
import Control.Monad.IO.Class as X
import Control.Monad.Reader as X
( ReaderT,
ask,
local,
)
import Data.Foldable (fold)
import Data.List as X
import Data.Maybe as X
import Data.Monoid as X
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Version as X
import Paths_b9 (version)
import System.Exit as X
( ExitCode (..),
exitWith,
)
import System.FilePath as X
( (<.>),
(</>),
replaceExtension,
takeDirectory,
takeFileName,
)
import System.IO.B9Extras as X
import Text.Printf as X
( printf,
)
import Text.Show.Pretty as X
( ppShow,
)
| Return the cabal package version of the B9 library .
b9Version :: Version
b9Version = version
| Return the cabal package version of the B9 library ,
b9VersionString :: String
b9VersionString = showVersion version
runShowVersion :: MonadIO m => m ()
runShowVersion = liftIO $ putStrLn b9VersionString
Read the text files in the list and parse them as ' ArtifactGenerator 's
runBuildArtifacts :: [FilePath] -> B9ConfigAction String
runBuildArtifacts buildFiles = do
generators <- mapM consult buildFiles
runB9 (buildArtifacts (mconcat generators))
| Read all text files and parse them as ' ArtifactGenerator 's .
runFormatBuildFiles :: MonadIO m => [FilePath] -> m ()
runFormatBuildFiles buildFiles = liftIO $ do
generators <- mapM consult buildFiles
let generatorsFormatted = map ppShow (generators :: [ArtifactGenerator])
putStrLn `mapM_` generatorsFormatted
zipWithM_ writeFile buildFiles generatorsFormatted
runPush :: SharedImageName -> B9ConfigAction ()
runPush name = localB9Config (keepTempDirs .~ False) $ runB9 $ do
conf <- getConfig
if isNothing (conf ^. repository)
then
errorExitL
"No repository specified! Use '-r' to specify a repo BEFORE 'push'."
else pushSharedImageLatestVersion name
runPull :: Maybe SharedImageName -> B9ConfigAction ()
runPull mName =
localB9Config
(keepTempDirs .~ False)
(runB9 (pullRemoteRepos >> maybePullImage))
where
maybePullImage =
mapM_
( \name -> pullLatestImage name >>= maybe (failPull name) (const (return ()))
)
mName
failPull name = errorExitL (printf "failed to pull: %s" (show name))
runRun :: SharedImageName -> [String] -> B9ConfigAction String
runRun (SharedImageName name) cmdAndArgs =
localB9Config
((keepTempDirs .~ False) . (verbosity .~ Just LogTrace))
(runB9Interactive (buildArtifacts runCmdAndArgs))
where
runCmdAndArgs =
Artifact
(IID ("run-" ++ name))
( VmImages
[ImageTarget Transient (From name KeepSize) (MountPoint "/")]
( VmScript
X86_64
[SharedDirectory "." (MountPoint "/mnt/CWD")]
(Run (head cmdAndArgs') (tail cmdAndArgs'))
)
)
where
cmdAndArgs' = if null cmdAndArgs then ["/usr/bin/zsh"] else cmdAndArgs
runGcLocalRepoCache :: B9ConfigAction ()
runGcLocalRepoCache = localB9Config (keepTempDirs .~ False) (runB9 cleanLocalRepoCache)
TODO delete - too - many - revisions
runGcRemoteRepoCache :: B9ConfigAction ()
runGcRemoteRepoCache =
localB9Config
(keepTempDirs .~ False)
( runB9
( do
repos <- getSelectedRepos
cache <- getRepoCache
mapM_ (cleanRemoteRepo cache) repos
)
)
runListSharedImages :: B9ConfigAction (Set SharedImage)
runListSharedImages =
localB9Config
(keepTempDirs .~ False)
( runB9
( do
MkSelectedRemoteRepo remoteRepo <- getSelectedRemoteRepo
let repoPred = maybe (== Cache) ((==) . toRemoteRepository) remoteRepo
allRepos <- getRemoteRepos
if isNothing remoteRepo
then liftIO $ do
putStrLn "Showing local shared images only.\n"
putStrLn "To view the contents of a remote repo add"
putStrLn "the '-r' switch with one of the remote"
putStrLn "repository ids."
else
liftIO $
putStrLn
( "Showing shared images on: "
++ remoteRepoRepoId (fromJust remoteRepo)
)
unless (null allRepos) $ liftIO $ do
putStrLn "\nAvailable remote repositories:"
mapM_ (putStrLn . (" * " ++) . remoteRepoRepoId) allRepos
imgs <-
fold
. filterRepoImagesMap repoPred (const True)
<$> getSharedImages
if null imgs
then liftIO $ putStrLn "\n\nNO SHARED IMAGES\n"
else liftIO $ do
putStrLn ""
putStrLn $ prettyPrintSharedImages imgs
return imgs
)
)
| Check the SSH settings for a remote repository and add it to the user wide
B9 configuration file .
runAddRepo :: RemoteRepo -> B9ConfigAction ()
runAddRepo repo = do
repo' <- remoteRepoCheckSshPrivKey repo
modifyPermanentConfig
( Endo
( remoteRepos
%~ ( mappend (Set.singleton repo')
. Set.filter ((== remoteRepoRepoId repo') . remoteRepoRepoId)
)
)
)
runLookupLocalSharedImage ::
SharedImageName -> B9ConfigAction (Maybe SharedImageBuildId)
runLookupLocalSharedImage n = runB9 $ do
traceL (printf "Searching for cached image: %s" (show n))
imgs <- lookupCachedImages n <$> getSharedImages
traceL "Candidate images: "
traceL (printf "%s\n" (prettyPrintSharedImages imgs))
let res = if null imgs then Nothing else Just (sharedImageBuildId (maximum imgs))
traceL (printf "Returning result: %s" (show res))
return res
|
f7e411d5b5f5296a138553a864714a1974084ae58abcd9259e32f83245e2dca5 | rudymatela/leancheck | io.hs | Copyright ( c ) 2015 - 2020 .
-- Distributed under the 3-Clause BSD licence (see the file LICENSE).
import Test
main :: IO ()
main = do
check $ \x -> (x::Int) + x == 2*x -- should pass
check $ \x - > ( ) + x = = x -- should fail , falsifiable
check $ \x - > ( ) ` div ` x = = 1 -- should fail , exception
| null | https://raw.githubusercontent.com/rudymatela/leancheck/cb6f49fd11839dc922c6b1d9a428212755dae2ff/test/io.hs | haskell | Distributed under the 3-Clause BSD licence (see the file LICENSE).
should pass
should fail , falsifiable
should fail , exception | Copyright ( c ) 2015 - 2020 .
import Test
main :: IO ()
main = do
|
7d159c4ff21ec48cd93ce0aa9741df38d0aee7f35df156a5289fc3f4f9933b97 | foreverbell/project-euler-solutions | 286.hs | import qualified Data.MemoCombinators as Memo
import Text.Printf (printf)
prob :: Double -> Double
prob q = dp 50 20
where
dp n k = Memo.memo2 Memo.integral Memo.integral dp' n k
where
dp' 0 0 = 1
dp' n k | n < k = 0
| k < 0 = 0
| otherwise = (dp (n - 1) k) * (1 - hit) + (dp (n - 1) (k - 1)) * hit
where
hit = 1 - (fromIntegral n) / q
solve :: Double
solve = helper 50 53 0
where
helper l r iter | iter > 1000 = l
| v > 0.02 = helper mid r (iter + 1)
| otherwise = helper l mid (iter + 1)
where
mid = (l + r) / 2
v = prob mid
main = printf "%.10f\n" solve
| null | https://raw.githubusercontent.com/foreverbell/project-euler-solutions/c0bf2746aafce9be510892814e2d03e20738bf2b/src/286.hs | haskell | import qualified Data.MemoCombinators as Memo
import Text.Printf (printf)
prob :: Double -> Double
prob q = dp 50 20
where
dp n k = Memo.memo2 Memo.integral Memo.integral dp' n k
where
dp' 0 0 = 1
dp' n k | n < k = 0
| k < 0 = 0
| otherwise = (dp (n - 1) k) * (1 - hit) + (dp (n - 1) (k - 1)) * hit
where
hit = 1 - (fromIntegral n) / q
solve :: Double
solve = helper 50 53 0
where
helper l r iter | iter > 1000 = l
| v > 0.02 = helper mid r (iter + 1)
| otherwise = helper l mid (iter + 1)
where
mid = (l + r) / 2
v = prob mid
main = printf "%.10f\n" solve
| |
f6124da96f2e51e3ddab326a7a0fdb3635e3ff233ad72e0c061c0324990b7779 | Drezil/pioneers | Types.hs | # LANGUAGE TemplateHaskell #
module Types where
import Control.Concurrent.STM (TQueue, TVar, readTVar, writeTVar, atomically)
import qualified Graphics.Rendering.OpenGL.GL as GL
import Graphics.UI.SDL as SDL (Event, Window)
import Foreign.C (CFloat)
import qualified Data.HashMap.Strict as Map
import Data.Time (UTCTime)
import Linear.Matrix (M44)
import Linear (V3)
import Control.Monad.RWS.Strict (RWST, liftIO, get)
import Control.Monad.Writer.Strict
import Control . ( when )
import Control.Lens
import Graphics.Rendering.OpenGL.GL.Texturing.Objects (TextureObject)
import Render.Types
import System.IO
import Importer.IQM.Types
import UI.UIBase
import Map.Types (PlayMap)
data Coord3D a = Coord3D a a a
--Static Read-Only-State
data Env = Env
{ _eventsChan :: TQueue Event
, _windowObject :: !Window
, _zDistClosest :: !Double
, _zDistFarthest :: !Double
, : : ! GLContext
--, envFont :: TTF.TTFFont
-- , _renderer :: !Renderer
}
Mutable State
data Position = Position
{ __x :: !Double
, __y :: !Double
}
data WindowState = WindowState
{ _width :: !Int
, _height :: !Int
, _shouldClose :: !Bool
}
data CameraState = CameraState
{ _xAngle :: !Double
, _yAngle :: !Double
, _zDist :: !Double
, _frustum :: !(M44 CFloat)
, _camObject :: !Camera
}
data IOState = IOState
{ _clock :: !UTCTime
, _tessClockFactor :: !Double
, _tessClockTime :: !UTCTime
}
data GameState = GameState
{ _currentMap :: !PlayMap
}
data ArrowKeyState = ArrowKeyState {
_up :: !Bool
,_down :: !Bool
,_left :: !Bool
,_right :: !Bool
}
data KeyboardState = KeyboardState
{ _arrowsPressed :: !ArrowKeyState
}
| State in which all map - related Data is stored
--
The map itself is rendered with mapProgram and the shaders given here directly
-- This does not include any objects on the map - only the map itself
--
-- _mapTextures must contain the following Textures (in this ordering) after initialisation:
--
1 . Grass
--
2 . Sand
--
3 . Water
--
4 . Stone
--
5 . Snow
--
6 . Dirt ( blended on grass )
data GLMapState = GLMapState
{ _mapShaderData :: !MapShaderData
, _mapObjectShaderData :: !MapObjectShaderData
, _stateTessellationFactor :: !Int
, _stateMap :: !GL.BufferObject
, _mapVert :: !GL.NumArrayIndices
, _mapProgram :: !GL.Program
, _overviewTexture :: !TextureObject
, _shadowMapTexture :: !TextureObject
, _mapTextures :: ![TextureObject] --TODO: Fix size on list?
, _objectProgram :: !GL.Program
, _mapObjects :: ![MapObject]
, _shadowMapProgram :: !GL.Program
}
data MapShaderData = MapShaderData
{ shdrVertexIndex :: !GL.AttribLocation
, shdrColorIndex :: !GL.AttribLocation
, shdrNormalIndex :: !GL.AttribLocation
, shdrProjMatIndex :: !GL.UniformLocation
, shdrViewMatIndex :: !GL.UniformLocation
, shdrModelMatIndex :: !GL.UniformLocation
, shdrNormalMatIndex :: !GL.UniformLocation
, shdrTessInnerIndex :: !GL.UniformLocation
, shdrTessOuterIndex :: !GL.UniformLocation
}
data MapObjectShaderData = MapObjectShaderData
{ shdrMOVertexIndex :: !GL.AttribLocation
, shdrMOVertexOffsetIndex :: !GL.UniformLocation
, shdrMONormalIndex :: !GL.AttribLocation
, shdrMOTexIndex :: !GL.AttribLocation
, shdrMOProjMatIndex :: !GL.UniformLocation
, shdrMOViewMatIndex :: !GL.UniformLocation
, shdrMOModelMatIndex :: !GL.UniformLocation
, shdrMONormalMatIndex :: !GL.UniformLocation
, shdrMOTessInnerIndex :: !GL.UniformLocation
, shdrMOTessOuterIndex :: !GL.UniformLocation
}
data MapObject = MapObject !IQM !MapCoordinates !MapObjectState
data MapObjectState = MapObjectState ()
type MapCoordinates = V3 CFloat
data GLHud = GLHud
^ HUD - Texture itself
, _hudTexIndex :: !GL.UniformLocation -- ^ Position of Overlay-Texture in Shader
, _hudBackIndex :: !GL.UniformLocation -- ^ Position of Background-Texture in Shader
^ Position of Vertices in Shader
, _hudVert :: !GL.NumArrayIndices -- ^ Number of Vertices to draw
, _hudVBO :: !GL.BufferObject -- ^ Vertex-Buffer-Object
, _hudEBO :: !GL.BufferObject -- ^ Element-Buffer-Object
^ Program for rendering HUD
}
data GLState = GLState
{ _glMap :: !GLMapState
, _glHud :: !GLHud
, _glRenderbuffer :: !GL.RenderbufferObject
, _glFramebuffer :: !GL.FramebufferObject
}
data UIState = UIState
{ _uiHasChanged :: !Bool
, _uiMap :: Map.HashMap UIId (GUIWidget Pioneers)
, _uiObserverEvents :: Map.HashMap EventKey [EventHandler Pioneers]
, _uiRoots :: !([UIId])
, _uiButtonState :: !UIButtonState
}
data State = State
{ _window :: !WindowState
, _camera :: TVar CameraState
, _mapTexture :: TVar TextureObject
, _mapDepthTexture :: TVar TextureObject
, _camStack :: (Map.HashMap UIId (TVar CameraState, TVar TextureObject))
, _io :: !IOState
, _keyboard :: !KeyboardState
, _gl :: !GLState
, _game :: TVar GameState
, _ui :: !UIState
}
data Entry = Log {msg::String} deriving Eq
instance Show Entry where
show (Log s) = s
type Logger = WriterT [Entry] IO Handle
type Pioneers = RWST Env () State IO
when using TemplateHaskell order of declaration matters
$(makeLenses ''State)
$(makeLenses ''GLState)
$(makeLenses ''GLMapState)
$(makeLenses ''GLHud)
$(makeLenses ''KeyboardState)
$(makeLenses ''ArrowKeyState)
$(makeLenses ''GameState)
$(makeLenses ''IOState)
$(makeLenses ''CameraState)
$(makeLenses ''WindowState)
$(makeLenses ''Position)
$(makeLenses ''Env)
$(makeLenses ''UIState)
-- helper-functions for types
-- | atomically change gamestate on condition
changeIfGamestate :: (GameState -> Bool) -> (GameState -> GameState) -> Pioneers Bool
changeIfGamestate cond f = do
state <- get
liftIO $ atomically $ do
game' <- readTVar (state ^. game)
let cond' = cond game'
when cond' (writeTVar (state ^. game) (f game'))
return cond'
-- | atomically change gamestate
changeGamestate :: (GameState -> GameState) -> Pioneers ()
changeGamestate s = do
--forget implied result - is True anyway
_ <- changeIfGamestate (const True) s
return ()
| null | https://raw.githubusercontent.com/Drezil/pioneers/2a9de00213144cfa870e9b71255a92a905dec3a9/src/Types.hs | haskell | Static Read-Only-State
, envFont :: TTF.TTFFont
, _renderer :: !Renderer
This does not include any objects on the map - only the map itself
_mapTextures must contain the following Textures (in this ordering) after initialisation:
TODO: Fix size on list?
^ Position of Overlay-Texture in Shader
^ Position of Background-Texture in Shader
^ Number of Vertices to draw
^ Vertex-Buffer-Object
^ Element-Buffer-Object
helper-functions for types
| atomically change gamestate on condition
| atomically change gamestate
forget implied result - is True anyway | # LANGUAGE TemplateHaskell #
module Types where
import Control.Concurrent.STM (TQueue, TVar, readTVar, writeTVar, atomically)
import qualified Graphics.Rendering.OpenGL.GL as GL
import Graphics.UI.SDL as SDL (Event, Window)
import Foreign.C (CFloat)
import qualified Data.HashMap.Strict as Map
import Data.Time (UTCTime)
import Linear.Matrix (M44)
import Linear (V3)
import Control.Monad.RWS.Strict (RWST, liftIO, get)
import Control.Monad.Writer.Strict
import Control . ( when )
import Control.Lens
import Graphics.Rendering.OpenGL.GL.Texturing.Objects (TextureObject)
import Render.Types
import System.IO
import Importer.IQM.Types
import UI.UIBase
import Map.Types (PlayMap)
data Coord3D a = Coord3D a a a
data Env = Env
{ _eventsChan :: TQueue Event
, _windowObject :: !Window
, _zDistClosest :: !Double
, _zDistFarthest :: !Double
, : : ! GLContext
}
Mutable State
data Position = Position
{ __x :: !Double
, __y :: !Double
}
data WindowState = WindowState
{ _width :: !Int
, _height :: !Int
, _shouldClose :: !Bool
}
data CameraState = CameraState
{ _xAngle :: !Double
, _yAngle :: !Double
, _zDist :: !Double
, _frustum :: !(M44 CFloat)
, _camObject :: !Camera
}
data IOState = IOState
{ _clock :: !UTCTime
, _tessClockFactor :: !Double
, _tessClockTime :: !UTCTime
}
data GameState = GameState
{ _currentMap :: !PlayMap
}
data ArrowKeyState = ArrowKeyState {
_up :: !Bool
,_down :: !Bool
,_left :: !Bool
,_right :: !Bool
}
data KeyboardState = KeyboardState
{ _arrowsPressed :: !ArrowKeyState
}
| State in which all map - related Data is stored
The map itself is rendered with mapProgram and the shaders given here directly
1 . Grass
2 . Sand
3 . Water
4 . Stone
5 . Snow
6 . Dirt ( blended on grass )
data GLMapState = GLMapState
{ _mapShaderData :: !MapShaderData
, _mapObjectShaderData :: !MapObjectShaderData
, _stateTessellationFactor :: !Int
, _stateMap :: !GL.BufferObject
, _mapVert :: !GL.NumArrayIndices
, _mapProgram :: !GL.Program
, _overviewTexture :: !TextureObject
, _shadowMapTexture :: !TextureObject
, _objectProgram :: !GL.Program
, _mapObjects :: ![MapObject]
, _shadowMapProgram :: !GL.Program
}
data MapShaderData = MapShaderData
{ shdrVertexIndex :: !GL.AttribLocation
, shdrColorIndex :: !GL.AttribLocation
, shdrNormalIndex :: !GL.AttribLocation
, shdrProjMatIndex :: !GL.UniformLocation
, shdrViewMatIndex :: !GL.UniformLocation
, shdrModelMatIndex :: !GL.UniformLocation
, shdrNormalMatIndex :: !GL.UniformLocation
, shdrTessInnerIndex :: !GL.UniformLocation
, shdrTessOuterIndex :: !GL.UniformLocation
}
data MapObjectShaderData = MapObjectShaderData
{ shdrMOVertexIndex :: !GL.AttribLocation
, shdrMOVertexOffsetIndex :: !GL.UniformLocation
, shdrMONormalIndex :: !GL.AttribLocation
, shdrMOTexIndex :: !GL.AttribLocation
, shdrMOProjMatIndex :: !GL.UniformLocation
, shdrMOViewMatIndex :: !GL.UniformLocation
, shdrMOModelMatIndex :: !GL.UniformLocation
, shdrMONormalMatIndex :: !GL.UniformLocation
, shdrMOTessInnerIndex :: !GL.UniformLocation
, shdrMOTessOuterIndex :: !GL.UniformLocation
}
data MapObject = MapObject !IQM !MapCoordinates !MapObjectState
data MapObjectState = MapObjectState ()
type MapCoordinates = V3 CFloat
data GLHud = GLHud
^ HUD - Texture itself
^ Position of Vertices in Shader
^ Program for rendering HUD
}
data GLState = GLState
{ _glMap :: !GLMapState
, _glHud :: !GLHud
, _glRenderbuffer :: !GL.RenderbufferObject
, _glFramebuffer :: !GL.FramebufferObject
}
data UIState = UIState
{ _uiHasChanged :: !Bool
, _uiMap :: Map.HashMap UIId (GUIWidget Pioneers)
, _uiObserverEvents :: Map.HashMap EventKey [EventHandler Pioneers]
, _uiRoots :: !([UIId])
, _uiButtonState :: !UIButtonState
}
data State = State
{ _window :: !WindowState
, _camera :: TVar CameraState
, _mapTexture :: TVar TextureObject
, _mapDepthTexture :: TVar TextureObject
, _camStack :: (Map.HashMap UIId (TVar CameraState, TVar TextureObject))
, _io :: !IOState
, _keyboard :: !KeyboardState
, _gl :: !GLState
, _game :: TVar GameState
, _ui :: !UIState
}
data Entry = Log {msg::String} deriving Eq
instance Show Entry where
show (Log s) = s
type Logger = WriterT [Entry] IO Handle
type Pioneers = RWST Env () State IO
when using TemplateHaskell order of declaration matters
$(makeLenses ''State)
$(makeLenses ''GLState)
$(makeLenses ''GLMapState)
$(makeLenses ''GLHud)
$(makeLenses ''KeyboardState)
$(makeLenses ''ArrowKeyState)
$(makeLenses ''GameState)
$(makeLenses ''IOState)
$(makeLenses ''CameraState)
$(makeLenses ''WindowState)
$(makeLenses ''Position)
$(makeLenses ''Env)
$(makeLenses ''UIState)
changeIfGamestate :: (GameState -> Bool) -> (GameState -> GameState) -> Pioneers Bool
changeIfGamestate cond f = do
state <- get
liftIO $ atomically $ do
game' <- readTVar (state ^. game)
let cond' = cond game'
when cond' (writeTVar (state ^. game) (f game'))
return cond'
changeGamestate :: (GameState -> GameState) -> Pioneers ()
changeGamestate s = do
_ <- changeIfGamestate (const True) s
return ()
|
4bfbb879dd2ec63e0ad079109752564dde5cc5f41d5a07831a16b990f866d2b3 | SecPriv/webspec | serviceworker.mli | (********************************************************************************)
Copyright ( c ) 2022
(* *)
(* 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. *)
(* *)
(********************************************************************************)
module type S =
sig
val s_response : States.VerifierState.t -> int -> string
val s_request : States.VerifierState.t -> int -> string
RoundTrip - related functions
end
module ServiceWorker : S
| null | https://raw.githubusercontent.com/SecPriv/webspec/b7ff6b714b3a4b572c108cc3136506da3d263eff/verifier/src/serviceworker.mli | ocaml | ******************************************************************************
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.
****************************************************************************** | Copyright ( c ) 2022
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
module type S =
sig
val s_response : States.VerifierState.t -> int -> string
val s_request : States.VerifierState.t -> int -> string
RoundTrip - related functions
end
module ServiceWorker : S
|
2f368a07f8cdf0805ef05b9c90d6c0a09be9ad6c3a9e8db4f67aad0c87103250 | LaurentMazare/btc-ocaml | common.ml | open Core.Std
let consume_compact_uint iobuf =
let len_len = Iobuf.Consume.uint8 iobuf in
if len_len <= 252 then len_len
else if len_len = 253 then Iobuf.Consume.uint16_le iobuf
else if len_len = 254 then Iobuf.Consume.uint32_le iobuf
else if len_len = 255 then Iobuf.Consume.int64_le_trunc iobuf
else failwithf "incorrect len len %d" len_len ()
let fill_compact_uint iobuf int =
if int <= 252 then
Iobuf.Fill.uint8 iobuf int
else if int <= 0xFFFF then
Iobuf.Fill.uint16_le iobuf int
else if int <= 0xFFFFFFFF then
Iobuf.Fill.uint32_le iobuf int
else
Iobuf.Fill.int64_le_trunc iobuf int
| null | https://raw.githubusercontent.com/LaurentMazare/btc-ocaml/0616d7853d807e50dc9ff83c6783b80f71640da2/common.ml | ocaml | open Core.Std
let consume_compact_uint iobuf =
let len_len = Iobuf.Consume.uint8 iobuf in
if len_len <= 252 then len_len
else if len_len = 253 then Iobuf.Consume.uint16_le iobuf
else if len_len = 254 then Iobuf.Consume.uint32_le iobuf
else if len_len = 255 then Iobuf.Consume.int64_le_trunc iobuf
else failwithf "incorrect len len %d" len_len ()
let fill_compact_uint iobuf int =
if int <= 252 then
Iobuf.Fill.uint8 iobuf int
else if int <= 0xFFFF then
Iobuf.Fill.uint16_le iobuf int
else if int <= 0xFFFFFFFF then
Iobuf.Fill.uint32_le iobuf int
else
Iobuf.Fill.int64_le_trunc iobuf int
| |
2729ad514e0b9bcb2f45d803b57bd542a29fb11272b02e7a059f2cbf02f2be12 | nha/boot-uglify | nashorn.clj | (ns nha.boot-uglify.nashorn
(:require [clojure.java.io :as io]
[clojure.string :as string])
(:import
[java.io StringWriter FileInputStream FileOutputStream File]
[javax.script ScriptEngine ScriptEngineManager ScriptException ScriptEngineFactory]
[org.apache.commons.lang3 StringEscapeUtils]
[java.util.zip GZIPOutputStream]
[java.util.logging Level]))
;;;;;;;;;;;;;
;; Nashorn ;;
;;;;;;;;;;;;;
(defn create-engine
"Create a JS engine
Stolen from ClojureScript"
([] (create-engine nil))
([{:keys [code-cache] :or {code-cache true}}]
(let [args (when code-cache ["-pcc"])
factories (.getEngineFactories (ScriptEngineManager.))
factory (get (zipmap (map #(.getEngineName %) factories) factories) "Oracle Nashorn")]
(if-let [engine (if-not (empty? args)
(.getScriptEngine ^ScriptEngineFactory factory (into-array args))
(.getScriptEngine ^ScriptEngineFactory factory))]
(let [context (.getContext engine)]
(.setWriter context *out*)
(.setErrorWriter context *err*)
engine)
(throw (IllegalArgumentException.
"Cannot find the Nashorn script engine, use a JDK version 8 or higher."))))))
(defn get-context
"get the context from an engine"
[^ScriptEngine engine]
(.getContext engine))
(defn set-writer!
"set the writer of an engine"
[context writer]
(.setWriter context writer))
(defn eval-str
"evaluate a string into an engine
returns nil - the result is contained in the engine"
([^String s] (eval-str (create-engine) s))
([^ScriptEngine engine ^String s]
(try
{:out (.eval engine s)
:error nil}
(catch Exception e
{:s nil
:error e}))))
(defn eval-resource
"Evaluate a file on the classpath in the engine."
([path] (eval-resource (create-engine) path))
([^ScriptEngine engine path]
(eval-str engine (slurp (io/resource path)))))
(comment
(eval-str "var a = 3; print(\"OK\")")
(eval-str (slurp (io/resource "Uglify2/uglifyjs.self.js")))
)
| null | https://raw.githubusercontent.com/nha/boot-uglify/df0cffb2734bdd1db2be1fab5fcefdda5f735e68/src/nha/boot_uglify/nashorn.clj | clojure |
Nashorn ;;
| (ns nha.boot-uglify.nashorn
(:require [clojure.java.io :as io]
[clojure.string :as string])
(:import
[java.io StringWriter FileInputStream FileOutputStream File]
[javax.script ScriptEngine ScriptEngineManager ScriptException ScriptEngineFactory]
[org.apache.commons.lang3 StringEscapeUtils]
[java.util.zip GZIPOutputStream]
[java.util.logging Level]))
(defn create-engine
"Create a JS engine
Stolen from ClojureScript"
([] (create-engine nil))
([{:keys [code-cache] :or {code-cache true}}]
(let [args (when code-cache ["-pcc"])
factories (.getEngineFactories (ScriptEngineManager.))
factory (get (zipmap (map #(.getEngineName %) factories) factories) "Oracle Nashorn")]
(if-let [engine (if-not (empty? args)
(.getScriptEngine ^ScriptEngineFactory factory (into-array args))
(.getScriptEngine ^ScriptEngineFactory factory))]
(let [context (.getContext engine)]
(.setWriter context *out*)
(.setErrorWriter context *err*)
engine)
(throw (IllegalArgumentException.
"Cannot find the Nashorn script engine, use a JDK version 8 or higher."))))))
(defn get-context
"get the context from an engine"
[^ScriptEngine engine]
(.getContext engine))
(defn set-writer!
"set the writer of an engine"
[context writer]
(.setWriter context writer))
(defn eval-str
"evaluate a string into an engine
returns nil - the result is contained in the engine"
([^String s] (eval-str (create-engine) s))
([^ScriptEngine engine ^String s]
(try
{:out (.eval engine s)
:error nil}
(catch Exception e
{:s nil
:error e}))))
(defn eval-resource
"Evaluate a file on the classpath in the engine."
([path] (eval-resource (create-engine) path))
([^ScriptEngine engine path]
(eval-str engine (slurp (io/resource path)))))
(comment
(eval-str "var a = 3; print(\"OK\")")
(eval-str (slurp (io/resource "Uglify2/uglifyjs.self.js")))
)
|
d8b7cb81d7740f5498c1a57ac33d7c62fb34e79acd7729b468dd41da256e6082 | tari3x/csec-modex | cfg.ml |
*
* Copyright ( c ) 2001 - 2003 ,
* < >
* < >
* < >
* < >
* S.P Rahul ,
* All rights reserved .
*
* Redistribution and use in source and binary forms , with or without
* modification , are permitted provided that the following conditions are
* met :
*
* 1 . Redistributions of source code must retain the above copyright
* notice , this list of conditions and the following disclaimer .
*
* 2 . Redistributions in binary form must reproduce the above copyright
* notice , this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution .
*
* 3 . The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission .
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS
* IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED
* TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL ,
* EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO ,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR
* PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
* NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE .
*
*
* Copyright (c) 2001-2003,
* George C. Necula <>
* Scott McPeak <>
* Wes Weimer <>
* Simon Goldsmith <>
* S.P Rahul, Aman Bhargava
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*)
Authors : ,
(* sfg: this stuff was stolen from optim.ml - the code to print the cfg as
a dot graph is mine *)
open Pretty
open Cil
module E=Errormsg
(* entry points: cfgFun, printCfgChannel, printCfgFilename *)
known issues :
* -sucessors of if somehow end up with two edges each
* -sucessors of if somehow end up with two edges each
*)
(*------------------------------------------------------------*)
Notes regarding CFG computation :
1 ) Initially only succs and are computed . 's are filled in
later , in whatever order is suitable ( e.g. for forward problems , reverse
depth - first postorder ) .
2 ) If a stmt ( return , break or continue ) has no successors , then
function return must follow .
No predecessors means it is the start of the function
3 ) We use the fact that initially all the succs and are assigned [ ]
1) Initially only succs and preds are computed. sid's are filled in
later, in whatever order is suitable (e.g. for forward problems, reverse
depth-first postorder).
2) If a stmt (return, break or continue) has no successors, then
function return must follow.
No predecessors means it is the start of the function
3) We use the fact that initially all the succs and preds are assigned []
*)
Fill in the CFG info for the stmts in a block
next = succ of the last stmt in this block
break = succ of any Break in this block
cont = succ of any Continue in this block
None means the succ is the function return . It does not mean the break / cont
is invalid . We assume the validity has already been checked .
rlabels = list of potential successors of computed ( ie . every labelled
statement whose address is retained )
next = succ of the last stmt in this block
break = succ of any Break in this block
cont = succ of any Continue in this block
None means the succ is the function return. It does not mean the break/cont
is invalid. We assume the validity has already been checked.
rlabels = list of potential successors of computed gotos (ie. every labelled
statement whose address is retained)
*)
let start_id = ref 0 (* for unique ids across many functions *)
class caseLabeledStmtFinder slr = object(self)
inherit nopCilVisitor
method vstmt s =
if List.exists (fun l ->
match l with | Case _ | CaseRange _ | Default _ -> true | _ -> false)
s.labels
then begin
slr := s :: (!slr);
match s.skind with
| Switch(_,_,_,_) -> SkipChildren
| _ -> DoChildren
end else match s.skind with
| Switch(_,_,_,_) -> SkipChildren
| _ -> DoChildren
end
let findCaseLabeledStmts (b : block) : stmt list =
let slr = ref [] in
let vis = new caseLabeledStmtFinder slr in
ignore(visitCilBlock vis b);
!slr
class addrOfLabelFinder slr = object(self)
inherit nopCilVisitor
method vexpr e = match e with
| AddrOfLabel sref ->
slr := !sref :: (!slr);
SkipChildren
| _ -> DoChildren
end
let findAddrOfLabelStmts (b : block) : stmt list =
let slr = ref [] in
let vis = new addrOfLabelFinder slr in
ignore(visitCilBlock vis b);
!slr
(* entry point *)
* Compute a control flow graph for fd . Stmts in fd have preds and filled in
filled in *)
let rec cfgFun (fd : fundec): int =
begin
let initial_id = !start_id in
let nodeList = ref [] in
let rlabels = findAddrOfLabelStmts fd.sbody in
cfgBlock fd.sbody None None None nodeList rlabels;
fd.smaxstmtid <- Some(!start_id);
fd.sallstmts <- List.rev !nodeList;
!start_id - initial_id
end
and cfgStmts (ss: stmt list)
(next:stmt option) (break:stmt option) (cont:stmt option)
(nodeList:stmt list ref) (rlabels: stmt list) =
match ss with
[] -> ();
| [s] -> cfgStmt s next break cont nodeList rlabels
| hd::tl ->
cfgStmt hd (Some (List.hd tl)) break cont nodeList rlabels;
cfgStmts tl next break cont nodeList rlabels
and cfgBlock (blk: block)
(next:stmt option) (break:stmt option) (cont:stmt option)
(nodeList:stmt list ref) (rlabels: stmt list) =
cfgStmts blk.bstmts next break cont nodeList rlabels
Fill in the CFG info for a stmt
Meaning of next , break , cont should be clear from earlier comment
Meaning of next, break, cont should be clear from earlier comment
*)
and cfgStmt (s: stmt) (next:stmt option) (break:stmt option) (cont:stmt option)
(nodeList:stmt list ref) (rlabels: stmt list) =
incr start_id;
s.sid <- !start_id;
nodeList := s :: !nodeList; (* Future traversals can be made in linear time. e.g. *)
if s.succs <> [] then begin
(*E.s*)ignore (bug "CFG must be cleared before being computed!");
raise (Failure "CFG bug")
end;
let addSucc (n: stmt) =
if not (List.memq n s.succs) then
s.succs <- n::s.succs;
if not (List.memq s n.preds) then
n.preds <- s::n.preds
in
let addOptionSucc (n: stmt option) =
match n with
None -> ()
| Some n' -> addSucc n'
in
let addBlockSucc (b: block) (n: stmt option) =
Add the first statement in b as a successor to the current stmt .
Or , if b is empty , add n as a successor
Or, if b is empty, add n as a successor *)
match b.bstmts with
[] -> addOptionSucc n
| hd::_ -> addSucc hd
in
let instrFallsThrough (i : instr) : bool = match i with
Call (_, Lval (Var vf, NoOffset), _, _) ->
See if this has the noreturn attribute
not (hasAttribute "noreturn" vf.vattr)
| Call (_, f, _, _) ->
not (hasAttribute "noreturn" (typeAttrs (typeOf f)))
| _ -> true
in
match s.skind with
Instr il ->
if List.for_all instrFallsThrough il then
addOptionSucc next
else
()
| Return _ -> ()
| Goto (p,_) -> addSucc !p
| ComputedGoto (e,_) -> List.iter addSucc rlabels
| Break _ -> addOptionSucc break
| Continue _ -> addOptionSucc cont
| If (_, blk1, blk2, _) ->
(* The succs of If is [true branch;false branch] *)
addBlockSucc blk2 next;
addBlockSucc blk1 next;
cfgBlock blk1 next break cont nodeList rlabels;
cfgBlock blk2 next break cont nodeList rlabels
| Block b ->
addBlockSucc b next;
cfgBlock b next break cont nodeList rlabels
| Switch(_,blk,l,_) ->
let bl = findCaseLabeledStmts blk in
List.iter addSucc (List.rev bl(*l*)); (* Add successors in order *)
(* sfg: if there's no default, need to connect s->next *)
if not (List.exists
(fun stmt -> List.exists
(function Default _ -> true | _ -> false)
stmt.labels)
bl)
then
addOptionSucc next;
cfgBlock blk next next cont nodeList rlabels
| Loop(blk, loc, s1, s2) ->
s.skind <- Loop(blk, loc, (Some s), next);
addBlockSucc blk (Some s);
cfgBlock blk (Some s) next (Some s) nodeList rlabels
Since all loops have terminating condition true , we do n't put
any direct successor to stmt following the loop
any direct successor to stmt following the loop *)
| TryExcept _ | TryFinally _ ->
E.s (E.unimp "try/except/finally")
(*------------------------------------------------------------*)
(**************************************************************)
do something for all stmts in a fundec
let rec forallStmts (todo) (fd : fundec) =
begin
fasBlock todo fd.sbody;
end
and fasBlock (todo) (b : block) =
List.iter (fasStmt todo) b.bstmts
and fasStmt (todo) (s : stmt) =
begin
ignore(todo s);
match s.skind with
| Block b -> fasBlock todo b
| If (_, tb, fb, _) -> (fasBlock todo tb; fasBlock todo fb)
| Switch (_, b, _, _) -> fasBlock todo b
| Loop (b, _, _, _) -> fasBlock todo b
| (Return _ | Break _ | Continue _ | Goto _ | ComputedGoto _ | Instr _) -> ()
| TryExcept _ | TryFinally _ -> E.s (E.unimp "try/except/finally")
end
;;
(**************************************************************)
printing the control flow graph - you have to compute it first
let d_cfgnodename () (s : stmt) =
dprintf "%d" s.sid
let d_cfgnodelabel () (s : stmt) =
let label =
begin
match s.skind with
sprint ~width:999 ( " if % a " d_exp e )
| Loop _ -> "loop"
| Break _ -> "break"
| Continue _ -> "continue"
| Goto _ | ComputedGoto _ -> "goto"
| Instr _ -> "instr"
| Switch _ -> "switch"
| Block _ -> "block"
| Return _ -> "return"
| TryExcept _ -> "try-except"
| TryFinally _ -> "try-finally"
end in
dprintf "%d: %s" s.sid label
let d_cfgedge (src) () (dest) =
dprintf "%a -> %a"
d_cfgnodename src
d_cfgnodename dest
let d_cfgnode () (s : stmt) =
dprintf "%a [label=\"%a\"]\n\t%a"
d_cfgnodename s
d_cfgnodelabel s
(d_list "\n\t" (d_cfgedge s)) s.succs
(**********************************************************************)
(* entry points *)
* print control flow graph ( in dot form ) for fundec to channel
let printCfgChannel (chan : out_channel) (fd : fundec) =
let pnode (s:stmt) = fprintf chan "%a\n" d_cfgnode s in
begin
ignore (fprintf chan "digraph CFG_%s {\n" fd.svar.vname);
forallStmts pnode fd;
ignore(fprintf chan "}\n");
end
* Print control flow graph ( in dot form ) for fundec to file
let printCfgFilename (filename : string) (fd : fundec) =
let chan = open_out filename in
begin
printCfgChannel chan fd;
close_out chan;
end
;;
(**********************************************************************)
let clearCFGinfo (fd : fundec) =
let clear s =
s.sid <- -1;
s.succs <- [];
s.preds <- [];
in
forallStmts clear fd
let clearFileCFG (f : file) =
start_id := 0;
iterGlobals f (fun g ->
match g with GFun(fd,_) ->
clearCFGinfo fd
| _ -> ())
let computeFileCFG (f : file) =
iterGlobals f (fun g ->
match g with GFun(fd,_) ->
ignore(cfgFun fd)
| _ -> ())
let allStmts (f : file) : stmt list =
foldGlobals f
(fun accu g ->
match g with
| GFun (f,l) -> f.sallstmts @ accu
| _ -> accu
) []
| null | https://raw.githubusercontent.com/tari3x/csec-modex/5ab2aa18ef308b4d18ac479e5ab14476328a6a50/deps/cil-1.7.3/src/ext/cfg.ml | ocaml | sfg: this stuff was stolen from optim.ml - the code to print the cfg as
a dot graph is mine
entry points: cfgFun, printCfgChannel, printCfgFilename
------------------------------------------------------------
for unique ids across many functions
entry point
Future traversals can be made in linear time. e.g.
E.s
The succs of If is [true branch;false branch]
l
Add successors in order
sfg: if there's no default, need to connect s->next
------------------------------------------------------------
************************************************************
************************************************************
********************************************************************
entry points
******************************************************************** |
*
* Copyright ( c ) 2001 - 2003 ,
* < >
* < >
* < >
* < >
* S.P Rahul ,
* All rights reserved .
*
* Redistribution and use in source and binary forms , with or without
* modification , are permitted provided that the following conditions are
* met :
*
* 1 . Redistributions of source code must retain the above copyright
* notice , this list of conditions and the following disclaimer .
*
* 2 . Redistributions in binary form must reproduce the above copyright
* notice , this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution .
*
* 3 . The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission .
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS
* IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED
* TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL ,
* EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO ,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR
* PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
* NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE .
*
*
* Copyright (c) 2001-2003,
* George C. Necula <>
* Scott McPeak <>
* Wes Weimer <>
* Simon Goldsmith <>
* S.P Rahul, Aman Bhargava
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*)
Authors : ,
open Pretty
open Cil
module E=Errormsg
known issues :
* -sucessors of if somehow end up with two edges each
* -sucessors of if somehow end up with two edges each
*)
Notes regarding CFG computation :
1 ) Initially only succs and are computed . 's are filled in
later , in whatever order is suitable ( e.g. for forward problems , reverse
depth - first postorder ) .
2 ) If a stmt ( return , break or continue ) has no successors , then
function return must follow .
No predecessors means it is the start of the function
3 ) We use the fact that initially all the succs and are assigned [ ]
1) Initially only succs and preds are computed. sid's are filled in
later, in whatever order is suitable (e.g. for forward problems, reverse
depth-first postorder).
2) If a stmt (return, break or continue) has no successors, then
function return must follow.
No predecessors means it is the start of the function
3) We use the fact that initially all the succs and preds are assigned []
*)
Fill in the CFG info for the stmts in a block
next = succ of the last stmt in this block
break = succ of any Break in this block
cont = succ of any Continue in this block
None means the succ is the function return . It does not mean the break / cont
is invalid . We assume the validity has already been checked .
rlabels = list of potential successors of computed ( ie . every labelled
statement whose address is retained )
next = succ of the last stmt in this block
break = succ of any Break in this block
cont = succ of any Continue in this block
None means the succ is the function return. It does not mean the break/cont
is invalid. We assume the validity has already been checked.
rlabels = list of potential successors of computed gotos (ie. every labelled
statement whose address is retained)
*)
class caseLabeledStmtFinder slr = object(self)
inherit nopCilVisitor
method vstmt s =
if List.exists (fun l ->
match l with | Case _ | CaseRange _ | Default _ -> true | _ -> false)
s.labels
then begin
slr := s :: (!slr);
match s.skind with
| Switch(_,_,_,_) -> SkipChildren
| _ -> DoChildren
end else match s.skind with
| Switch(_,_,_,_) -> SkipChildren
| _ -> DoChildren
end
let findCaseLabeledStmts (b : block) : stmt list =
let slr = ref [] in
let vis = new caseLabeledStmtFinder slr in
ignore(visitCilBlock vis b);
!slr
class addrOfLabelFinder slr = object(self)
inherit nopCilVisitor
method vexpr e = match e with
| AddrOfLabel sref ->
slr := !sref :: (!slr);
SkipChildren
| _ -> DoChildren
end
let findAddrOfLabelStmts (b : block) : stmt list =
let slr = ref [] in
let vis = new addrOfLabelFinder slr in
ignore(visitCilBlock vis b);
!slr
* Compute a control flow graph for fd . Stmts in fd have preds and filled in
filled in *)
let rec cfgFun (fd : fundec): int =
begin
let initial_id = !start_id in
let nodeList = ref [] in
let rlabels = findAddrOfLabelStmts fd.sbody in
cfgBlock fd.sbody None None None nodeList rlabels;
fd.smaxstmtid <- Some(!start_id);
fd.sallstmts <- List.rev !nodeList;
!start_id - initial_id
end
and cfgStmts (ss: stmt list)
(next:stmt option) (break:stmt option) (cont:stmt option)
(nodeList:stmt list ref) (rlabels: stmt list) =
match ss with
[] -> ();
| [s] -> cfgStmt s next break cont nodeList rlabels
| hd::tl ->
cfgStmt hd (Some (List.hd tl)) break cont nodeList rlabels;
cfgStmts tl next break cont nodeList rlabels
and cfgBlock (blk: block)
(next:stmt option) (break:stmt option) (cont:stmt option)
(nodeList:stmt list ref) (rlabels: stmt list) =
cfgStmts blk.bstmts next break cont nodeList rlabels
Fill in the CFG info for a stmt
Meaning of next , break , cont should be clear from earlier comment
Meaning of next, break, cont should be clear from earlier comment
*)
and cfgStmt (s: stmt) (next:stmt option) (break:stmt option) (cont:stmt option)
(nodeList:stmt list ref) (rlabels: stmt list) =
incr start_id;
s.sid <- !start_id;
if s.succs <> [] then begin
raise (Failure "CFG bug")
end;
let addSucc (n: stmt) =
if not (List.memq n s.succs) then
s.succs <- n::s.succs;
if not (List.memq s n.preds) then
n.preds <- s::n.preds
in
let addOptionSucc (n: stmt option) =
match n with
None -> ()
| Some n' -> addSucc n'
in
let addBlockSucc (b: block) (n: stmt option) =
Add the first statement in b as a successor to the current stmt .
Or , if b is empty , add n as a successor
Or, if b is empty, add n as a successor *)
match b.bstmts with
[] -> addOptionSucc n
| hd::_ -> addSucc hd
in
let instrFallsThrough (i : instr) : bool = match i with
Call (_, Lval (Var vf, NoOffset), _, _) ->
See if this has the noreturn attribute
not (hasAttribute "noreturn" vf.vattr)
| Call (_, f, _, _) ->
not (hasAttribute "noreturn" (typeAttrs (typeOf f)))
| _ -> true
in
match s.skind with
Instr il ->
if List.for_all instrFallsThrough il then
addOptionSucc next
else
()
| Return _ -> ()
| Goto (p,_) -> addSucc !p
| ComputedGoto (e,_) -> List.iter addSucc rlabels
| Break _ -> addOptionSucc break
| Continue _ -> addOptionSucc cont
| If (_, blk1, blk2, _) ->
addBlockSucc blk2 next;
addBlockSucc blk1 next;
cfgBlock blk1 next break cont nodeList rlabels;
cfgBlock blk2 next break cont nodeList rlabels
| Block b ->
addBlockSucc b next;
cfgBlock b next break cont nodeList rlabels
| Switch(_,blk,l,_) ->
let bl = findCaseLabeledStmts blk in
if not (List.exists
(fun stmt -> List.exists
(function Default _ -> true | _ -> false)
stmt.labels)
bl)
then
addOptionSucc next;
cfgBlock blk next next cont nodeList rlabels
| Loop(blk, loc, s1, s2) ->
s.skind <- Loop(blk, loc, (Some s), next);
addBlockSucc blk (Some s);
cfgBlock blk (Some s) next (Some s) nodeList rlabels
Since all loops have terminating condition true , we do n't put
any direct successor to stmt following the loop
any direct successor to stmt following the loop *)
| TryExcept _ | TryFinally _ ->
E.s (E.unimp "try/except/finally")
do something for all stmts in a fundec
let rec forallStmts (todo) (fd : fundec) =
begin
fasBlock todo fd.sbody;
end
and fasBlock (todo) (b : block) =
List.iter (fasStmt todo) b.bstmts
and fasStmt (todo) (s : stmt) =
begin
ignore(todo s);
match s.skind with
| Block b -> fasBlock todo b
| If (_, tb, fb, _) -> (fasBlock todo tb; fasBlock todo fb)
| Switch (_, b, _, _) -> fasBlock todo b
| Loop (b, _, _, _) -> fasBlock todo b
| (Return _ | Break _ | Continue _ | Goto _ | ComputedGoto _ | Instr _) -> ()
| TryExcept _ | TryFinally _ -> E.s (E.unimp "try/except/finally")
end
;;
printing the control flow graph - you have to compute it first
let d_cfgnodename () (s : stmt) =
dprintf "%d" s.sid
let d_cfgnodelabel () (s : stmt) =
let label =
begin
match s.skind with
sprint ~width:999 ( " if % a " d_exp e )
| Loop _ -> "loop"
| Break _ -> "break"
| Continue _ -> "continue"
| Goto _ | ComputedGoto _ -> "goto"
| Instr _ -> "instr"
| Switch _ -> "switch"
| Block _ -> "block"
| Return _ -> "return"
| TryExcept _ -> "try-except"
| TryFinally _ -> "try-finally"
end in
dprintf "%d: %s" s.sid label
let d_cfgedge (src) () (dest) =
dprintf "%a -> %a"
d_cfgnodename src
d_cfgnodename dest
let d_cfgnode () (s : stmt) =
dprintf "%a [label=\"%a\"]\n\t%a"
d_cfgnodename s
d_cfgnodelabel s
(d_list "\n\t" (d_cfgedge s)) s.succs
* print control flow graph ( in dot form ) for fundec to channel
let printCfgChannel (chan : out_channel) (fd : fundec) =
let pnode (s:stmt) = fprintf chan "%a\n" d_cfgnode s in
begin
ignore (fprintf chan "digraph CFG_%s {\n" fd.svar.vname);
forallStmts pnode fd;
ignore(fprintf chan "}\n");
end
* Print control flow graph ( in dot form ) for fundec to file
let printCfgFilename (filename : string) (fd : fundec) =
let chan = open_out filename in
begin
printCfgChannel chan fd;
close_out chan;
end
;;
let clearCFGinfo (fd : fundec) =
let clear s =
s.sid <- -1;
s.succs <- [];
s.preds <- [];
in
forallStmts clear fd
let clearFileCFG (f : file) =
start_id := 0;
iterGlobals f (fun g ->
match g with GFun(fd,_) ->
clearCFGinfo fd
| _ -> ())
let computeFileCFG (f : file) =
iterGlobals f (fun g ->
match g with GFun(fd,_) ->
ignore(cfgFun fd)
| _ -> ())
let allStmts (f : file) : stmt list =
foldGlobals f
(fun accu g ->
match g with
| GFun (f,l) -> f.sallstmts @ accu
| _ -> accu
) []
|
746093913e56f659e40d656dcfa59d13fe59731b2de02a9b4188af2ab6f2da73 | finnishtransportagency/harja | pohjavesialueet.clj | (ns harja.palvelin.integraatiot.paikkatietojarjestelma.tuonnit.pohjavesialueet
(:require [taoensso.timbre :as log]
[clojure.java.jdbc :as jdbc]
[harja.kyselyt.pohjavesialueet :as p]
[harja.palvelin.integraatiot.paikkatietojarjestelma.tuonnit.shapefile :as shapefile]
[clojure.string :as str]))
, nimet
rajataan 10 merkkiin .
;; harja-avain | Velho-kenttä | shapefile-kenttä
--------------- |---------------------------------------|---------------------
;; nimi | rakenteelliset_ominaisuudet_nimi | rakenteell
;; tunnus | toiminnalliset_ominaisuudet_tunnus | toiminnall
tr_numero | alkusijainti_tie / loppusijainti_tie | alkusijain
| alkusijainti_osa | alkusijai0
;; tr_alkuetaisyys | alkusijainti_etaisyys | alkusijai1
;; tr_loppuosa | loppusijainti_osa | loppusija0
;; tr_loppuetaisyys | loppusijainti_etaisyys | loppusija1
;; tr_ajorata | <Ei saatavilla | <Ei saatavilla>
;; aineisto-id | internal_id | internal_i
(defn vie-pohjavesialue [db pohjavesialue]
(if (:the_geom pohjavesialue)
(let [nimi (:rakenteell pohjavesialue)
,
geometria (.toString (:the_geom pohjavesialue))
Riippumatta geometria - aineiston pvsuola - arvosta , suolarajoitus voidaan
tr_numero (:alkusijain pohjavesialue)
tr_alkuosa (:alkusijai0 pohjavesialue)
tr_alkuetaisyys (:alkusijai1 pohjavesialue)
tr_loppuosa (:loppusija0 pohjavesialue)
tr_loppuetaisyys (:loppusija1 pohjavesialue)
tr_ajorata nil
aineisto_id (:internal_i pohjavesialue)]
(p/luo-pohjavesialue! db
nimi
tunnus
geometria
suolarajoitus
tr_numero
tr_alkuosa
tr_alkuetaisyys
tr_loppuosa
tr_loppuetaisyys
tr_ajorata
aineisto_id))
(log/warn "Pohjavesialuetta ei voida tuoda ilman geometriaa. Virheviesti: " (:loc_error pohjavesialue))))
(defn vie-pohjavesialueet-kantaan [db shapefile]
(if shapefile
(do
(log/debug (str "Tuodaan pohjavesialueet kantaan tiedostosta " shapefile ". Ei tuoda rivejä, joissa tunnus puuttuu."))
(jdbc/with-db-transaction [db db]
(log/debug "Poistetaan nykyiset pohjavesialueet")
(p/poista-pohjavesialueet! db)
(log/debug "Viedään kantaan uudet alueet")
(doseq [pohjavesialue (filter #(not (= "" (:toiminnall %))) (shapefile/tuo shapefile))]
(vie-pohjavesialue db pohjavesialue)))
(p/paivita-pohjavesialueet db)
(p/paivita-pohjavesialue-kooste db)
(log/debug "Pohjavesialueiden tuonti kantaan valmis."))
(log/debug "Pohjavesialueiden tiedostoa ei löydy konfiguraatiosta. Tuontia ei suoriteta.")))
| null | https://raw.githubusercontent.com/finnishtransportagency/harja/b44024c0c83ae2a4257ba04bccd4c83330d3efd1/src/clj/harja/palvelin/integraatiot/paikkatietojarjestelma/tuonnit/pohjavesialueet.clj | clojure | harja-avain | Velho-kenttä | shapefile-kenttä
nimi | rakenteelliset_ominaisuudet_nimi | rakenteell
tunnus | toiminnalliset_ominaisuudet_tunnus | toiminnall
tr_alkuetaisyys | alkusijainti_etaisyys | alkusijai1
tr_loppuosa | loppusijainti_osa | loppusija0
tr_loppuetaisyys | loppusijainti_etaisyys | loppusija1
tr_ajorata | <Ei saatavilla | <Ei saatavilla>
aineisto-id | internal_id | internal_i | (ns harja.palvelin.integraatiot.paikkatietojarjestelma.tuonnit.pohjavesialueet
(:require [taoensso.timbre :as log]
[clojure.java.jdbc :as jdbc]
[harja.kyselyt.pohjavesialueet :as p]
[harja.palvelin.integraatiot.paikkatietojarjestelma.tuonnit.shapefile :as shapefile]
[clojure.string :as str]))
, nimet
rajataan 10 merkkiin .
--------------- |---------------------------------------|---------------------
tr_numero | alkusijainti_tie / loppusijainti_tie | alkusijain
| alkusijainti_osa | alkusijai0
(defn vie-pohjavesialue [db pohjavesialue]
(if (:the_geom pohjavesialue)
(let [nimi (:rakenteell pohjavesialue)
,
geometria (.toString (:the_geom pohjavesialue))
Riippumatta geometria - aineiston pvsuola - arvosta , suolarajoitus voidaan
tr_numero (:alkusijain pohjavesialue)
tr_alkuosa (:alkusijai0 pohjavesialue)
tr_alkuetaisyys (:alkusijai1 pohjavesialue)
tr_loppuosa (:loppusija0 pohjavesialue)
tr_loppuetaisyys (:loppusija1 pohjavesialue)
tr_ajorata nil
aineisto_id (:internal_i pohjavesialue)]
(p/luo-pohjavesialue! db
nimi
tunnus
geometria
suolarajoitus
tr_numero
tr_alkuosa
tr_alkuetaisyys
tr_loppuosa
tr_loppuetaisyys
tr_ajorata
aineisto_id))
(log/warn "Pohjavesialuetta ei voida tuoda ilman geometriaa. Virheviesti: " (:loc_error pohjavesialue))))
(defn vie-pohjavesialueet-kantaan [db shapefile]
(if shapefile
(do
(log/debug (str "Tuodaan pohjavesialueet kantaan tiedostosta " shapefile ". Ei tuoda rivejä, joissa tunnus puuttuu."))
(jdbc/with-db-transaction [db db]
(log/debug "Poistetaan nykyiset pohjavesialueet")
(p/poista-pohjavesialueet! db)
(log/debug "Viedään kantaan uudet alueet")
(doseq [pohjavesialue (filter #(not (= "" (:toiminnall %))) (shapefile/tuo shapefile))]
(vie-pohjavesialue db pohjavesialue)))
(p/paivita-pohjavesialueet db)
(p/paivita-pohjavesialue-kooste db)
(log/debug "Pohjavesialueiden tuonti kantaan valmis."))
(log/debug "Pohjavesialueiden tiedostoa ei löydy konfiguraatiosta. Tuontia ei suoriteta.")))
|
47a49ddad1c5a7b78717432e1595cfb4984cec6c1ddbd24ed486fe9389cf6ff7 | adaliu-gh/htdp | 393-395.rkt | ;;=====================
393
a Set - of - Number ( Son)is one of :
;; - empty
;; - (cons Number Set-of-Number)
constrains : numbers in should not appear more than once
(define son-1 '(1 4 2 6))
(define son-2 '(43 12 56 4 6))
;; Son Son -> Boolean
check if the first son is in the second
(check-expect (in-set? '(1 2) '( 1 2 4)) #true)
(check-expect (in-set? '( 1 2) '( 1 3 4)) #false)
(define (in-set? sub sup)
(foldl (lambda (x y) (and y (member? x sup))) #true sub))
;; List -> Boolean
;; check if the given list is a set
(check-expect (set? '( 1 2)) #true)
(check-expect (set? '( 1 2 2)) #false)
(define (set? l)
(cond
[(empty? l) #true]
[else (if (member? (first l) (rest l))
#false
(set? (rest l)))]))
;; Son Son -> [Son -> Boolean]
(define (union? s1 s2)
(lambda (s)
(and (in-set? s1 s) (in-set? s2 s) (set? s))))
;; Son Son -> Son
make a union out of two sets
(check-satisfied (union son-1 son-2) (union? son-2 son-1))
(define (union s1 s2)
(cond
[(and (empty? s1) (empty? s2)) '()]
[(empty? s1) s2]
[(empty? s2) s1]
[else (if (member? (first s2) s1)
(union s1 (rest s2))
(cons (first s2) (union s1 (rest s2))))]))
;; Son Son -> [Son -> Boolean]
;; this function is not complete
(define (intersect? s1 s2)
(lambda (s)
(and (in-set? s s1) (in-set? s s2) (set? s))))
;; Son Son -> Son
(check-satisfied (intersect son-2 son-1) (intersect? son-2 son-1))
(define (intersect s1 s2)
(cond
[(or (empty? s1) (empty? s2)) '()]
[else (if (member? (first s1) s2)
(cons (first s1) (intersect (rest s1) s2))
(intersect (rest s1) s2))]))
(check-satisfied (intersect.v2 son-2 son-1) (intersect? son-2 son-1))
(define (intersect.v2 s1 s2)
(foldl (lambda (x y) (if (member? x s2) (cons x y) y)) '() s1))
;;===========================
394
;; [List-of Number] -> Boolean
(check-expect (sort<? '( 1 2 2 3)) #true)
(check-expect (sort<? '( 1 3 2)) #false)
(define (sort<? l)
(cond
[(empty? l) #true]
[(empty? (rest l)) #true]
[else (if (not (> (first l) (first (rest l))))
(sort<? (rest l)) #false)]))
;; [List-of Number] [List-of Number] -> [ [List-of Number] -> Boolean]
;; this function is not complete
(define (merge? l1 l2)
(lambda (l)
(and (in-set? l1 l) (in-set? l2 l) (sort<? l))))
;; Number [List-of Number] -> [List-of Number]
;; inserts a number into a sorted list of numbers
(define (insert n l)
(cond
[(empty? l) (list n)]
[else (if (< n (first l))
(cons n (cons (first l) (rest l)))
(cons (first l) (insert n (rest l))))]))
;; [List-of Number] [List-of Number] -> [List-of Number]
merges two sorted list of numbers into one sorted list of numbers
(check-satisfied (merge '( 1 2 2 3 6 7) '( 2 3 3 4 6 7)) (merge? '( 1 2 2 3 6 7) '( 2 3 3 4 6 7)))
(define (merge l1 l2)
(cond
[(and (empty? l1) (empty? l2)) '()]
[(empty? l2) l1]
[(empty? l1) l2]
[else (merge (rest l1) (insert (first l1) l2))]))
;;============================
395
;; [List-of Number] Number -> [List-of Number]
extracts the first n numbers from the list or the whole list if the list is too short
(check-expect (take '() 2) '())
(check-expect (take '( 1 2 3) 1) '(1))
(check-expect (take '( 1 2 3) 2) '( 1 2))
(check-expect (take '( 1 2 3) 34) '( 1 2 3))
(define (take l n)
(cond
[(empty? l) l]
[(= n 0) '()]
[else (cons (first l) (take (rest l) (sub1 n)))]))
;; [List-of Number] Number -> [List-of Number]
removes the first n numbers from the list or all of them if the list is too short
(check-expect (drop '() 34) '())
(check-expect (drop '( 1 2) 34) '())
(check-expect (drop '( 1 2) 0) '(1 2))
(check-expect (drop '( 1 2 3) 2) '( 3))
(define (drop l n)
(cond
[(empty? l) '()]
[(= n 0) l]
[else (drop (rest l) (sub1 n))]))
| null | https://raw.githubusercontent.com/adaliu-gh/htdp/a0fca8af2ae8bdcef40d56f6f45021dd92df2995/19-24%20Intertwined%20Data/393-395.rkt | racket | =====================
- empty
- (cons Number Set-of-Number)
Son Son -> Boolean
List -> Boolean
check if the given list is a set
Son Son -> [Son -> Boolean]
Son Son -> Son
Son Son -> [Son -> Boolean]
this function is not complete
Son Son -> Son
===========================
[List-of Number] -> Boolean
[List-of Number] [List-of Number] -> [ [List-of Number] -> Boolean]
this function is not complete
Number [List-of Number] -> [List-of Number]
inserts a number into a sorted list of numbers
[List-of Number] [List-of Number] -> [List-of Number]
============================
[List-of Number] Number -> [List-of Number]
[List-of Number] Number -> [List-of Number] | 393
a Set - of - Number ( Son)is one of :
constrains : numbers in should not appear more than once
(define son-1 '(1 4 2 6))
(define son-2 '(43 12 56 4 6))
check if the first son is in the second
(check-expect (in-set? '(1 2) '( 1 2 4)) #true)
(check-expect (in-set? '( 1 2) '( 1 3 4)) #false)
(define (in-set? sub sup)
(foldl (lambda (x y) (and y (member? x sup))) #true sub))
(check-expect (set? '( 1 2)) #true)
(check-expect (set? '( 1 2 2)) #false)
(define (set? l)
(cond
[(empty? l) #true]
[else (if (member? (first l) (rest l))
#false
(set? (rest l)))]))
(define (union? s1 s2)
(lambda (s)
(and (in-set? s1 s) (in-set? s2 s) (set? s))))
make a union out of two sets
(check-satisfied (union son-1 son-2) (union? son-2 son-1))
(define (union s1 s2)
(cond
[(and (empty? s1) (empty? s2)) '()]
[(empty? s1) s2]
[(empty? s2) s1]
[else (if (member? (first s2) s1)
(union s1 (rest s2))
(cons (first s2) (union s1 (rest s2))))]))
(define (intersect? s1 s2)
(lambda (s)
(and (in-set? s s1) (in-set? s s2) (set? s))))
(check-satisfied (intersect son-2 son-1) (intersect? son-2 son-1))
(define (intersect s1 s2)
(cond
[(or (empty? s1) (empty? s2)) '()]
[else (if (member? (first s1) s2)
(cons (first s1) (intersect (rest s1) s2))
(intersect (rest s1) s2))]))
(check-satisfied (intersect.v2 son-2 son-1) (intersect? son-2 son-1))
(define (intersect.v2 s1 s2)
(foldl (lambda (x y) (if (member? x s2) (cons x y) y)) '() s1))
394
(check-expect (sort<? '( 1 2 2 3)) #true)
(check-expect (sort<? '( 1 3 2)) #false)
(define (sort<? l)
(cond
[(empty? l) #true]
[(empty? (rest l)) #true]
[else (if (not (> (first l) (first (rest l))))
(sort<? (rest l)) #false)]))
(define (merge? l1 l2)
(lambda (l)
(and (in-set? l1 l) (in-set? l2 l) (sort<? l))))
(define (insert n l)
(cond
[(empty? l) (list n)]
[else (if (< n (first l))
(cons n (cons (first l) (rest l)))
(cons (first l) (insert n (rest l))))]))
merges two sorted list of numbers into one sorted list of numbers
(check-satisfied (merge '( 1 2 2 3 6 7) '( 2 3 3 4 6 7)) (merge? '( 1 2 2 3 6 7) '( 2 3 3 4 6 7)))
(define (merge l1 l2)
(cond
[(and (empty? l1) (empty? l2)) '()]
[(empty? l2) l1]
[(empty? l1) l2]
[else (merge (rest l1) (insert (first l1) l2))]))
395
extracts the first n numbers from the list or the whole list if the list is too short
(check-expect (take '() 2) '())
(check-expect (take '( 1 2 3) 1) '(1))
(check-expect (take '( 1 2 3) 2) '( 1 2))
(check-expect (take '( 1 2 3) 34) '( 1 2 3))
(define (take l n)
(cond
[(empty? l) l]
[(= n 0) '()]
[else (cons (first l) (take (rest l) (sub1 n)))]))
removes the first n numbers from the list or all of them if the list is too short
(check-expect (drop '() 34) '())
(check-expect (drop '( 1 2) 34) '())
(check-expect (drop '( 1 2) 0) '(1 2))
(check-expect (drop '( 1 2 3) 2) '( 3))
(define (drop l n)
(cond
[(empty? l) '()]
[(= n 0) l]
[else (drop (rest l) (sub1 n))]))
|
59a893680120ab36b89749137f9b900f8c4d427c4b9a2a6a5a87a5098b68fda6 | mtpearce/idyom | generics.lisp | ;;;; ======================================================================
;;;; File: generics.lisp
Author : < >
Created : < 2004 - 10 - 28 11:56:59 >
Time - stamp : < 2014 - 06 - 04 16:04:23 marcusp >
;;;; ======================================================================
(cl:in-package #:prediction-sets)
(defgeneric average-codelengths (prediction))
(defgeneric average-codelength (prediction))
(defgeneric codelengths (prediction))
(defgeneric shannon-entropies (prediction))
(defgeneric event-prediction (event-prediction))
(defgeneric event-predictions (prediction))
(defgeneric sequence-probability (sequence-prediction))
(cl:in-package #:multiple-viewpoint-system)
(defgeneric count-viewpoints (mvs))
(defgeneric get-event-array (mvs sequence))
(defgeneric operate-on-models (mvs operation &key models ltm-args stm-args))
(defgeneric set-model-alphabets (mvs event events viewpoint ltm stm
unconstrained))
(defgeneric get-basic-viewpoint (mvs derived-viewpoint))
(defgeneric sequence-prediction-sets (mvs events event-prediction-sets))
(defgeneric dataset-prediction-sets (mvs sequence-prediction-sets))
(defgeneric set-mvs-parameters (mvs &key ltm-order-bound ltm-mixtures
ltm-update-exclusion ltm-escape stm-order-bound
stm-mixtures stm-update-exclusion stm-escape))
(defgeneric model-event (model event events &key construct? predict?
&allow-other-keys))
| null | https://raw.githubusercontent.com/mtpearce/idyom/d0449a978c79f8ded74c509fdfad7c1a253c5a80/mvs/generics.lisp | lisp | ======================================================================
File: generics.lisp
====================================================================== | Author : < >
Created : < 2004 - 10 - 28 11:56:59 >
Time - stamp : < 2014 - 06 - 04 16:04:23 marcusp >
(cl:in-package #:prediction-sets)
(defgeneric average-codelengths (prediction))
(defgeneric average-codelength (prediction))
(defgeneric codelengths (prediction))
(defgeneric shannon-entropies (prediction))
(defgeneric event-prediction (event-prediction))
(defgeneric event-predictions (prediction))
(defgeneric sequence-probability (sequence-prediction))
(cl:in-package #:multiple-viewpoint-system)
(defgeneric count-viewpoints (mvs))
(defgeneric get-event-array (mvs sequence))
(defgeneric operate-on-models (mvs operation &key models ltm-args stm-args))
(defgeneric set-model-alphabets (mvs event events viewpoint ltm stm
unconstrained))
(defgeneric get-basic-viewpoint (mvs derived-viewpoint))
(defgeneric sequence-prediction-sets (mvs events event-prediction-sets))
(defgeneric dataset-prediction-sets (mvs sequence-prediction-sets))
(defgeneric set-mvs-parameters (mvs &key ltm-order-bound ltm-mixtures
ltm-update-exclusion ltm-escape stm-order-bound
stm-mixtures stm-update-exclusion stm-escape))
(defgeneric model-event (model event events &key construct? predict?
&allow-other-keys))
|
02f1ecedab5cdb2258bd83b6d459ba9bb7abac9ddb3252894c6874a3593bbd92 | quil-lang/magicl | householder.lisp | ;;;; householder.lisp
;;;;
Author :
(in-package #:magicl)
;;;; This file doesn't actually implement any MAGICL functions. These
;;;; functions are utilities for implementing QR decomposition.
(defstruct householder-reflection
"Representation of a Householder reflection."
v (idx 0))
(defun column->householder (A i0 j0)
"Construct a Householder reflection which, when applied from the left, puts zeros in column J0 below row I0."
(let* ((m (nrows A))
(v (zeros (list (- m i0)) :type (element-type A))))
(loop :for i :from i0 :below m
:for iv :from 0
:do (setf (tref v iv) (tref A i j0)))
(let ((norm-v (norm v)))
(if (zerop norm-v)
(make-householder-reflection)
(let ((v0 (tref v 0)))
(incf (tref v 0) ; TODO: revisit this
(* norm-v (/ v0 (abs v0))))
(scale! v (/ (norm v)))
(make-householder-reflection :v v :idx j0))))))
(defun row->householder (A i0 j0)
"Construct a Householder reflection which, when applied from the right, puts zeros in row I0 to the right of column J0."
(let* ((n (ncols A))
(v (zeros (list (- n j0)) :type (element-type A))))
(loop :for j :from j0 :below n
:for jv :from 0
:do (setf (tref v jv) (conjugate (tref A i0 j))))
(let ((norm-v (norm v)))
(if (zerop norm-v)
(make-householder-reflection)
(let ((v0 (tref v 0)))
(incf (tref v 0)
(* norm-v (/ v0 (abs v0))))
(scale! v (/ (norm v)))
(make-householder-reflection :v v :idx i0))))))
(defun left-apply-householder! (A hh)
"Apply the Householder reflection HH to A[i:,j:], from the left."
(when (null (householder-reflection-v hh))
(return-from left-apply-householder! A))
(let* ((m (nrows A))
(n (ncols A))
(v (householder-reflection-v hh))
(i0 (- m (size v))))
(flet ((column-reflect! (j)
"Reflect A[i0:m,j]."
(let ((v-dot-A
(loop :for i :from i0 :below m
:for iv :from 0
:sum (* (conjugate (tref v iv)) (tref A i j)))))
(loop :for i :from i0 :below m
:for iv :from 0
:do (decf (tref A i j)
(* 2 (tref v iv) v-dot-A))))))
(loop :for j :from (householder-reflection-idx hh) :below n
:do (column-reflect! j))))
A)
(defun right-apply-householder! (A hh)
"Apply the Householder reflection HH to A[i:,j:] from the right."
(declare (optimize debug))
(when (null (householder-reflection-v hh))
(return-from right-apply-householder! A))
(let* ((m (nrows A))
(n (ncols A))
(v (householder-reflection-v hh))
(j0 (- n (size v))))
(flet ((row-reflect! (i)
"Reflect A[i,j0:m] across (dagger V)."
(let ((v*-dot-a
(loop :for j :from j0 :below n
:for iv :from 0
:sum (* (tref A i j) (tref v iv)))))
(loop :for j :from j0 :below n
:for iv :from 0
:do (decf (tref A i j)
(* 2 v*-dot-a (conjugate (tref v iv))))))))
(loop :for i :from (householder-reflection-idx hh) :below m
:do (row-reflect! i)))))
| null | https://raw.githubusercontent.com/quil-lang/magicl/c7730fba6614652ae291053566a9c2b6696ad737/src/high-level/matrix-functions/householder.lisp | lisp | householder.lisp
This file doesn't actually implement any MAGICL functions. These
functions are utilities for implementing QR decomposition.
TODO: revisit this | Author :
(in-package #:magicl)
(defstruct householder-reflection
"Representation of a Householder reflection."
v (idx 0))
(defun column->householder (A i0 j0)
"Construct a Householder reflection which, when applied from the left, puts zeros in column J0 below row I0."
(let* ((m (nrows A))
(v (zeros (list (- m i0)) :type (element-type A))))
(loop :for i :from i0 :below m
:for iv :from 0
:do (setf (tref v iv) (tref A i j0)))
(let ((norm-v (norm v)))
(if (zerop norm-v)
(make-householder-reflection)
(let ((v0 (tref v 0)))
(* norm-v (/ v0 (abs v0))))
(scale! v (/ (norm v)))
(make-householder-reflection :v v :idx j0))))))
(defun row->householder (A i0 j0)
"Construct a Householder reflection which, when applied from the right, puts zeros in row I0 to the right of column J0."
(let* ((n (ncols A))
(v (zeros (list (- n j0)) :type (element-type A))))
(loop :for j :from j0 :below n
:for jv :from 0
:do (setf (tref v jv) (conjugate (tref A i0 j))))
(let ((norm-v (norm v)))
(if (zerop norm-v)
(make-householder-reflection)
(let ((v0 (tref v 0)))
(incf (tref v 0)
(* norm-v (/ v0 (abs v0))))
(scale! v (/ (norm v)))
(make-householder-reflection :v v :idx i0))))))
(defun left-apply-householder! (A hh)
"Apply the Householder reflection HH to A[i:,j:], from the left."
(when (null (householder-reflection-v hh))
(return-from left-apply-householder! A))
(let* ((m (nrows A))
(n (ncols A))
(v (householder-reflection-v hh))
(i0 (- m (size v))))
(flet ((column-reflect! (j)
"Reflect A[i0:m,j]."
(let ((v-dot-A
(loop :for i :from i0 :below m
:for iv :from 0
:sum (* (conjugate (tref v iv)) (tref A i j)))))
(loop :for i :from i0 :below m
:for iv :from 0
:do (decf (tref A i j)
(* 2 (tref v iv) v-dot-A))))))
(loop :for j :from (householder-reflection-idx hh) :below n
:do (column-reflect! j))))
A)
(defun right-apply-householder! (A hh)
"Apply the Householder reflection HH to A[i:,j:] from the right."
(declare (optimize debug))
(when (null (householder-reflection-v hh))
(return-from right-apply-householder! A))
(let* ((m (nrows A))
(n (ncols A))
(v (householder-reflection-v hh))
(j0 (- n (size v))))
(flet ((row-reflect! (i)
"Reflect A[i,j0:m] across (dagger V)."
(let ((v*-dot-a
(loop :for j :from j0 :below n
:for iv :from 0
:sum (* (tref A i j) (tref v iv)))))
(loop :for j :from j0 :below n
:for iv :from 0
:do (decf (tref A i j)
(* 2 v*-dot-a (conjugate (tref v iv))))))))
(loop :for i :from (householder-reflection-idx hh) :below m
:do (row-reflect! i)))))
|
d9e138a0ac9c2b0cbdad221c5a8f0c2ea3c9bae7726853e33f1d58f8dde57e93 | david-christiansen/pudding-old | stlc-refiner.rkt | #lang racket
(require
;; Make definitions with the refiner
"../refiner-define.rkt"
;; The theory and tactics we care about
(for-syntax "../theories/stlc.rkt" "../tactics.rkt" "../proofs.rkt"
"../proof-state.rkt"
zippers
racket/list))
(module+ test
(require rackunit))
(define/refiner two #'Int
(refine (length-of-string))
(move (down/proof))
(refine (string-intro #'"ab"))
solve
(move up)
solve)
;; A linear tactic script, dispatching subgoals as they arise
(define/refiner add-two #'(--> Int Int)
(refine (function-intro 'n))
(move (down/proof))
;; Make sure that "try" works
(try (refine (function-intro 'fnord)))
(refine (addition 3))
(move (down/proof))
(refine (int-intro #'1))
solve
(move right/proof)
(refine (assumption 0))
solve
(move right/proof)
(refine (int-intro #'1))
solve
(move up)
solve
(move up)
solve)
(define-for-syntax (by tac)
(proof tac solve))
;; A tree-shaped tactic script, corresponding more closely to the goal
;; structure
(define/refiner add-2 #'(--> Int Int)
(with-subgoals (refine (function-intro 'n))
(by
(with-subgoals (refine (addition 3))
(by (refine (int-intro #'1)))
(proof
skip ;; start by doing nothing, just for the heck of it
(refine (assumption 0))
solve)
(proof (refine (int-intro #'1))
solve))))
solve)
(define/refiner strlen #'(--> String Int)
(proof
(refine (function-intro 'str))
(move (down/proof))
(refine (length-of-string))
(move (down/proof))
(refine (assumption 0))
solve
(move up)
solve
(move up)
solve))
(define/refiner twice-string-length #'(--> String Int)
(with-subgoals (refine (function-intro 'str))
(by (with-subgoals (refine (addition 2))
(proof (refine (length-of-string))
(move (down/proof))
(by (refine (assumption 0)))
(move up)
solve)
(proof (refine (length-of-string))
(move (down/proof))
(by (refine (assumption 0)))
(move up)
solve))))
solve)
(module+ test
(check-equal? (add-two 4)
6)
(check-equal? (add-2 17)
19)
(check-equal? (strlen "halløjsa!") 9))
| null | https://raw.githubusercontent.com/david-christiansen/pudding-old/6b9ee633b551226df61d40191bafa14386fc86ad/demo/stlc-refiner.rkt | racket | Make definitions with the refiner
The theory and tactics we care about
A linear tactic script, dispatching subgoals as they arise
Make sure that "try" works
A tree-shaped tactic script, corresponding more closely to the goal
structure
start by doing nothing, just for the heck of it | #lang racket
(require
"../refiner-define.rkt"
(for-syntax "../theories/stlc.rkt" "../tactics.rkt" "../proofs.rkt"
"../proof-state.rkt"
zippers
racket/list))
(module+ test
(require rackunit))
(define/refiner two #'Int
(refine (length-of-string))
(move (down/proof))
(refine (string-intro #'"ab"))
solve
(move up)
solve)
(define/refiner add-two #'(--> Int Int)
(refine (function-intro 'n))
(move (down/proof))
(try (refine (function-intro 'fnord)))
(refine (addition 3))
(move (down/proof))
(refine (int-intro #'1))
solve
(move right/proof)
(refine (assumption 0))
solve
(move right/proof)
(refine (int-intro #'1))
solve
(move up)
solve
(move up)
solve)
(define-for-syntax (by tac)
(proof tac solve))
(define/refiner add-2 #'(--> Int Int)
(with-subgoals (refine (function-intro 'n))
(by
(with-subgoals (refine (addition 3))
(by (refine (int-intro #'1)))
(proof
(refine (assumption 0))
solve)
(proof (refine (int-intro #'1))
solve))))
solve)
(define/refiner strlen #'(--> String Int)
(proof
(refine (function-intro 'str))
(move (down/proof))
(refine (length-of-string))
(move (down/proof))
(refine (assumption 0))
solve
(move up)
solve
(move up)
solve))
(define/refiner twice-string-length #'(--> String Int)
(with-subgoals (refine (function-intro 'str))
(by (with-subgoals (refine (addition 2))
(proof (refine (length-of-string))
(move (down/proof))
(by (refine (assumption 0)))
(move up)
solve)
(proof (refine (length-of-string))
(move (down/proof))
(by (refine (assumption 0)))
(move up)
solve))))
solve)
(module+ test
(check-equal? (add-two 4)
6)
(check-equal? (add-2 17)
19)
(check-equal? (strlen "halløjsa!") 9))
|
f26eb811f2c4dfe95bc3a861f2ad05606f80fe25065c09218de64ff73543074d | Dale-M/mcron | utils.scm | ;;;; utils.scm -- helper procedures
Copyright © 2003 , 2012 < >
Copyright © 2015 , 2016 , 2018 < >
;;;
This file is part of GNU Mcron .
;;;
GNU Mcron is free software : you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
;;; (at your option) any later version.
;;;
GNU Mcron is distributed in the hope that it will be useful ,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
You should have received a copy of the GNU General Public License
along with GNU Mcron . If not , see < / > .
(define-module (mcron utils)
#:use-module (ice-9 rdelim)
#:use-module (mcron config)
#:use-module (mcron base)
#:use-module (mcron job-specifier)
#:use-module (mcron vixie-specification)
#:export (catch-mcron-error
mcron-error
show-version
show-package-information
process-update-request
get-user)
#:re-export (read-string))
(define (mcron-error exit-code . rest)
"Print an error message (made up from the parts of REST), and if the
EXIT-CODE error is fatal (present and non-zero) then exit to the system with
EXIT-CODE."
(with-output-to-port (current-error-port)
(lambda ()
(for-each display (cons "mcron: " rest))
(newline)))
(when (and exit-code (not (eq? exit-code 0)))
(primitive-exit exit-code)))
(define-syntax-rule (catch-mcron-error exp ...)
"Evaluate EXP .... if an 'mcron-error exception occurs, print its diagnostics
and exit with its error code."
(catch 'mcron-error
(lambda () exp ...)
(lambda (key exit-code . msg)
(apply mcron-error exit-code msg))))
(define (show-version command)
"Display version information for COMMAND and quit."
(let* ((name config-package-name)
(short-name (cadr (string-split name #\space)))
(version config-package-version))
(simple-format #t "~a (~a) ~a
Copyright (C) 2020 the ~a authors.
License GPLv3+: GNU GPL version 3 or later <>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.\n"
command name version short-name)))
(define (show-package-information)
"Display where to get help and send bug reports."
(simple-format #t "\nReport bugs to: ~a.
~a home page: <~a>
General help using GNU software: </>\n"
config-package-bugreport
config-package-name
config-package-url))
(define (process-update-request fdes-list)
"Read a user name from the socket, dealing with the /etc/crontab special
case, remove all the user's jobs from the job list, and then re-read the
user's updated file. In the special case drop all the system jobs and re-read
the /etc/crontab file. This function should be called whenever a message
comes in on the above socket."
(let* ((sock (car (accept (car fdes-list))))
(user-name (read-line sock)))
(close sock)
(set-configuration-time (current-time))
(catch-mcron-error
(if (string=? user-name "/etc/crontab")
(begin
(clear-system-jobs)
(use-system-job-list)
(read-vixie-file "/etc/crontab" parse-system-vixie-line)
(use-user-job-list))
(let ((user (getpw user-name)))
(remove-user-jobs user)
(set-configuration-user user)
(read-vixie-file (string-append config-spool-dir "/" user-name)))))))
(define (get-user spec)
"Return the passwd entry corresponding to SPEC. If SPEC is passwd entry
then return it. If SPEC is not a valid specification throw an exception."
(cond ((or (string? spec) (integer? spec))
(getpw spec))
((vector? spec) ;assume a user passwd entry
spec)
(else
(throw 'invalid-user-specification spec))))
| null | https://raw.githubusercontent.com/Dale-M/mcron/56308568da1c846698a4b2ad593a164133ab19cf/src/mcron/utils.scm | scheme | utils.scm -- helper procedures
(at your option) any later version.
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.
assume a user passwd entry | Copyright © 2003 , 2012 < >
Copyright © 2015 , 2016 , 2018 < >
This file is part of GNU Mcron .
GNU Mcron 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
GNU Mcron is distributed in the hope that it will be useful ,
You should have received a copy of the GNU General Public License
along with GNU Mcron . If not , see < / > .
(define-module (mcron utils)
#:use-module (ice-9 rdelim)
#:use-module (mcron config)
#:use-module (mcron base)
#:use-module (mcron job-specifier)
#:use-module (mcron vixie-specification)
#:export (catch-mcron-error
mcron-error
show-version
show-package-information
process-update-request
get-user)
#:re-export (read-string))
(define (mcron-error exit-code . rest)
"Print an error message (made up from the parts of REST), and if the
EXIT-CODE error is fatal (present and non-zero) then exit to the system with
EXIT-CODE."
(with-output-to-port (current-error-port)
(lambda ()
(for-each display (cons "mcron: " rest))
(newline)))
(when (and exit-code (not (eq? exit-code 0)))
(primitive-exit exit-code)))
(define-syntax-rule (catch-mcron-error exp ...)
"Evaluate EXP .... if an 'mcron-error exception occurs, print its diagnostics
and exit with its error code."
(catch 'mcron-error
(lambda () exp ...)
(lambda (key exit-code . msg)
(apply mcron-error exit-code msg))))
(define (show-version command)
"Display version information for COMMAND and quit."
(let* ((name config-package-name)
(short-name (cadr (string-split name #\space)))
(version config-package-version))
(simple-format #t "~a (~a) ~a
Copyright (C) 2020 the ~a authors.
License GPLv3+: GNU GPL version 3 or later <>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.\n"
command name version short-name)))
(define (show-package-information)
"Display where to get help and send bug reports."
(simple-format #t "\nReport bugs to: ~a.
~a home page: <~a>
General help using GNU software: </>\n"
config-package-bugreport
config-package-name
config-package-url))
(define (process-update-request fdes-list)
"Read a user name from the socket, dealing with the /etc/crontab special
case, remove all the user's jobs from the job list, and then re-read the
user's updated file. In the special case drop all the system jobs and re-read
the /etc/crontab file. This function should be called whenever a message
comes in on the above socket."
(let* ((sock (car (accept (car fdes-list))))
(user-name (read-line sock)))
(close sock)
(set-configuration-time (current-time))
(catch-mcron-error
(if (string=? user-name "/etc/crontab")
(begin
(clear-system-jobs)
(use-system-job-list)
(read-vixie-file "/etc/crontab" parse-system-vixie-line)
(use-user-job-list))
(let ((user (getpw user-name)))
(remove-user-jobs user)
(set-configuration-user user)
(read-vixie-file (string-append config-spool-dir "/" user-name)))))))
(define (get-user spec)
"Return the passwd entry corresponding to SPEC. If SPEC is passwd entry
then return it. If SPEC is not a valid specification throw an exception."
(cond ((or (string? spec) (integer? spec))
(getpw spec))
spec)
(else
(throw 'invalid-user-specification spec))))
|
f7905fd8bd165f7b06cb89e5e54a1cbe6b3134fa6879608a3aa6fe54c14675db | tonsky/down-the-rabbit-hole | phases.clj | (ns down-the-rabbit-hole.phases
(:require
[datascript.core :as ds]
[down-the-rabbit-hole.core :as core]
[down-the-rabbit-hole.alice :as alice]
[down-the-rabbit-hole.decorations :as decorations]
[down-the-rabbit-hole.end-turn :as end-turn]
[down-the-rabbit-hole.item :as item]
[down-the-rabbit-hole.rabbit :as rabbit])
(:import
[org.jetbrains.skija Canvas Point Rect]))
(defmulti tick
(fn [db game]
(:game/phase game)))
(defmethod tick :default [db game]
#_(try
(println "default" (:game/phase game) (core/lerp-phase game 0 1))
(catch Exception e))
[])
(defmethod tick :phase/start [_ _]
(let [now (System/currentTimeMillis)]
(concat
[{:db/id 1
:game/nano (System/nanoTime)
:game/now now
:game/phase :phase/player-enter
:game/phase-started now
:game/phase-length 200}]
(decorations/decorations-tx)
(alice/alice-tx))))
(defmethod tick :phase/player-enter [db game]
(if (>= (core/lerp-phase game 0 1) 1)
(concat
[{:db/id 1
:game/phase :phase/enemy-enter
:game/phase-started (:game/now game)
:game/phase-length 400}]
(rabbit/rabbit-tx))
[]))
(defmethod tick :phase/enemy-enter [db game]
(if (>= (core/lerp-phase game 0 1) 1)
[{:db/id 1
:game/phase :phase/players-separate
:game/phase-started (:game/now game)
:game/phase-length 200}]
[]))
(defn items-enter-tx [db game]
(let [player (first (core/entities db :avet :role :role/player))
player-items (mapcat #(item/item-tx % 6 player) (range 0 6))
enemy (first (core/entities db :avet :role :role/enemy))
enemy-items (mapcat #(item/item-tx % 3 enemy) (range 0 3))]
(concat
[{:db/id 1
:game/phase :phase/items-enter
:game/phase-started (:game/now game)
:game/phase-length 500}]
player-items
enemy-items)))
(defmethod tick :phase/players-separate [db game]
(if (>= (core/lerp-phase game 0 1) 1)
(items-enter-tx db game)
[]))
(defmethod tick :phase/items-enter [db game]
(if (>= (core/lerp-phase game 0 1) 1)
(concat
[{:db/id 1
:game/phase :phase/player-turn
:game/phase-started (:game/now game)
:game/phase-length Long/MAX_VALUE}]
(end-turn/end-turn-tx))
[]))
(defmethod tick :phase/player-items-leave [db game]
(if (>= (core/lerp-phase game 0 1) 1)
(concat
[{:db/id 1
:game/phase :phase/enemy-items-leave
:game/phase-started (:game/now game)
:game/phase-length 500}]
(->> (core/entities db :avet :role :role/item)
(filter #(= :role/player (:role (:item/owner %))))
(map (fn [e] [:db/retractEntity (:db/id e)]))))
[]))
(defmethod tick :phase/enemy-items-leave [db game]
(if (>= (core/lerp-phase game 0 1) 1)
(concat
(->> (core/entities db :avet :role :role/item)
(filter #(= :role/enemy (:role (:item/owner %))))
(map (fn [e] [:db/retractEntity (:db/id e)])))
(items-enter-tx db game))
[]))
| null | https://raw.githubusercontent.com/tonsky/down-the-rabbit-hole/cca89725c14f3a316f6a8bf44fe3a1ee2b04617c/src/down_the_rabbit_hole/phases.clj | clojure | (ns down-the-rabbit-hole.phases
(:require
[datascript.core :as ds]
[down-the-rabbit-hole.core :as core]
[down-the-rabbit-hole.alice :as alice]
[down-the-rabbit-hole.decorations :as decorations]
[down-the-rabbit-hole.end-turn :as end-turn]
[down-the-rabbit-hole.item :as item]
[down-the-rabbit-hole.rabbit :as rabbit])
(:import
[org.jetbrains.skija Canvas Point Rect]))
(defmulti tick
(fn [db game]
(:game/phase game)))
(defmethod tick :default [db game]
#_(try
(println "default" (:game/phase game) (core/lerp-phase game 0 1))
(catch Exception e))
[])
(defmethod tick :phase/start [_ _]
(let [now (System/currentTimeMillis)]
(concat
[{:db/id 1
:game/nano (System/nanoTime)
:game/now now
:game/phase :phase/player-enter
:game/phase-started now
:game/phase-length 200}]
(decorations/decorations-tx)
(alice/alice-tx))))
(defmethod tick :phase/player-enter [db game]
(if (>= (core/lerp-phase game 0 1) 1)
(concat
[{:db/id 1
:game/phase :phase/enemy-enter
:game/phase-started (:game/now game)
:game/phase-length 400}]
(rabbit/rabbit-tx))
[]))
(defmethod tick :phase/enemy-enter [db game]
(if (>= (core/lerp-phase game 0 1) 1)
[{:db/id 1
:game/phase :phase/players-separate
:game/phase-started (:game/now game)
:game/phase-length 200}]
[]))
(defn items-enter-tx [db game]
(let [player (first (core/entities db :avet :role :role/player))
player-items (mapcat #(item/item-tx % 6 player) (range 0 6))
enemy (first (core/entities db :avet :role :role/enemy))
enemy-items (mapcat #(item/item-tx % 3 enemy) (range 0 3))]
(concat
[{:db/id 1
:game/phase :phase/items-enter
:game/phase-started (:game/now game)
:game/phase-length 500}]
player-items
enemy-items)))
(defmethod tick :phase/players-separate [db game]
(if (>= (core/lerp-phase game 0 1) 1)
(items-enter-tx db game)
[]))
(defmethod tick :phase/items-enter [db game]
(if (>= (core/lerp-phase game 0 1) 1)
(concat
[{:db/id 1
:game/phase :phase/player-turn
:game/phase-started (:game/now game)
:game/phase-length Long/MAX_VALUE}]
(end-turn/end-turn-tx))
[]))
(defmethod tick :phase/player-items-leave [db game]
(if (>= (core/lerp-phase game 0 1) 1)
(concat
[{:db/id 1
:game/phase :phase/enemy-items-leave
:game/phase-started (:game/now game)
:game/phase-length 500}]
(->> (core/entities db :avet :role :role/item)
(filter #(= :role/player (:role (:item/owner %))))
(map (fn [e] [:db/retractEntity (:db/id e)]))))
[]))
(defmethod tick :phase/enemy-items-leave [db game]
(if (>= (core/lerp-phase game 0 1) 1)
(concat
(->> (core/entities db :avet :role :role/item)
(filter #(= :role/enemy (:role (:item/owner %))))
(map (fn [e] [:db/retractEntity (:db/id e)])))
(items-enter-tx db game))
[]))
| |
216ef81e397444fee623873139664b4137aad557a26fa2664dd34ad3d89a4c54 | msp-strath/ask | Proving.hs | ------------------------------------------------------------------------------
---------- ----------
-------- Ask . . Proving ----------
---------- ----------
------------------------------------------------------------------------------
# LANGUAGE
LambdaCase
#
LambdaCase
#-}
module Ask.Src.Proving where
import Data.Foldable
import Data.Traversable
import Ask.Src.Thin
import Ask.Src.Hide
import Ask.Src.Bwd
import Ask.Src.Lexing
import Ask.Src.RawAsk
import Ask.Src.Tm
import Ask.Src.Glueing
import Ask.Src.Context
import Ask.Src.Typing
import Debug.Trace
trice = const id
by :: Tm -> Appl -> AM TmR
by goal a@(_, (t, _, r) :$$ ss) | elem t [Uid, Sym] = do
subses <- fold <$> (gamma >>= traverse backchain)
case subses of
[(tel, subs)] -> do
(t, m) <- elabVec EXP r tel ss
mapM_ fred (stan m subs)
return $ Our t a
[] -> gripe $ ByBadRule r goal
_ -> gripe $ ByAmbiguous r goal
where
backchain :: CxE -> AM [(Tel, [Subgoal])] -- list of successes
backchain (ByRule _ ((gop, (h, tel)) :<= prems))
| h == r =
cope (do
m <- maAM (gop, goal)
return [(stan m tel, stan m prems)])
(\ _ -> return [])
return
backchain _ = return []
by goal r = gripe $ NotARule r
invert :: Tm -> AM [([CxE], [Subgoal])]
invert hyp = fold <$> (gamma >>= traverse try )
where
try :: CxE -> AM [([CxE], [Subgoal])]
try (ByRule True ((gop, (h, tel)) :<= prems)) = do
doorStop
m <- prayTel [] tel
True <- trice ("INVERT TRIES: " ++ show ((hyp, gop), (h, tel), prems)) $ return True
gingerly m Prop gop hyp >>= \case
[(_, m)] -> do
let prems' = stan m prems
de <- doorStep
True <- trice ("INVERT: " ++ show m ++ " ===> " ++
show (de, prems')) $ return True
return [(de, prems')]
_ -> doorStep *> return []
try _ = return []
prayTel :: Matching -> Tel -> AM Matching
prayTel m (Pr hs) = do
for (stan m hs) $ \ h -> push $ Hyp True h
return m
prayTel m (Ex s b) = do
xn <- fresh "x"
BOO !
let xp = (xn, Hide (stan m s))
push $ Bind xp (User u)
prayTel m (b // TP xp)
prayTel m ((x, s) :*: t) = do
xn <- fresh x
BOO !
let xp = (xn, Hide (stan m s))
push $ Bind xp (User u)
prayTel ((x, TE (TP xp)) : m) t
prayPat :: Matching -> Tm -> Pat -> AM (Syn, Matching)
prayPat m ty (PC c ps) = do
ty <- hnf $ stan m ty
tel <- constructor PAT ty c
(ts, m) <- prayPats m tel ps
return (TC c ts ::: ty, m)
prayPat m ty (PM x _) = do
xn <- fresh x
BOO !
let xp = (xn, Hide (stan m ty))
push $ Bind xp (User u)
return (TP xp, (x, TE (TP xp)) : m)
prayPats :: Matching -> Tel -> [Pat] -> AM ([Tm], Matching)
prayPats m (Pr hs) [] = do
for (stan m hs) $ \ h -> push $ Hyp True h
return ([], m)
prayPats m (Ex s b) (p : ps) = do
(e, m) <- prayPat m s p
(ts, m) <- prayPats m (b // e) ps
return (upTE e : ts, m)
prayPats m ((x, s) :*: tel) (p : ps) = do
(e, m) <- prayPat m s p
(ts, m) <- prayPats ((x, upTE e) : m) tel ps
return (upTE e : ts, m)
prayPats _ _ _ = gripe Mardiness
gingerly :: Matching -> Tm -> Pat -> Tm -> AM [(Syn, Matching)]
gingerly m ty p@(PC gc ps) t = hnf t >>= \case
TC hc ts | gc /= hc -> return [] | otherwise -> do
let ty' = stan m ty
tel <- constructor PAT ty' gc
gingerlies m tel ps ts >>= \case
[(us, m)] -> return [(TC gc us ::: ty', m)]
_ -> return []
t -> do
let ty' = case t of
TE (TP (_, Hide ty)) -> ty -- would like a size if it's there
_ -> ty
(e, m) <- prayPat m ty' p
push . Hyp True $ TC "=" [ty', t, upTE e]
return [(e, m)]
gingerly m ty (PM x th) t = case trice ("GINGERLY PM: " ++ x) $ thicken th t of
Nothing -> return []
Just u -> return [(t ::: stan m ty, (x, u) : m)]
gingerly _ _ _ _ = gripe Mardiness
gingerlies :: Matching -> Tel -> [Pat] -> [Tm] -> AM [([Tm], Matching)]
gingerlies m (Pr hs) [] [] = do
for (stan m hs) $ \ h -> push $ Hyp True h
return [([], m)]
gingerlies m (Ex s b) (p : ps) (t : ts) = gingerly m s p t >>= \case
[(e, m)] -> gingerlies m (b // e) ps ts >>= \case
[(us, m)] -> return [(upTE e : us, m)]
_ -> return []
_ -> return []
gingerlies m ((x, s) :*: tel) (p : ps) (t : ts) = gingerly m s p t >>= \case
[(e, m)] -> let u = upTE e in
gingerlies ((x, u) : m) tel ps ts >>= \case
[(us, m)] -> return [(u : us, m)]
_ -> return []
_ -> return []
gingerlies _ _ _ _ = return []
given :: Tm -> AM Bool{-proven?-}
given goal = do
ga <- gamma
True <- trice ("GIVEN: " ++ show goal ++ " from?\n" ++
show (filter (\case {Bind _ _ -> True; Hyp _ _ -> True; _ -> False})
(ga <>> [])))
$ return True
go ga
where
go B0 = gripe $ NotGiven goal
go (ga :< Hyp b hyp) = cope (do
True <- trice ("TRYING " ++ show hyp) $ return True
doorStop
smegUp hyp
cope (unify (TC "Prop" []) hyp goal)
(\ gr -> trice "OOPS" $ gripe gr)
return
doorStep
True <- trice "BINGO" $ return True
return b
)
(\ gr -> go ga) return
go (ga :< _) = go ga
smegUp :: Tm -> AM ()
smegUp (TE e) = smegDown e
smegUp (TC _ hs) = () <$ traverse smegUp hs
smegUp (TB (L t)) = smegUp t
smegUp (TB (K t)) = smegUp t
smegUp _ = return ()
smegDown :: Syn -> AM ()
smegDown (TP xp@(x, Hide ty)) =
cope (nomBKind x)
(\ _ -> do
ty <- hnf ty
push $ Bind xp Hole
True <- trice ("GUESS: " ++ show x ++ " " ++ show ty) $ return True
return ())
(\ _ -> return ())
smegDown (tm ::: ty) = smegUp tm >> smegUp ty
smegDown (f :$ s) = smegDown f >> smegUp s
smegDown (TF _ as bs) = traverse smegUp as >> traverse smegUp bs >> return ()
smegDown _ = return ()
(|-) :: Tm -> AM x -> AM x
h |- p = do
h <- normAQTy h
push (Hyp True h)
x <- p
pop $ \case
Hyp _ _ -> True
_ -> False
return x
splitProof
:: (Nom, Hide Tm) -- thing to split
-> Tm -- its type
-> Tm -- goal
-> (Con, Tel) -- a candidate constructor and its telescope
-> AM () -- generate relevant demands
splitProof xp@(xn, _) ty goal (c, tel) = quan B0 tel >>= demand
where
quan :: Bwd Tm -> Tel -> AM Subgoal
quan sz (Ex s b) =
("", s) |:- \ e@(TP (yn, _)) ->
(EVERY s . (yn \\)) <$> quan (sz :< TE e) (b // e)
quan sz ((y, s) :*: tel) =
(y, s) |:- \ e@(TP (yn, _)) ->
(EVERY s . (yn \\)) <$> quan (sz :< TE e) (stan [(y, TE e)] tel)
quan sz (Pr hs) = let tm = TC c (sz <>> []) in
return $ foldr GIVEN
(GIVEN (TC "=" [ty, TE (TP xp), tm]) $
PROVE ((xn \\ goal) // (tm ::: ty)))
hs
under :: Tm -> Tm -> Appl -> AM ()
under (TE lhs) (TE rhs) (_, (_, _, h) :$$ []) = () <$ go lhs rhs where
go (e :$ a) (f :$ b) = do
ty <- go e f
hnf ty >>= \case
TC "->" [dom, ran] -> do
fred . PROVE $ TC "=" [dom, a, b]
return ran
_ -> gripe FAIL
go (TP (xn, Hide ty)) (TP (yn, _)) | xn == yn = nomBKind xn >>= \case
User k | k == h -> return ty
_ -> gripe FAIL
go (TF (f, Hide sch) as bs) (TF (g, _) cs ds)
| fst (last f) == h && fst (last g) == h
= mo sch as bs cs ds
go _ _ = gripe FAIL
mo (Al s t) (a : as) bs (c : cs) ds = do
equal s (a, c)
mo (t // (a ::: s)) as bs cs ds
mo (iss :>> t) [] bs [] ds = so [] iss bs ds where
so m [] [] [] = return $ stan m t
so m ((x, s) : ss) (b : bs) (d : ds) = do
fred . PROVE $ TC "=" [stan m t, b, d]
so ((x, b) : m) ss bs ds
so _ _ _ _ = gripe FAIL
mo _ _ _ _ _ = gripe FAIL
under _ _ f = gripe FAIL | null | https://raw.githubusercontent.com/msp-strath/ask/96f3e8a0ae577cdb4633a30924a16c95b4e09bc0/Src/Proving.hs | haskell | ----------------------------------------------------------------------------
-------- ----------
------ Ask . . Proving ----------
-------- ----------
----------------------------------------------------------------------------
list of successes
would like a size if it's there
proven?
thing to split
its type
goal
a candidate constructor and its telescope
generate relevant demands |
# LANGUAGE
LambdaCase
#
LambdaCase
#-}
module Ask.Src.Proving where
import Data.Foldable
import Data.Traversable
import Ask.Src.Thin
import Ask.Src.Hide
import Ask.Src.Bwd
import Ask.Src.Lexing
import Ask.Src.RawAsk
import Ask.Src.Tm
import Ask.Src.Glueing
import Ask.Src.Context
import Ask.Src.Typing
import Debug.Trace
trice = const id
by :: Tm -> Appl -> AM TmR
by goal a@(_, (t, _, r) :$$ ss) | elem t [Uid, Sym] = do
subses <- fold <$> (gamma >>= traverse backchain)
case subses of
[(tel, subs)] -> do
(t, m) <- elabVec EXP r tel ss
mapM_ fred (stan m subs)
return $ Our t a
[] -> gripe $ ByBadRule r goal
_ -> gripe $ ByAmbiguous r goal
where
backchain (ByRule _ ((gop, (h, tel)) :<= prems))
| h == r =
cope (do
m <- maAM (gop, goal)
return [(stan m tel, stan m prems)])
(\ _ -> return [])
return
backchain _ = return []
by goal r = gripe $ NotARule r
invert :: Tm -> AM [([CxE], [Subgoal])]
invert hyp = fold <$> (gamma >>= traverse try )
where
try :: CxE -> AM [([CxE], [Subgoal])]
try (ByRule True ((gop, (h, tel)) :<= prems)) = do
doorStop
m <- prayTel [] tel
True <- trice ("INVERT TRIES: " ++ show ((hyp, gop), (h, tel), prems)) $ return True
gingerly m Prop gop hyp >>= \case
[(_, m)] -> do
let prems' = stan m prems
de <- doorStep
True <- trice ("INVERT: " ++ show m ++ " ===> " ++
show (de, prems')) $ return True
return [(de, prems')]
_ -> doorStep *> return []
try _ = return []
prayTel :: Matching -> Tel -> AM Matching
prayTel m (Pr hs) = do
for (stan m hs) $ \ h -> push $ Hyp True h
return m
prayTel m (Ex s b) = do
xn <- fresh "x"
BOO !
let xp = (xn, Hide (stan m s))
push $ Bind xp (User u)
prayTel m (b // TP xp)
prayTel m ((x, s) :*: t) = do
xn <- fresh x
BOO !
let xp = (xn, Hide (stan m s))
push $ Bind xp (User u)
prayTel ((x, TE (TP xp)) : m) t
prayPat :: Matching -> Tm -> Pat -> AM (Syn, Matching)
prayPat m ty (PC c ps) = do
ty <- hnf $ stan m ty
tel <- constructor PAT ty c
(ts, m) <- prayPats m tel ps
return (TC c ts ::: ty, m)
prayPat m ty (PM x _) = do
xn <- fresh x
BOO !
let xp = (xn, Hide (stan m ty))
push $ Bind xp (User u)
return (TP xp, (x, TE (TP xp)) : m)
prayPats :: Matching -> Tel -> [Pat] -> AM ([Tm], Matching)
prayPats m (Pr hs) [] = do
for (stan m hs) $ \ h -> push $ Hyp True h
return ([], m)
prayPats m (Ex s b) (p : ps) = do
(e, m) <- prayPat m s p
(ts, m) <- prayPats m (b // e) ps
return (upTE e : ts, m)
prayPats m ((x, s) :*: tel) (p : ps) = do
(e, m) <- prayPat m s p
(ts, m) <- prayPats ((x, upTE e) : m) tel ps
return (upTE e : ts, m)
prayPats _ _ _ = gripe Mardiness
gingerly :: Matching -> Tm -> Pat -> Tm -> AM [(Syn, Matching)]
gingerly m ty p@(PC gc ps) t = hnf t >>= \case
TC hc ts | gc /= hc -> return [] | otherwise -> do
let ty' = stan m ty
tel <- constructor PAT ty' gc
gingerlies m tel ps ts >>= \case
[(us, m)] -> return [(TC gc us ::: ty', m)]
_ -> return []
t -> do
let ty' = case t of
_ -> ty
(e, m) <- prayPat m ty' p
push . Hyp True $ TC "=" [ty', t, upTE e]
return [(e, m)]
gingerly m ty (PM x th) t = case trice ("GINGERLY PM: " ++ x) $ thicken th t of
Nothing -> return []
Just u -> return [(t ::: stan m ty, (x, u) : m)]
gingerly _ _ _ _ = gripe Mardiness
gingerlies :: Matching -> Tel -> [Pat] -> [Tm] -> AM [([Tm], Matching)]
gingerlies m (Pr hs) [] [] = do
for (stan m hs) $ \ h -> push $ Hyp True h
return [([], m)]
gingerlies m (Ex s b) (p : ps) (t : ts) = gingerly m s p t >>= \case
[(e, m)] -> gingerlies m (b // e) ps ts >>= \case
[(us, m)] -> return [(upTE e : us, m)]
_ -> return []
_ -> return []
gingerlies m ((x, s) :*: tel) (p : ps) (t : ts) = gingerly m s p t >>= \case
[(e, m)] -> let u = upTE e in
gingerlies ((x, u) : m) tel ps ts >>= \case
[(us, m)] -> return [(u : us, m)]
_ -> return []
_ -> return []
gingerlies _ _ _ _ = return []
given goal = do
ga <- gamma
True <- trice ("GIVEN: " ++ show goal ++ " from?\n" ++
show (filter (\case {Bind _ _ -> True; Hyp _ _ -> True; _ -> False})
(ga <>> [])))
$ return True
go ga
where
go B0 = gripe $ NotGiven goal
go (ga :< Hyp b hyp) = cope (do
True <- trice ("TRYING " ++ show hyp) $ return True
doorStop
smegUp hyp
cope (unify (TC "Prop" []) hyp goal)
(\ gr -> trice "OOPS" $ gripe gr)
return
doorStep
True <- trice "BINGO" $ return True
return b
)
(\ gr -> go ga) return
go (ga :< _) = go ga
smegUp :: Tm -> AM ()
smegUp (TE e) = smegDown e
smegUp (TC _ hs) = () <$ traverse smegUp hs
smegUp (TB (L t)) = smegUp t
smegUp (TB (K t)) = smegUp t
smegUp _ = return ()
smegDown :: Syn -> AM ()
smegDown (TP xp@(x, Hide ty)) =
cope (nomBKind x)
(\ _ -> do
ty <- hnf ty
push $ Bind xp Hole
True <- trice ("GUESS: " ++ show x ++ " " ++ show ty) $ return True
return ())
(\ _ -> return ())
smegDown (tm ::: ty) = smegUp tm >> smegUp ty
smegDown (f :$ s) = smegDown f >> smegUp s
smegDown (TF _ as bs) = traverse smegUp as >> traverse smegUp bs >> return ()
smegDown _ = return ()
(|-) :: Tm -> AM x -> AM x
h |- p = do
h <- normAQTy h
push (Hyp True h)
x <- p
pop $ \case
Hyp _ _ -> True
_ -> False
return x
splitProof
splitProof xp@(xn, _) ty goal (c, tel) = quan B0 tel >>= demand
where
quan :: Bwd Tm -> Tel -> AM Subgoal
quan sz (Ex s b) =
("", s) |:- \ e@(TP (yn, _)) ->
(EVERY s . (yn \\)) <$> quan (sz :< TE e) (b // e)
quan sz ((y, s) :*: tel) =
(y, s) |:- \ e@(TP (yn, _)) ->
(EVERY s . (yn \\)) <$> quan (sz :< TE e) (stan [(y, TE e)] tel)
quan sz (Pr hs) = let tm = TC c (sz <>> []) in
return $ foldr GIVEN
(GIVEN (TC "=" [ty, TE (TP xp), tm]) $
PROVE ((xn \\ goal) // (tm ::: ty)))
hs
under :: Tm -> Tm -> Appl -> AM ()
under (TE lhs) (TE rhs) (_, (_, _, h) :$$ []) = () <$ go lhs rhs where
go (e :$ a) (f :$ b) = do
ty <- go e f
hnf ty >>= \case
TC "->" [dom, ran] -> do
fred . PROVE $ TC "=" [dom, a, b]
return ran
_ -> gripe FAIL
go (TP (xn, Hide ty)) (TP (yn, _)) | xn == yn = nomBKind xn >>= \case
User k | k == h -> return ty
_ -> gripe FAIL
go (TF (f, Hide sch) as bs) (TF (g, _) cs ds)
| fst (last f) == h && fst (last g) == h
= mo sch as bs cs ds
go _ _ = gripe FAIL
mo (Al s t) (a : as) bs (c : cs) ds = do
equal s (a, c)
mo (t // (a ::: s)) as bs cs ds
mo (iss :>> t) [] bs [] ds = so [] iss bs ds where
so m [] [] [] = return $ stan m t
so m ((x, s) : ss) (b : bs) (d : ds) = do
fred . PROVE $ TC "=" [stan m t, b, d]
so ((x, b) : m) ss bs ds
so _ _ _ _ = gripe FAIL
mo _ _ _ _ _ = gripe FAIL
under _ _ f = gripe FAIL |
2c2da224c4cfbf07dc3fe890d3a1211fb89832b1f0d0200c79fd26d65926fd4d | jvf/scalaris | yaws_generated.erl | %%%----------------------------------------------------------------------
%%% File : yaws_generated.template
Author : Klacke < >
%%% Purpose :
Created : 10 Jun 2002 by Klacke < >
%%%----------------------------------------------------------------------
%% generated code from some environment variables
-module(yaws_generated).
-author('').
-export([version/0,
vardir/0,
etcdir/0]).
version() -> "2.0.2".
vardir() -> "/usr/local/var".
etcdir() -> "/usr/local/etc".
| null | https://raw.githubusercontent.com/jvf/scalaris/c069f44cf149ea6c69e24bdb08714bda242e7ee0/contrib/yaws/src/yaws_generated.erl | erlang | ----------------------------------------------------------------------
File : yaws_generated.template
Purpose :
----------------------------------------------------------------------
generated code from some environment variables | Author : Klacke < >
Created : 10 Jun 2002 by Klacke < >
-module(yaws_generated).
-author('').
-export([version/0,
vardir/0,
etcdir/0]).
version() -> "2.0.2".
vardir() -> "/usr/local/var".
etcdir() -> "/usr/local/etc".
|
860c4341deb730ba9ad02a316370f033a2e98f0b44af21cd1bc09393496902fb | ocaml/dune | proc.ml | [ execve ] does n't exist on Windows , so instead we do a
[ Unix.create_process_env ] followed by [ Unix.waitpid ] and finally [ sys_exit ] .
We use [ sys_exit ] rather than [ exit ] so that [ at_exit ] functions are not
invoked . We do n't want [ at_exit ] functions to be invoked to match the
behaviour of [ Unix.execve ] on Unix .
[Unix.create_process_env] followed by [Unix.waitpid] and finally [sys_exit].
We use [sys_exit] rather than [exit] so that [at_exit] functions are not
invoked. We don't want [at_exit] functions to be invoked to match the
behaviour of [Unix.execve] on Unix. *)
external sys_exit : int -> 'a = "caml_sys_exit"
let restore_cwd_and_execve prog argv ~env =
let env = Env.to_unix env |> Array.of_list in
let argv = Array.of_list argv in
(* run at_exit before changing the working directory *)
Stdlib.do_at_exit ();
Sys.chdir (Path.External.to_string Path.External.initial_cwd);
if Sys.win32 then
let pid =
Unix.create_process_env prog argv env Unix.stdin Unix.stdout Unix.stderr
in
match snd (Unix.waitpid [] pid) with
| WEXITED n -> sys_exit n
| WSIGNALED _ -> sys_exit 255
| WSTOPPED _ -> assert false
else (
ignore (Unix.sigprocmask SIG_SETMASK [] : int list);
Unix.execve prog argv env)
module Resource_usage = struct
type t =
{ user_cpu_time : float
; system_cpu_time : float
}
end
module Times = struct
type t =
{ elapsed_time : float
; resource_usage : Resource_usage.t option
}
end
module Process_info = struct
type t =
{ pid : Pid.t
; status : Unix.process_status
; end_time : float
; resource_usage : Resource_usage.t option
}
end
external stub_wait3 :
Unix.wait_flag list -> int * Unix.process_status * float * Resource_usage.t
= "dune_wait3"
let wait flags =
if Sys.win32 then Code_error.raise "wait3 not available on windows" []
else
let pid, status, end_time, resource_usage = stub_wait3 flags in
{ Process_info.pid = Pid.of_int pid
; status
; end_time
; resource_usage = Some resource_usage
}
| null | https://raw.githubusercontent.com/ocaml/dune/714626f4d408e5c71c24ba91d0d520588702ec52/otherlibs/stdune/src/proc.ml | ocaml | run at_exit before changing the working directory | [ execve ] does n't exist on Windows , so instead we do a
[ Unix.create_process_env ] followed by [ Unix.waitpid ] and finally [ sys_exit ] .
We use [ sys_exit ] rather than [ exit ] so that [ at_exit ] functions are not
invoked . We do n't want [ at_exit ] functions to be invoked to match the
behaviour of [ Unix.execve ] on Unix .
[Unix.create_process_env] followed by [Unix.waitpid] and finally [sys_exit].
We use [sys_exit] rather than [exit] so that [at_exit] functions are not
invoked. We don't want [at_exit] functions to be invoked to match the
behaviour of [Unix.execve] on Unix. *)
external sys_exit : int -> 'a = "caml_sys_exit"
let restore_cwd_and_execve prog argv ~env =
let env = Env.to_unix env |> Array.of_list in
let argv = Array.of_list argv in
Stdlib.do_at_exit ();
Sys.chdir (Path.External.to_string Path.External.initial_cwd);
if Sys.win32 then
let pid =
Unix.create_process_env prog argv env Unix.stdin Unix.stdout Unix.stderr
in
match snd (Unix.waitpid [] pid) with
| WEXITED n -> sys_exit n
| WSIGNALED _ -> sys_exit 255
| WSTOPPED _ -> assert false
else (
ignore (Unix.sigprocmask SIG_SETMASK [] : int list);
Unix.execve prog argv env)
module Resource_usage = struct
type t =
{ user_cpu_time : float
; system_cpu_time : float
}
end
module Times = struct
type t =
{ elapsed_time : float
; resource_usage : Resource_usage.t option
}
end
module Process_info = struct
type t =
{ pid : Pid.t
; status : Unix.process_status
; end_time : float
; resource_usage : Resource_usage.t option
}
end
external stub_wait3 :
Unix.wait_flag list -> int * Unix.process_status * float * Resource_usage.t
= "dune_wait3"
let wait flags =
if Sys.win32 then Code_error.raise "wait3 not available on windows" []
else
let pid, status, end_time, resource_usage = stub_wait3 flags in
{ Process_info.pid = Pid.of_int pid
; status
; end_time
; resource_usage = Some resource_usage
}
|
a8ba877bec8f276a84febc384a873657f3565bc0dafdeb60d9c640f2cb5ee72e | parsonsmatt/servant-persistent | User.hs | # LANGUAGE DataKinds #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE TypeOperators #
module Api.User where
import Control.Monad.Except (MonadIO, liftIO)
import Control.Monad.Logger (logDebugNS)
import qualified Control.Monad.Metrics as Metrics
import Data.Int (Int64)
import Database.Persist.Postgresql
(Entity(..), fromSqlKey, insert, selectFirst, selectList, (==.))
import Servant
import Servant.JS (vanillaJS, writeJSForAPI)
import Config (AppT(..))
import Control.Monad.Metrics (increment, metricsCounters)
import Data.HashMap.Lazy (HashMap)
import Data.IORef (readIORef)
import Data.Text (Text)
import Lens.Micro ((^.))
import Models (User(User), runDb, userEmail, userName)
import qualified Models as Md
import qualified System.Metrics.Counter as Counter
type UserAPI =
"users" :> Get '[JSON] [Entity User]
:<|> "users" :> Capture "name" Text :> Get '[JSON] (Entity User)
:<|> "users" :> ReqBody '[JSON] User :> Post '[JSON] Int64
:<|> "metrics" :> Get '[JSON] (HashMap Text Int64)
userApi :: Proxy UserAPI
userApi = Proxy
-- | The server that runs the UserAPI
userServer :: MonadIO m => ServerT UserAPI (AppT m)
userServer = allUsers :<|> singleUser :<|> createUser :<|> waiMetrics
-- | Returns all users in the database.
allUsers :: MonadIO m => AppT m [Entity User]
allUsers = do
increment "allUsers"
logDebugNS "web" "allUsers"
runDb (selectList [] [])
| Returns a user by name or throws a 404 error .
singleUser :: MonadIO m => Text -> AppT m (Entity User)
singleUser str = do
increment "singleUser"
logDebugNS "web" "singleUser"
maybeUser <- runDb (selectFirst [Md.UserName ==. str] [])
case maybeUser of
Nothing ->
throwError err404
Just person ->
return person
-- | Creates a user in the database.
createUser :: MonadIO m => User -> AppT m Int64
createUser p = do
increment "createUser"
logDebugNS "web" "creating a user"
newUser <- runDb (insert (User (userName p) (userEmail p)))
return $ fromSqlKey newUser
-- | Return wai metrics as JSON
waiMetrics :: MonadIO m => AppT m (HashMap Text Int64)
waiMetrics = do
increment "metrics"
logDebugNS "web" "metrics"
metr <- Metrics.getMetrics
liftIO $ mapM Counter.read =<< readIORef (metr ^. metricsCounters)
-- | Generates JavaScript to query the User API.
generateJavaScript :: IO ()
generateJavaScript =
writeJSForAPI (Proxy :: Proxy UserAPI) vanillaJS "./assets/api.js"
| null | https://raw.githubusercontent.com/parsonsmatt/servant-persistent/95df92b2fe9b0f421afa0cf1bcc9c3a4ca38b48c/src/Api/User.hs | haskell | # LANGUAGE OverloadedStrings #
| The server that runs the UserAPI
| Returns all users in the database.
| Creates a user in the database.
| Return wai metrics as JSON
| Generates JavaScript to query the User API. | # LANGUAGE DataKinds #
# LANGUAGE TypeOperators #
module Api.User where
import Control.Monad.Except (MonadIO, liftIO)
import Control.Monad.Logger (logDebugNS)
import qualified Control.Monad.Metrics as Metrics
import Data.Int (Int64)
import Database.Persist.Postgresql
(Entity(..), fromSqlKey, insert, selectFirst, selectList, (==.))
import Servant
import Servant.JS (vanillaJS, writeJSForAPI)
import Config (AppT(..))
import Control.Monad.Metrics (increment, metricsCounters)
import Data.HashMap.Lazy (HashMap)
import Data.IORef (readIORef)
import Data.Text (Text)
import Lens.Micro ((^.))
import Models (User(User), runDb, userEmail, userName)
import qualified Models as Md
import qualified System.Metrics.Counter as Counter
type UserAPI =
"users" :> Get '[JSON] [Entity User]
:<|> "users" :> Capture "name" Text :> Get '[JSON] (Entity User)
:<|> "users" :> ReqBody '[JSON] User :> Post '[JSON] Int64
:<|> "metrics" :> Get '[JSON] (HashMap Text Int64)
userApi :: Proxy UserAPI
userApi = Proxy
userServer :: MonadIO m => ServerT UserAPI (AppT m)
userServer = allUsers :<|> singleUser :<|> createUser :<|> waiMetrics
allUsers :: MonadIO m => AppT m [Entity User]
allUsers = do
increment "allUsers"
logDebugNS "web" "allUsers"
runDb (selectList [] [])
| Returns a user by name or throws a 404 error .
singleUser :: MonadIO m => Text -> AppT m (Entity User)
singleUser str = do
increment "singleUser"
logDebugNS "web" "singleUser"
maybeUser <- runDb (selectFirst [Md.UserName ==. str] [])
case maybeUser of
Nothing ->
throwError err404
Just person ->
return person
createUser :: MonadIO m => User -> AppT m Int64
createUser p = do
increment "createUser"
logDebugNS "web" "creating a user"
newUser <- runDb (insert (User (userName p) (userEmail p)))
return $ fromSqlKey newUser
waiMetrics :: MonadIO m => AppT m (HashMap Text Int64)
waiMetrics = do
increment "metrics"
logDebugNS "web" "metrics"
metr <- Metrics.getMetrics
liftIO $ mapM Counter.read =<< readIORef (metr ^. metricsCounters)
generateJavaScript :: IO ()
generateJavaScript =
writeJSForAPI (Proxy :: Proxy UserAPI) vanillaJS "./assets/api.js"
|
458e902fb4e141741929b7eaab6bacabe8db8dce6d0d96bec26d3318d5ae30d0 | exercism/common-lisp | etl.lisp | (defpackage :etl
(:use :cl)
(:export :transform))
(in-package :etl)
(defun transform (data)
"Transforms hash values into keys with their keys as their values."
)
| null | https://raw.githubusercontent.com/exercism/common-lisp/f3cdf6cf7e607138d1bb4d26c57999d4364af243/exercises/practice/etl/etl.lisp | lisp | (defpackage :etl
(:use :cl)
(:export :transform))
(in-package :etl)
(defun transform (data)
"Transforms hash values into keys with their keys as their values."
)
| |
57367a78ba9b78c8e4a3db1f15c3a8bb509170be0e5ec15323620aa334915d9a | c-cube/ocaml-containers | objsize.ml | (**************************************************************************)
(* *)
Copyright ( C )
(* *)
(* 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. *)
(* *)
(**************************************************************************)
(*i $Id$ i*)
(*i*)
open Obj
(*i*)
(*s Pointers already visited are stored in a hash-table, where
comparisons are done using physical equality. *)
module H = Hashtbl.Make (struct
type t = Obj.t
let equal = ( == )
let hash o = Hashtbl.hash (magic o : int)
end)
let node_table = (H.create 257 : unit H.t)
let in_table o =
try
H.find node_table o;
true
with Not_found -> false
let add_in_table o = H.add node_table o ()
let reset_table () = H.clear node_table
(*s Objects are traversed recursively, as soon as their tags are less than
[no_scan_tag]. [count] records the numbers of words already visited. *)
let size_of_double = size (repr 1.0)
let count = ref 0
let rec traverse t =
if not (in_table t) then (
add_in_table t;
if is_block t then (
let n = size t in
let tag = tag t in
if tag < no_scan_tag then (
count := !count + 1 + n;
for i = 0 to n - 1 do
let f = field t i in
if is_block f then traverse f
done
) else if tag = string_tag then
count := !count + 1 + n
else if tag = double_tag then
count := !count + size_of_double
else if tag = double_array_tag then
count := !count + 1 + (size_of_double * n)
else
incr count
)
)
(*s Sizes of objects in words and in bytes. The size in bytes is computed
system-independently according to [Sys.word_size]. *)
let size_w o =
reset_table ();
count := 0;
traverse (repr o);
!count
let size_b o = size_w o * (Sys.word_size / 8)
let size_kb o = size_w o / (8192 / Sys.word_size)
| null | https://raw.githubusercontent.com/c-cube/ocaml-containers/69f2805f1073c4ebd1063bbd58380d17e62f6324/benchs/objsize.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.
************************************************************************
i $Id$ i
i
i
s Pointers already visited are stored in a hash-table, where
comparisons are done using physical equality.
s Objects are traversed recursively, as soon as their tags are less than
[no_scan_tag]. [count] records the numbers of words already visited.
s Sizes of objects in words and in bytes. The size in bytes is computed
system-independently according to [Sys.word_size]. | Copyright ( C )
modify it under the terms of the GNU Library General Public
License version 2.1 , with the special exception on linking
open Obj
module H = Hashtbl.Make (struct
type t = Obj.t
let equal = ( == )
let hash o = Hashtbl.hash (magic o : int)
end)
let node_table = (H.create 257 : unit H.t)
let in_table o =
try
H.find node_table o;
true
with Not_found -> false
let add_in_table o = H.add node_table o ()
let reset_table () = H.clear node_table
let size_of_double = size (repr 1.0)
let count = ref 0
let rec traverse t =
if not (in_table t) then (
add_in_table t;
if is_block t then (
let n = size t in
let tag = tag t in
if tag < no_scan_tag then (
count := !count + 1 + n;
for i = 0 to n - 1 do
let f = field t i in
if is_block f then traverse f
done
) else if tag = string_tag then
count := !count + 1 + n
else if tag = double_tag then
count := !count + size_of_double
else if tag = double_array_tag then
count := !count + 1 + (size_of_double * n)
else
incr count
)
)
let size_w o =
reset_table ();
count := 0;
traverse (repr o);
!count
let size_b o = size_w o * (Sys.word_size / 8)
let size_kb o = size_w o / (8192 / Sys.word_size)
|
99dbedb791b3745dbc560a28b04e26ac839f7983a666f58bcebe5b77f827f03e | mrossini-ethz/parseq | unit-test.lisp | Copyright ( c ) 2005 , All rights reserved .
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions are
;; met:
;; * Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
;; * Redistributions in binary form must reproduce the above
;; copyright notice, this list of conditions and the following
;; disclaimer in the documentation and/or other materials provided
;; with the distribution.
* Neither the name of the Peter Seibel nor the names of its
;; contributors may be used to endorse or promote products derived
;; from this software without specific prior written permission.
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR ANY DIRECT , INDIRECT , INCIDENTAL ,
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT
LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE ,
;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package :parseq)
(defvar *test-name* nil)
(defvar *test-failures* 0)
(defmacro condition= (form condition &optional condition-object-variable &rest tests)
"Tests whether the execution of the form results in the given condition (returning T). If no condition or a different condition occurs, NIL is returned."
`(handler-case (and ,form nil)
(,condition (,@(if condition-object-variable `(,condition-object-variable) nil)) (and ,@tests))
(t () nil)))
(defmacro define-test (name parameters &body body)
"Define a test function. Within a test function we can call
other test functions or use 'check' to run individual test
cases."
`(defun ,name ,parameters
(when (null *test-name*)
(setf *test-failures* 0))
(let ((level (list-length *test-name*)) (*test-name* (append *test-name* (list ',name))) (test-failures-save *test-failures*))
(format t "~V,0TTesting ~{~a~^:~} ...~%" level *test-name*)
,@body
(if (> *test-failures* test-failures-save)
(progn
(format t "~V,0TTotal number of tests failed in ~{~a~^:~}: ~a~%" level *test-name* (- *test-failures* test-failures-save))
(plusp level))
t))))
(defun report-result (result form expanded-form)
"Report the results of a single test case. Called by 'check'."
(when (not result)
(incf *test-failures*)
(format t "~V,0T ~:[Failed~;Passed~]: ~s~@[ => ~*~s~]~%" (- (list-length *test-name*) 1) result form (not (equal form expanded-form)) expanded-form))
result)
(defmacro combine-results (&body forms)
"Logical AND operation of the given forms, but without short-circuiting. This ensures that each form is evaluated exactly once."
(with-gensyms (result)
`(let ((,result t))
,@(loop for f in forms collect `(unless ,f (setf ,result nil)))
,result)))
(defmacro check (&body forms)
"Run each expression in 'forms' once and reports whether succeded (t) or failed (nil)."
`(combine-results
,@(loop for f in forms collect `(report-result ,f ',f ,@(if (and (listp f) (not (eql 'condition= (first f)))) `((list ',(first f) ,@(rest f))) `(',f))))))
(defmacro check-with-side-effects (&body forms)
"Run each expression in 'forms' once and reports whether succeded (t) or failed (nil)."
`(combine-results
,@(loop for f in forms collect `(report-result ,f ',f ',f))))
| null | https://raw.githubusercontent.com/mrossini-ethz/parseq/c14dc4ce0b40e2c565694534dccc9af26c0a8a1c/test/unit-test.lisp | lisp | Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
LOSS OF USE ,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | Copyright ( c ) 2005 , All rights reserved .
* Neither the name of the Peter Seibel nor the names of its
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
OWNER OR ANY DIRECT , INDIRECT , INCIDENTAL ,
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
(in-package :parseq)
(defvar *test-name* nil)
(defvar *test-failures* 0)
(defmacro condition= (form condition &optional condition-object-variable &rest tests)
"Tests whether the execution of the form results in the given condition (returning T). If no condition or a different condition occurs, NIL is returned."
`(handler-case (and ,form nil)
(,condition (,@(if condition-object-variable `(,condition-object-variable) nil)) (and ,@tests))
(t () nil)))
(defmacro define-test (name parameters &body body)
"Define a test function. Within a test function we can call
other test functions or use 'check' to run individual test
cases."
`(defun ,name ,parameters
(when (null *test-name*)
(setf *test-failures* 0))
(let ((level (list-length *test-name*)) (*test-name* (append *test-name* (list ',name))) (test-failures-save *test-failures*))
(format t "~V,0TTesting ~{~a~^:~} ...~%" level *test-name*)
,@body
(if (> *test-failures* test-failures-save)
(progn
(format t "~V,0TTotal number of tests failed in ~{~a~^:~}: ~a~%" level *test-name* (- *test-failures* test-failures-save))
(plusp level))
t))))
(defun report-result (result form expanded-form)
"Report the results of a single test case. Called by 'check'."
(when (not result)
(incf *test-failures*)
(format t "~V,0T ~:[Failed~;Passed~]: ~s~@[ => ~*~s~]~%" (- (list-length *test-name*) 1) result form (not (equal form expanded-form)) expanded-form))
result)
(defmacro combine-results (&body forms)
"Logical AND operation of the given forms, but without short-circuiting. This ensures that each form is evaluated exactly once."
(with-gensyms (result)
`(let ((,result t))
,@(loop for f in forms collect `(unless ,f (setf ,result nil)))
,result)))
(defmacro check (&body forms)
"Run each expression in 'forms' once and reports whether succeded (t) or failed (nil)."
`(combine-results
,@(loop for f in forms collect `(report-result ,f ',f ,@(if (and (listp f) (not (eql 'condition= (first f)))) `((list ',(first f) ,@(rest f))) `(',f))))))
(defmacro check-with-side-effects (&body forms)
"Run each expression in 'forms' once and reports whether succeded (t) or failed (nil)."
`(combine-results
,@(loop for f in forms collect `(report-result ,f ',f ',f))))
|
22b1edfaaeb735442f6688184e884824d66661877f82d5654249d7f0c63801c8 | jumarko/clojure-experiments | omnitrace.clj | (ns clojure-experiments.tracing.omnitrace
"-trace"
;; this leads to circular dependency error in aws logs?!
#_(:require
[cyrik.omni-trace :as o]))
;; try this in `clojure-experiments.aws.logs`
#_(o/rooted-flamegraph 'clojure-experiments.aws.logs/get-all-data)
| null | https://raw.githubusercontent.com/jumarko/clojure-experiments/a87098fe69044ad65813a68cb870d824c2c2d18f/src/clojure_experiments/tracing/omnitrace.clj | clojure | this leads to circular dependency error in aws logs?!
try this in `clojure-experiments.aws.logs` | (ns clojure-experiments.tracing.omnitrace
"-trace"
#_(:require
[cyrik.omni-trace :as o]))
#_(o/rooted-flamegraph 'clojure-experiments.aws.logs/get-all-data)
|
f8f42896b704642b328e1e74cb8cf1174c4417cf505a584d16409462f42e9e29 | wdebeaum/step | enter.lisp | ;;;;
;;;; W::enter
;;;;
(define-words :pos W::v :TEMPL AGENT-AFFECTED-XP-NP-TEMPL
:words (
(W::enter
(wordfeats (W::morph (:forms (-vb) :past W::entered :ing W::entering)))
(SENSES
((EXAMPLE "the vehicle entered the enclosure")
(meta-data :origin calo-ontology :entry-date 20051213 :change-date nil :comments Penetrate)
(LF-PARENT ONT::entering)
(templ agent-neutral-xp-templ)
(SEM (F::Aspect F::bounded) (F::Time-span F::atomic))
)
((EXAMPLE "enter the title in the textbox")
(meta-data :origin calo :entry-date 20050621 :change-date nil :comments plow)
( LF - PARENT ONT::put )
;(TEMPL AGENT-AFFECTED-XP-NP-TEMPL)
(LF-PARENT ONT::record)
(TEMPL AGENT-NEUTRAL-XP-TEMPL)
(SEM (F::Aspect F::bounded) (F::Time-span F::extended))
)
((EXAMPLE "enter!")
(meta-data :origin gloss-training :entry-date 20100301 :change-date nil :comments nil)
(LF-PARENT ONT::entering)
(templ agent-templ)
(SEM (F::Aspect F::bounded) (F::Time-span F::extended))
)
((LF-PARENT ONT::enroll)
(SEM (F::Aspect F::bounded) (F::Time-span F::extended))
(example "We enter into an agreement.")
( templ agent - goal - optional - templ ( xp ( % W::PP ( W::ptype ( ? t W::into ) ) ) ) )
(templ agent-templ)
)
((LF-PARENT ONT::enroll)
(SEM (F::Aspect F::bounded) (F::Time-span F::extended))
(example "We enter the contest")
(templ agent-neutral-templ)
)
))
))
| null | https://raw.githubusercontent.com/wdebeaum/step/8810f7c877db4db809296c66275e070bfd969507/src/LexiconManager/Data/new/enter.lisp | lisp |
W::enter
(TEMPL AGENT-AFFECTED-XP-NP-TEMPL) |
(define-words :pos W::v :TEMPL AGENT-AFFECTED-XP-NP-TEMPL
:words (
(W::enter
(wordfeats (W::morph (:forms (-vb) :past W::entered :ing W::entering)))
(SENSES
((EXAMPLE "the vehicle entered the enclosure")
(meta-data :origin calo-ontology :entry-date 20051213 :change-date nil :comments Penetrate)
(LF-PARENT ONT::entering)
(templ agent-neutral-xp-templ)
(SEM (F::Aspect F::bounded) (F::Time-span F::atomic))
)
((EXAMPLE "enter the title in the textbox")
(meta-data :origin calo :entry-date 20050621 :change-date nil :comments plow)
( LF - PARENT ONT::put )
(LF-PARENT ONT::record)
(TEMPL AGENT-NEUTRAL-XP-TEMPL)
(SEM (F::Aspect F::bounded) (F::Time-span F::extended))
)
((EXAMPLE "enter!")
(meta-data :origin gloss-training :entry-date 20100301 :change-date nil :comments nil)
(LF-PARENT ONT::entering)
(templ agent-templ)
(SEM (F::Aspect F::bounded) (F::Time-span F::extended))
)
((LF-PARENT ONT::enroll)
(SEM (F::Aspect F::bounded) (F::Time-span F::extended))
(example "We enter into an agreement.")
( templ agent - goal - optional - templ ( xp ( % W::PP ( W::ptype ( ? t W::into ) ) ) ) )
(templ agent-templ)
)
((LF-PARENT ONT::enroll)
(SEM (F::Aspect F::bounded) (F::Time-span F::extended))
(example "We enter the contest")
(templ agent-neutral-templ)
)
))
))
|
96317876b8f431e500f810858a5ec4d2457d716d9cb3cb527f1e87459c20409d | Mayvenn/storefront | svg.cljc | (ns storefront.components.svg
(:require [spice.maps :as maps]
[storefront.component :as component :refer [defcomponent]]
[storefront.assets :as assets]))
;; OPTIMIZATION TOOLS:
;; hiccup -> xml: Let the browser do it... then delete the data-reactid's
;; svg -> optimized svg:
;; manual cleanup remove title, if warranted
svg - > sprited svg : move svg to a ` symbol ` in sprites.svg
;; set id
use the same viewBox
;; remove width and height
;; remove xmlns
;; use .stroke-x and .fill-x color classes (internally,
;; not in the external sprite), so SVGs change with
palette . If an SVG uses more than one stroke or
;; fill, the colors will have be inlined in the
;; sprite.
;; use it, referencing id
here , in , as svg / svg - xlink
;; in static content as xlink:href
(defn svg-xlink
([id] (svg-xlink {} id))
([opts id] (component/html [:g [:use {:xlinkHref (str "#" id)}]])))
(defn error [opts]
(component/html
[:svg opts (svg-xlink "circled-exclamation")]))
(defn angle-arrow [opts]
(component/html
[:svg opts
^:inline (svg-xlink "angle-arrow")]))
(defn dropdown-arrow [opts]
(component/html
[:svg (maps/deep-merge {:style {:stroke-width "3"}} opts)
^:inline (svg-xlink "dropdown-arrow")]))
(defn left-caret [opts]
(component/html
[:svg.mtp1 opts
^:inline (svg-xlink "left-caret")]))
(defn thick-left-arrow [opts]
(component/html
[:svg opts
^:inline (svg-xlink "thick-left-arrow")]))
(defn left-arrow [opts]
(component/html
[:svg opts
^:inline (svg-xlink "left-arrow")]))
;; Stylist Dashboard
(defn box-package [opts]
(component/html
[:svg opts
^:inline (svg-xlink "box-package")]))
;; Help
(defn phone-ringing [opts]
(component/html
[:svg (merge {:class "stroke-black" :style {:width "30px" :height "30px"}} opts)
^:inline (svg-xlink "phone-ringing")]))
(defn mail-envelope [opts]
(component/html
[:svg (merge {:class "stroke-black" :style {:width "30px" :height "30px"}} opts)
^:inline (svg-xlink "closed-mail-envelope")]))
(defn message-bubble [opts]
(component/html
[:svg (merge {:class "stroke-black" :style {:width "30px" :height "30px"}} opts)
^:inline (svg-xlink "message-bubble")]))
;;
(defn circled-check [opts]
(component/html
[:svg
(maps/deep-merge {:style {:stroke-width "0.5"}} opts)
^:inline (svg-xlink "circled-check")]))
(defn check [opts]
(component/html
[:svg
(maps/deep-merge {:style {:stroke-width "0.5"}} opts)
^:inline (svg-xlink "check")]))
(defn bag [opts]
(component/html
[:svg (merge {:style {:width "25px" :height "28px"}} opts)
^:inline (svg-xlink "bag")]))
(defn counter-inc
([] (counter-inc {}))
([opts]
(component/html
[:svg (maps/deep-merge {:class "stroke-white fill-gray" :style {:width "1.2em" :height "1.2em"}} opts)
^:inline (svg-xlink "counter-inc")])))
(defn counter-dec
([] (counter-dec {}))
([opts]
(component/html
[:svg (maps/deep-merge {:class "stroke-white fill-gray" :style {:width "1.2em" :height "1.2em"}} opts)
^:inline (svg-xlink "counter-dec")])))
(defn x-sharp [opts]
(component/html
[:svg opts
^:inline (svg-xlink "x-sharp")]))
(defn close-x [{:keys [class height width]}]
(component/html
[:svg.rotate-45 {:class class :style {:width (or width "1.2em") :height (or height "1.2em")}}
^:inline (svg-xlink "counter-inc")]))
NOTE(jeff ): was an SVG , but upgrading to zip logo is a PNG .
;; longer term, we should move away from SVG sprites and into individual images (because of http/2)
(defn quadpay-logo
([] (quadpay-logo nil))
([opts]
(component/html
[:img
(merge
{:src "//ucarecdn.com/6ed38929-a47b-4e45-bd03-1e955dc831de/-/format/auto/-/resize/76x28/zip"
:width "38"
:height "14"
:alt "zip logo"}
opts)])))
;; Social
(defn instagram
([] (instagram {}))
([opts]
(component/html
[:svg.container-size (maps/deep-merge {:class "fill-black"} opts)
^:inline (svg-xlink "instagram")])))
(defn facebook-f
([] (facebook-f {}))
([opts]
(component/html
[:svg.container-size (maps/deep-merge {:class "fill-black"} opts)
^:inline (svg-xlink "facebook-f")])))
(defn pinterest
([] (pinterest {}))
([opts]
(component/html
[:svg.container-size (maps/deep-merge {:class "fill-black"} opts)
^:inline (svg-xlink "pinterest")])))
(defn twitter
([] (twitter {}))
([opts]
(component/html
[:svg.container-size (maps/deep-merge {:class "fill-black"} opts)
^:inline (svg-xlink "twitter")])))
(defn styleseat
([] (styleseat {}))
([opts]
(component/html
[:svg.container-size (maps/deep-merge {:class "fill-black"} opts)
^:inline (svg-xlink "styleseat")])))
(defn tiktok
([] (tiktok {}))
([opts]
(component/html
[:svg.container-size (maps/deep-merge {:class "fill-black"} opts)
^:inline (svg-xlink "tiktok")])))
(def social-icon
{"instagram" instagram
"desktop" instagram
"facebook" facebook-f
"pinterest" pinterest
"twitter" twitter
"styleseat" styleseat
"tiktok" tiktok})
;; Footer
(defn ^:private mayvenn-on-social [title xlink opts]
(let [title-id (str "social-title-" xlink)]
(component/html
[:svg.container-size (maps/deep-merge {:class "fill-black"
:role "img"
:aria-labelledby title-id
:aria-label title}
opts)
[:title {:id title-id} title]
^:inline (svg-xlink {:role "presentation"} xlink)])))
(defn mayvenn-on-facebook
([] (mayvenn-on-facebook {}))
([opts]
(mayvenn-on-social "Follow Mayvenn on Facebook" "facebook-f" opts)))
(defn mayvenn-on-instagram
([] (mayvenn-on-instagram {}))
([opts]
(mayvenn-on-social "Follow Mayvenn on Instagram" "instagram" opts)))
(defn mayvenn-on-twitter
([] (mayvenn-on-twitter {}))
([opts]
(mayvenn-on-social "Follow Mayvenn on Twitter" "twitter" opts)))
(defn mayvenn-on-pinterest
([] (mayvenn-on-pinterest {}))
([opts]
(mayvenn-on-social "Follow Mayvenn on Pinterest" "pinterest" opts)))
(defn white-play-video [opts]
(component/html
[:svg opts ^:inline (svg-xlink "white-play-video")]))
(defn minus-sign [opts]
(component/html
[:svg opts
^:inline (svg-xlink "minus-sign")]))
(defn plus-sign [opts]
(component/html
[:svg opts
^:inline (svg-xlink "plus-sign")]))
(defn trash-can [opts]
(component/html
[:svg opts
^:inline (svg-xlink "trash-can")]))
(defn consolidated-trash-can [opts]
(component/html
[:svg opts
^:inline (svg-xlink "consolidated-trash-can")]))
(defn line-item-delete [opts]
(component/html
[:svg opts
^:inline (svg-xlink "line-item-delete")]))
(defn discount-tag [opts]
(component/html
[:svg.fill-s-color opts
^:inline (svg-xlink "discount-tag")]))
(defn share-arrow [opts]
(component/html
[:svg opts
^:inline (svg-xlink "share-arrow")]))
(defn coin-in-slot [opts]
(component/html
[:svg opts
^:inline (svg-xlink "coin-in-slot")]))
(defn stack-o-cash [opts]
(component/html
[:svg opts
^:inline (svg-xlink "stack-o-cash")]))
(defn icon-sms [opts]
(component/html
[:svg opts
^:inline (svg-xlink "icon-sms")]))
(defn icon-call [opts]
(component/html
[:svg opts
^:inline (svg-xlink "icon-call")]))
(defn icon-email [opts]
(component/html
[:svg opts
^:inline (svg-xlink "icon-email")]))
(defn phone [opts]
(component/html
[:svg opts
^:inline (svg-xlink "phone")]))
(defn position [opts]
(component/html
[:svg opts
^:inline (svg-xlink "position")]))
(defn info [opts]
(component/html
[:svg opts
^:inline (svg-xlink "info-outlined")]))
(defn info-filled [opts]
(component/html
[:svg opts
^:inline (svg-xlink "info-filled")]))
(defn info-color-circle [opts]
(component/html
[:svg opts
^:inline (svg-xlink "info-color-circle")]))
(defn lock [opts]
(component/html
[:svg opts
^:inline (svg-xlink "lock")]))
(defn stylist-lock [opts]
(component/html
[:svg opts
^:inline (svg-xlink "stylist-lock")]))
(defn swap-person [opts]
(component/html
[:svg opts
^:inline (svg-xlink "swap-person")]))
(defn swap-arrows [opts]
(component/html
[:svg opts
^:inline (svg-xlink "swap-arrows")]))
(defn forward-arrow [opts]
(component/html
[:svg opts
^:inline (svg-xlink "forward-arrow")]))
(defn empty-star [opts]
(component/html
[:svg (maps/deep-merge {:class "fill-s-color"} opts)
^:inline (svg-xlink "empty-star")]))
(defn half-star [opts]
(component/html
[:svg (maps/deep-merge {:class "fill-s-color"} opts)
^:inline (svg-xlink "half-star")]))
(defn three-quarter-star [opts]
(component/html
[:svg (maps/deep-merge {:class "fill-s-color"} opts)
^:inline (svg-xlink "three-quarter-star")]))
(defn whole-star [opts]
(component/html
[:svg (maps/deep-merge {:class "fill-s-color"} opts)
^:inline (svg-xlink "whole-star")]))
(defn chat-bubble [opts]
(component/html
[:svg opts
^:inline (svg-xlink "chat-bubble")]))
(defn share-icon [opts]
(component/html
[:svg opts
^:inline (svg-xlink "share-icon")]))
(defn straight-line [opts]
(component/html
[:svg opts
^:inline (svg-xlink "straight-line")]))
(defn quotation-mark [opts]
(component/html
[:svg opts
^:inline (svg-xlink "quotation-mark")]))
(defn shopping-bag [opts]
(component/html
[:svg opts
^:inline (svg-xlink "shopping-bag")]))
(defn alert-icon [opts]
(component/html
[:svg opts
^:inline (svg-xlink "alert-icon")]))
(defn heart [opts]
(component/html
[:svg opts
^:inline (svg-xlink "heart")]))
(defn calendar [opts]
(component/html
[:svg opts
^:inline (svg-xlink "calendar")]))
(defn worry-free [opts]
(component/html
[:svg opts
^:inline (svg-xlink "worry-free")]))
(defn mirror [opts]
(component/html
[:svg opts
^:inline (svg-xlink "mirror")]))
(defn check-mark [opts]
(component/html
[:svg opts
^:inline (svg-xlink "check-mark")]))
(defn mayvenn-logo [opts]
(component/html
[:svg opts
^:inline (svg-xlink "mayvenn-logo")]))
(defn mayvenn-text-logo [opts]
(component/html
[:svg opts
^:inline (svg-xlink "mayvenn-text-logo")]))
(defn play-video [opts]
(component/html
[:svg opts
^:inline (svg-xlink "play-video")]))
(defn vertical-squiggle [opts]
(component/html
[:svg opts
^:inline (svg-xlink "vertical-squiggle")]))
(defn vertical-blackline [opts]
(component/html
[:svg opts
^:inline (svg-xlink "blackline")]))
(defn map-pin [opts]
(component/html
[:svg opts
^:inline (svg-xlink "map-pin")]))
(defn qr-code-icon [opts]
(component/html
[:svg opts
^:inline (svg-xlink "qr-code-icon")]))
(defn diamond-check [opts]
(component/html
[:svg opts
^:inline (svg-xlink "diamond-check")]))
(defn button-facebook-f [opts]
(component/html
[:svg opts
^:inline (svg-xlink "button-facebook-f")]))
(defn magnifying-glass [opts]
(component/html
[:svg opts
^:inline (svg-xlink "magnifying-glass")]))
(defn funnel [opts]
(component/html
[:svg opts
^:inline (svg-xlink "funnel")]))
(defn purple-diamond [opts]
(component/html
[:svg opts
^:inline (svg-xlink "purple-diamond")]))
(defn white-diamond [opts]
(component/html
[:svg opts
^:inline (svg-xlink "white-diamond")]))
(defn pink-bang [opts]
(component/html
[:svg opts
^:inline (svg-xlink "pink-bang")]))
(defn shipping [opts]
(component/html
[:svg opts
^:inline (svg-xlink "shipping")]))
(defn experience-badge [opts]
(component/html
[:svg opts
^:inline (svg-xlink "experience-badge")]))
(defn description [opts]
(component/html
[:svg opts
^:inline (svg-xlink "description")]))
(defn shaded-shipping-package [opts]
(component/html
[:svg opts
^:inline (svg-xlink "shaded-shipping-package")]))
(defn customer-service-representative [opts]
(component/html
[:svg opts
^:inline (svg-xlink "customer-service-representative")]))
(defn exclamation-circle [opts]
(component/html
[:svg opts
^:inline (svg-xlink "exclamation-circle")]))
;; TODO: Find a way to override particular portions of the svg's fill currently
we are only able to override the larget background area and not the inner
;; diamonds
(defn chat-bubble-diamonds [opts]
(component/html
[:svg opts
^:inline (svg-xlink "chat-bubble-diamonds")]))
(defn chat-bubble-diamonds-p-color [opts]
(component/html
[:svg opts
^:inline (svg-xlink "chat-bubble-diamonds-p-color")]))
(defn crown [opts]
(component/html
[:svg opts
^:inline (svg-xlink "crown")]))
(defn certified [opts]
(component/html
[:svg opts
^:inline (svg-xlink "certified")]))
(defn edit
"A pencil denoting an edit action"
[opts]
(component/html
[:svg opts
^:inline (svg-xlink "edit")]))
(defn chat-bug
"A chat bubble icon for the live-help bug"
[opts]
(component/html
[:svg opts
^:inline (svg-xlink "chat-bug")]))
(defn snowflake
"A snowflake for the holiday shop"
[opts]
(component/html
[:svg opts
^:inline (svg-xlink "snowflake")]))
(defn hand-heart
"a heart floating above and open palm"
[opts]
(component/html
[:svg opts
^:inline (svg-xlink "hand-heart")]))
(defn shield
"shield with cross"
[opts]
(component/html
[:svg opts
^:inline (svg-xlink "shield")]))
(defn check-cloud
"checkmark in a cloud"
[opts]
(component/html
[:svg opts
^:inline (svg-xlink "check-cloud")]))
(defn custom-wig-services
"checkmark in a cloud"
[opts]
(component/html
[:svg opts
^:inline (svg-xlink "custom-wig-services")]))
(defn ship-truck
"truck with zooming motion lines"
[opts]
(component/html
[:svg opts
^:inline (svg-xlink "ship-truck")]))
(defn market
"A stall in a market"
[opts]
(component/html
[:svg opts
^:inline (svg-xlink "market")]))
(defn ribbon
"A stall in a market"
[opts]
(component/html
[:svg opts
^:inline (svg-xlink "ribbon")]))
(defn gem
"A stall in a market"
[opts]
(component/html
[:svg opts
^:inline (svg-xlink "gem")]))
(defn symbolic->html
"Converts a data from query that describes an svg to the appropriate html.
Query data is in the form: [:type options]
"
[[kind attrs]]
(component/html
(if kind
(case kind
:svg/calendar ^:inline (calendar attrs)
:svg/certified ^:inline (certified attrs)
:svg/chat-bubble-diamonds ^:inline (chat-bubble-diamonds attrs)
:svg/chat-bubble-diamonds-p-color ^:inline (chat-bubble-diamonds-p-color attrs)
:svg/check-mark ^:inline (check-mark attrs)
:svg/close-x ^:inline (close-x attrs)
:svg/crown ^:inline (crown attrs)
:svg/customer-service-representative ^:inline (customer-service-representative attrs)
:svg/discount-tag ^:inline (discount-tag attrs)
:svg/edit ^:inline (edit attrs)
:svg/experience-badge ^:inline (experience-badge attrs)
:svg/heart ^:inline (heart attrs)
:svg/icon-call ^:inline (icon-call attrs)
:svg/icon-email ^:inline (icon-email attrs)
:svg/icon-sms ^:inline (icon-sms attrs)
:svg/mayvenn-logo ^:inline (mayvenn-logo attrs)
:svg/mirror ^:inline (mirror attrs)
:svg/play-video ^:inline (play-video attrs)
:svg/shaded-shipping-package ^:inline (shaded-shipping-package attrs)
:svg/whole-star ^:inline (whole-star attrs)
:svg/worry-free ^:inline (worry-free attrs)
:svg/snowflake ^:inline (snowflake attrs)
:svg/shield ^:inline (shield attrs)
:svg/ship-truck ^:inline (ship-truck attrs)
:svg/market ^:inline (market attrs)
:svg/hand-heart ^:inline (hand-heart attrs)
:svg/check-cloud ^:inline (check-cloud attrs)
:svg/custom-wig-services ^:inline (custom-wig-services attrs)
:svg/gem ^:inline (gem attrs)
:svg/ribbon ^:inline (ribbon attrs)
:svg/lock ^:inline (lock attrs)
[:div])
[:div])))
| null | https://raw.githubusercontent.com/Mayvenn/storefront/6b26fe5bed28a7163d9ef1466e9532d862f1450a/src-cljc/storefront/components/svg.cljc | clojure | OPTIMIZATION TOOLS:
hiccup -> xml: Let the browser do it... then delete the data-reactid's
svg -> optimized svg:
manual cleanup remove title, if warranted
set id
remove width and height
remove xmlns
use .stroke-x and .fill-x color classes (internally,
not in the external sprite), so SVGs change with
fill, the colors will have be inlined in the
sprite.
use it, referencing id
in static content as xlink:href
Stylist Dashboard
Help
longer term, we should move away from SVG sprites and into individual images (because of http/2)
Social
Footer
TODO: Find a way to override particular portions of the svg's fill currently
diamonds | (ns storefront.components.svg
(:require [spice.maps :as maps]
[storefront.component :as component :refer [defcomponent]]
[storefront.assets :as assets]))
svg - > sprited svg : move svg to a ` symbol ` in sprites.svg
use the same viewBox
palette . If an SVG uses more than one stroke or
here , in , as svg / svg - xlink
(defn svg-xlink
([id] (svg-xlink {} id))
([opts id] (component/html [:g [:use {:xlinkHref (str "#" id)}]])))
(defn error [opts]
(component/html
[:svg opts (svg-xlink "circled-exclamation")]))
(defn angle-arrow [opts]
(component/html
[:svg opts
^:inline (svg-xlink "angle-arrow")]))
(defn dropdown-arrow [opts]
(component/html
[:svg (maps/deep-merge {:style {:stroke-width "3"}} opts)
^:inline (svg-xlink "dropdown-arrow")]))
(defn left-caret [opts]
(component/html
[:svg.mtp1 opts
^:inline (svg-xlink "left-caret")]))
(defn thick-left-arrow [opts]
(component/html
[:svg opts
^:inline (svg-xlink "thick-left-arrow")]))
(defn left-arrow [opts]
(component/html
[:svg opts
^:inline (svg-xlink "left-arrow")]))
(defn box-package [opts]
(component/html
[:svg opts
^:inline (svg-xlink "box-package")]))
(defn phone-ringing [opts]
(component/html
[:svg (merge {:class "stroke-black" :style {:width "30px" :height "30px"}} opts)
^:inline (svg-xlink "phone-ringing")]))
(defn mail-envelope [opts]
(component/html
[:svg (merge {:class "stroke-black" :style {:width "30px" :height "30px"}} opts)
^:inline (svg-xlink "closed-mail-envelope")]))
(defn message-bubble [opts]
(component/html
[:svg (merge {:class "stroke-black" :style {:width "30px" :height "30px"}} opts)
^:inline (svg-xlink "message-bubble")]))
(defn circled-check [opts]
(component/html
[:svg
(maps/deep-merge {:style {:stroke-width "0.5"}} opts)
^:inline (svg-xlink "circled-check")]))
(defn check [opts]
(component/html
[:svg
(maps/deep-merge {:style {:stroke-width "0.5"}} opts)
^:inline (svg-xlink "check")]))
(defn bag [opts]
(component/html
[:svg (merge {:style {:width "25px" :height "28px"}} opts)
^:inline (svg-xlink "bag")]))
(defn counter-inc
([] (counter-inc {}))
([opts]
(component/html
[:svg (maps/deep-merge {:class "stroke-white fill-gray" :style {:width "1.2em" :height "1.2em"}} opts)
^:inline (svg-xlink "counter-inc")])))
(defn counter-dec
([] (counter-dec {}))
([opts]
(component/html
[:svg (maps/deep-merge {:class "stroke-white fill-gray" :style {:width "1.2em" :height "1.2em"}} opts)
^:inline (svg-xlink "counter-dec")])))
(defn x-sharp [opts]
(component/html
[:svg opts
^:inline (svg-xlink "x-sharp")]))
(defn close-x [{:keys [class height width]}]
(component/html
[:svg.rotate-45 {:class class :style {:width (or width "1.2em") :height (or height "1.2em")}}
^:inline (svg-xlink "counter-inc")]))
NOTE(jeff ): was an SVG , but upgrading to zip logo is a PNG .
(defn quadpay-logo
([] (quadpay-logo nil))
([opts]
(component/html
[:img
(merge
{:src "//ucarecdn.com/6ed38929-a47b-4e45-bd03-1e955dc831de/-/format/auto/-/resize/76x28/zip"
:width "38"
:height "14"
:alt "zip logo"}
opts)])))
(defn instagram
([] (instagram {}))
([opts]
(component/html
[:svg.container-size (maps/deep-merge {:class "fill-black"} opts)
^:inline (svg-xlink "instagram")])))
(defn facebook-f
([] (facebook-f {}))
([opts]
(component/html
[:svg.container-size (maps/deep-merge {:class "fill-black"} opts)
^:inline (svg-xlink "facebook-f")])))
(defn pinterest
([] (pinterest {}))
([opts]
(component/html
[:svg.container-size (maps/deep-merge {:class "fill-black"} opts)
^:inline (svg-xlink "pinterest")])))
(defn twitter
([] (twitter {}))
([opts]
(component/html
[:svg.container-size (maps/deep-merge {:class "fill-black"} opts)
^:inline (svg-xlink "twitter")])))
(defn styleseat
([] (styleseat {}))
([opts]
(component/html
[:svg.container-size (maps/deep-merge {:class "fill-black"} opts)
^:inline (svg-xlink "styleseat")])))
(defn tiktok
([] (tiktok {}))
([opts]
(component/html
[:svg.container-size (maps/deep-merge {:class "fill-black"} opts)
^:inline (svg-xlink "tiktok")])))
(def social-icon
{"instagram" instagram
"desktop" instagram
"facebook" facebook-f
"pinterest" pinterest
"twitter" twitter
"styleseat" styleseat
"tiktok" tiktok})
(defn ^:private mayvenn-on-social [title xlink opts]
(let [title-id (str "social-title-" xlink)]
(component/html
[:svg.container-size (maps/deep-merge {:class "fill-black"
:role "img"
:aria-labelledby title-id
:aria-label title}
opts)
[:title {:id title-id} title]
^:inline (svg-xlink {:role "presentation"} xlink)])))
(defn mayvenn-on-facebook
([] (mayvenn-on-facebook {}))
([opts]
(mayvenn-on-social "Follow Mayvenn on Facebook" "facebook-f" opts)))
(defn mayvenn-on-instagram
([] (mayvenn-on-instagram {}))
([opts]
(mayvenn-on-social "Follow Mayvenn on Instagram" "instagram" opts)))
(defn mayvenn-on-twitter
([] (mayvenn-on-twitter {}))
([opts]
(mayvenn-on-social "Follow Mayvenn on Twitter" "twitter" opts)))
(defn mayvenn-on-pinterest
([] (mayvenn-on-pinterest {}))
([opts]
(mayvenn-on-social "Follow Mayvenn on Pinterest" "pinterest" opts)))
(defn white-play-video [opts]
(component/html
[:svg opts ^:inline (svg-xlink "white-play-video")]))
(defn minus-sign [opts]
(component/html
[:svg opts
^:inline (svg-xlink "minus-sign")]))
(defn plus-sign [opts]
(component/html
[:svg opts
^:inline (svg-xlink "plus-sign")]))
(defn trash-can [opts]
(component/html
[:svg opts
^:inline (svg-xlink "trash-can")]))
(defn consolidated-trash-can [opts]
(component/html
[:svg opts
^:inline (svg-xlink "consolidated-trash-can")]))
(defn line-item-delete [opts]
(component/html
[:svg opts
^:inline (svg-xlink "line-item-delete")]))
(defn discount-tag [opts]
(component/html
[:svg.fill-s-color opts
^:inline (svg-xlink "discount-tag")]))
(defn share-arrow [opts]
(component/html
[:svg opts
^:inline (svg-xlink "share-arrow")]))
(defn coin-in-slot [opts]
(component/html
[:svg opts
^:inline (svg-xlink "coin-in-slot")]))
(defn stack-o-cash [opts]
(component/html
[:svg opts
^:inline (svg-xlink "stack-o-cash")]))
(defn icon-sms [opts]
(component/html
[:svg opts
^:inline (svg-xlink "icon-sms")]))
(defn icon-call [opts]
(component/html
[:svg opts
^:inline (svg-xlink "icon-call")]))
(defn icon-email [opts]
(component/html
[:svg opts
^:inline (svg-xlink "icon-email")]))
(defn phone [opts]
(component/html
[:svg opts
^:inline (svg-xlink "phone")]))
(defn position [opts]
(component/html
[:svg opts
^:inline (svg-xlink "position")]))
(defn info [opts]
(component/html
[:svg opts
^:inline (svg-xlink "info-outlined")]))
(defn info-filled [opts]
(component/html
[:svg opts
^:inline (svg-xlink "info-filled")]))
(defn info-color-circle [opts]
(component/html
[:svg opts
^:inline (svg-xlink "info-color-circle")]))
(defn lock [opts]
(component/html
[:svg opts
^:inline (svg-xlink "lock")]))
(defn stylist-lock [opts]
(component/html
[:svg opts
^:inline (svg-xlink "stylist-lock")]))
(defn swap-person [opts]
(component/html
[:svg opts
^:inline (svg-xlink "swap-person")]))
(defn swap-arrows [opts]
(component/html
[:svg opts
^:inline (svg-xlink "swap-arrows")]))
(defn forward-arrow [opts]
(component/html
[:svg opts
^:inline (svg-xlink "forward-arrow")]))
(defn empty-star [opts]
(component/html
[:svg (maps/deep-merge {:class "fill-s-color"} opts)
^:inline (svg-xlink "empty-star")]))
(defn half-star [opts]
(component/html
[:svg (maps/deep-merge {:class "fill-s-color"} opts)
^:inline (svg-xlink "half-star")]))
(defn three-quarter-star [opts]
(component/html
[:svg (maps/deep-merge {:class "fill-s-color"} opts)
^:inline (svg-xlink "three-quarter-star")]))
(defn whole-star [opts]
(component/html
[:svg (maps/deep-merge {:class "fill-s-color"} opts)
^:inline (svg-xlink "whole-star")]))
(defn chat-bubble [opts]
(component/html
[:svg opts
^:inline (svg-xlink "chat-bubble")]))
(defn share-icon [opts]
(component/html
[:svg opts
^:inline (svg-xlink "share-icon")]))
(defn straight-line [opts]
(component/html
[:svg opts
^:inline (svg-xlink "straight-line")]))
(defn quotation-mark [opts]
(component/html
[:svg opts
^:inline (svg-xlink "quotation-mark")]))
(defn shopping-bag [opts]
(component/html
[:svg opts
^:inline (svg-xlink "shopping-bag")]))
(defn alert-icon [opts]
(component/html
[:svg opts
^:inline (svg-xlink "alert-icon")]))
(defn heart [opts]
(component/html
[:svg opts
^:inline (svg-xlink "heart")]))
(defn calendar [opts]
(component/html
[:svg opts
^:inline (svg-xlink "calendar")]))
(defn worry-free [opts]
(component/html
[:svg opts
^:inline (svg-xlink "worry-free")]))
(defn mirror [opts]
(component/html
[:svg opts
^:inline (svg-xlink "mirror")]))
(defn check-mark [opts]
(component/html
[:svg opts
^:inline (svg-xlink "check-mark")]))
(defn mayvenn-logo [opts]
(component/html
[:svg opts
^:inline (svg-xlink "mayvenn-logo")]))
(defn mayvenn-text-logo [opts]
(component/html
[:svg opts
^:inline (svg-xlink "mayvenn-text-logo")]))
(defn play-video [opts]
(component/html
[:svg opts
^:inline (svg-xlink "play-video")]))
(defn vertical-squiggle [opts]
(component/html
[:svg opts
^:inline (svg-xlink "vertical-squiggle")]))
(defn vertical-blackline [opts]
(component/html
[:svg opts
^:inline (svg-xlink "blackline")]))
(defn map-pin [opts]
(component/html
[:svg opts
^:inline (svg-xlink "map-pin")]))
(defn qr-code-icon [opts]
(component/html
[:svg opts
^:inline (svg-xlink "qr-code-icon")]))
(defn diamond-check [opts]
(component/html
[:svg opts
^:inline (svg-xlink "diamond-check")]))
(defn button-facebook-f [opts]
(component/html
[:svg opts
^:inline (svg-xlink "button-facebook-f")]))
(defn magnifying-glass [opts]
(component/html
[:svg opts
^:inline (svg-xlink "magnifying-glass")]))
(defn funnel [opts]
(component/html
[:svg opts
^:inline (svg-xlink "funnel")]))
(defn purple-diamond [opts]
(component/html
[:svg opts
^:inline (svg-xlink "purple-diamond")]))
(defn white-diamond [opts]
(component/html
[:svg opts
^:inline (svg-xlink "white-diamond")]))
(defn pink-bang [opts]
(component/html
[:svg opts
^:inline (svg-xlink "pink-bang")]))
(defn shipping [opts]
(component/html
[:svg opts
^:inline (svg-xlink "shipping")]))
(defn experience-badge [opts]
(component/html
[:svg opts
^:inline (svg-xlink "experience-badge")]))
(defn description [opts]
(component/html
[:svg opts
^:inline (svg-xlink "description")]))
(defn shaded-shipping-package [opts]
(component/html
[:svg opts
^:inline (svg-xlink "shaded-shipping-package")]))
(defn customer-service-representative [opts]
(component/html
[:svg opts
^:inline (svg-xlink "customer-service-representative")]))
(defn exclamation-circle [opts]
(component/html
[:svg opts
^:inline (svg-xlink "exclamation-circle")]))
we are only able to override the larget background area and not the inner
(defn chat-bubble-diamonds [opts]
(component/html
[:svg opts
^:inline (svg-xlink "chat-bubble-diamonds")]))
(defn chat-bubble-diamonds-p-color [opts]
(component/html
[:svg opts
^:inline (svg-xlink "chat-bubble-diamonds-p-color")]))
(defn crown [opts]
(component/html
[:svg opts
^:inline (svg-xlink "crown")]))
(defn certified [opts]
(component/html
[:svg opts
^:inline (svg-xlink "certified")]))
(defn edit
"A pencil denoting an edit action"
[opts]
(component/html
[:svg opts
^:inline (svg-xlink "edit")]))
(defn chat-bug
"A chat bubble icon for the live-help bug"
[opts]
(component/html
[:svg opts
^:inline (svg-xlink "chat-bug")]))
(defn snowflake
"A snowflake for the holiday shop"
[opts]
(component/html
[:svg opts
^:inline (svg-xlink "snowflake")]))
(defn hand-heart
"a heart floating above and open palm"
[opts]
(component/html
[:svg opts
^:inline (svg-xlink "hand-heart")]))
(defn shield
"shield with cross"
[opts]
(component/html
[:svg opts
^:inline (svg-xlink "shield")]))
(defn check-cloud
"checkmark in a cloud"
[opts]
(component/html
[:svg opts
^:inline (svg-xlink "check-cloud")]))
(defn custom-wig-services
"checkmark in a cloud"
[opts]
(component/html
[:svg opts
^:inline (svg-xlink "custom-wig-services")]))
(defn ship-truck
"truck with zooming motion lines"
[opts]
(component/html
[:svg opts
^:inline (svg-xlink "ship-truck")]))
(defn market
"A stall in a market"
[opts]
(component/html
[:svg opts
^:inline (svg-xlink "market")]))
(defn ribbon
"A stall in a market"
[opts]
(component/html
[:svg opts
^:inline (svg-xlink "ribbon")]))
(defn gem
"A stall in a market"
[opts]
(component/html
[:svg opts
^:inline (svg-xlink "gem")]))
(defn symbolic->html
"Converts a data from query that describes an svg to the appropriate html.
Query data is in the form: [:type options]
"
[[kind attrs]]
(component/html
(if kind
(case kind
:svg/calendar ^:inline (calendar attrs)
:svg/certified ^:inline (certified attrs)
:svg/chat-bubble-diamonds ^:inline (chat-bubble-diamonds attrs)
:svg/chat-bubble-diamonds-p-color ^:inline (chat-bubble-diamonds-p-color attrs)
:svg/check-mark ^:inline (check-mark attrs)
:svg/close-x ^:inline (close-x attrs)
:svg/crown ^:inline (crown attrs)
:svg/customer-service-representative ^:inline (customer-service-representative attrs)
:svg/discount-tag ^:inline (discount-tag attrs)
:svg/edit ^:inline (edit attrs)
:svg/experience-badge ^:inline (experience-badge attrs)
:svg/heart ^:inline (heart attrs)
:svg/icon-call ^:inline (icon-call attrs)
:svg/icon-email ^:inline (icon-email attrs)
:svg/icon-sms ^:inline (icon-sms attrs)
:svg/mayvenn-logo ^:inline (mayvenn-logo attrs)
:svg/mirror ^:inline (mirror attrs)
:svg/play-video ^:inline (play-video attrs)
:svg/shaded-shipping-package ^:inline (shaded-shipping-package attrs)
:svg/whole-star ^:inline (whole-star attrs)
:svg/worry-free ^:inline (worry-free attrs)
:svg/snowflake ^:inline (snowflake attrs)
:svg/shield ^:inline (shield attrs)
:svg/ship-truck ^:inline (ship-truck attrs)
:svg/market ^:inline (market attrs)
:svg/hand-heart ^:inline (hand-heart attrs)
:svg/check-cloud ^:inline (check-cloud attrs)
:svg/custom-wig-services ^:inline (custom-wig-services attrs)
:svg/gem ^:inline (gem attrs)
:svg/ribbon ^:inline (ribbon attrs)
:svg/lock ^:inline (lock attrs)
[:div])
[:div])))
|
7a95f4b08a2af14609ff8e5879211d285709bac0d536bc3bc9ca78572046ce79 | paf31/language-typescript | Parser.hs | -----------------------------------------------------------------------------
--
Module : Language . TypeScript .
Copyright : ( c ) DICOM Grid Inc. 2013
License : MIT
--
Maintainer : < >
-- Stability : experimental
-- Portability :
--
-- |
--
-----------------------------------------------------------------------------
module Language.TypeScript.Parser (
declarationSourceFile,
nextIdentifier
) where
import Language.TypeScript.Types
import Language.TypeScript.Lexer
import Text.Parsec
import Text.Parsec.Expr
import Text.Parsec.String (parseFromFile)
import Control.Applicative
(Applicative(..), (<$>), (<*>), (<*), (*>))
commentPlaceholder = fmap toOffset getPosition where
toOffset pos = Left $ (sourceLine pos, sourceColumn pos)
nextIdentifier =
skipMany (choice (map (try . reserved) [ "export", "declare", "public", "private", "static" ]))
>> choice (map (try . reserved) [ "var", "function", "class", "interface", "enum", "module" ])
>> identifier
declarationSourceFile = whiteSpace >> many declarationElement <* eof
exported = reserved "export" >> return Exported
declarationElement = choice $ map try
[ InterfaceDeclaration <$> commentPlaceholder <*> optionMaybe exported <*> interface
, ExportDeclaration <$> (reserved "export" >> lexeme (char '=') *> identifier)
, ExternalImportDeclaration <$> optionMaybe exported <*> (reserved "import" *> identifier) <*> (lexeme (char '=') *> reserved "require" *> parens stringLiteral <* semi)
, ImportDeclaration <$> optionMaybe exported <*> (reserved "import" *> identifier) <*> (lexeme (char '=') *> entityName)
, AmbientDeclaration <$> commentPlaceholder <*> optionMaybe exported <*> (reserved "declare" *> ambientDeclaration)
]
ambientDeclaration = choice (map try
[ ambientVariableDeclaration
, ambientFunctionDeclaration
, ambientClassDeclaration
, ambientInterfaceDeclaration
, ambientEnumDeclaration
, ambientModuleDeclaration
, ambientExternalModuleDeclaration
])
ambientVariableDeclaration = AmbientVariableDeclaration <$> commentPlaceholder <*> (reserved "var" *> identifier) <*> (optionMaybe typeAnnotation <* semi)
ambientFunctionDeclaration = AmbientFunctionDeclaration <$> commentPlaceholder <*> (reserved "function" *> identifier) <*> (parameterListAndReturnType <* semi)
ambientClassDeclaration = AmbientClassDeclaration <$> commentPlaceholder <*> (reserved "class" *> identifier) <*> optionMaybe typeParameters <*> optionMaybe extendsClause <*> optionMaybe implementsClause <*> braces (sepEndBy ambientClassBodyElement semi)
ambientInterfaceDeclaration = AmbientInterfaceDeclaration <$> interface
ambientEnumDeclaration = AmbientEnumDeclaration <$> commentPlaceholder <*> (reserved "enum" *> identifier) <*> braces (sepEndBy enumMember comma)
where
enumMember = (,) <$> propertyName <*> optionMaybe (lexeme (char '=') >> integer)
ambientModuleDeclaration = AmbientModuleDeclaration <$> commentPlaceholder <*> (reserved "module" *> sepBy identifier dot) <*> braces (many ambientDeclaration)
ambientExternalModuleDeclaration = AmbientExternalModuleDeclaration <$> commentPlaceholder <*> (reserved "module" *> stringLiteral) <*> braces (many ambientExternalModuleElement)
ambientExternalModuleElement = choice (map try
[ AmbientModuleElement <$> ambientDeclaration
, exportAssignment
, externalImportDeclaration ])
exportAssignment = ExportAssignment <$> (reserved "export" *> lexeme (char '=') *> identifier <* semi)
externalImportDeclaration =
AmbientModuleExternalImportDeclaration <$> optionMaybe exported
<*> (reserved "import" *> identifier)
<*> (lexeme (char '=') *> reserved "require" *> stringLiteral)
ambientClassBodyElement = (,) <$> commentPlaceholder <*> (choice $ map try
[ ambientConstructorDeclaration
, ambientMemberDeclaration
, ambientIndexSignature ])
ambientConstructorDeclaration = AmbientConstructorDeclaration <$> (reserved "constructor" *> parameterList <* semi)
ambientMemberDeclaration = AmbientMemberDeclaration <$> optionMaybe publicOrPrivate <*> optionMaybe static <*> propertyName <*> choice [fmap Right parameterListAndReturnType, fmap Left (optionMaybe typeAnnotation)]
ambientIndexSignature = AmbientIndexSignature <$> indexSignature
interface = Interface <$> commentPlaceholder <*> (reserved "interface" *> identifier) <*> optionMaybe typeParameters <*> optionMaybe extendsClause <*> objectType
extendsClause = reserved "extends" >> classOrInterfaceTypeList
implementsClause = reserved "implements" >> classOrInterfaceTypeList
classOrInterfaceTypeList = commaSep typeRef
objectType = braces typeBody
typeBody = TypeBody <$> sepEndBy typeMember semi
where
typeMember = (,) <$> commentPlaceholder <*> (choice $ map try [ methodSignature, propertySignature, callSignature, constructSignature, typeIndexSignature ])
propertySignature = PropertySignature <$> propertyName <*> optionMaybe (lexeme (char '?' >> return Optional)) <*> optionMaybe typeAnnotation
propertyName = identifier <|> stringLiteral
typeAnnotation = colon >> _type
callSignature = CallSignature <$> parameterListAndReturnType
parameterListAndReturnType = ParameterListAndReturnType <$> optionMaybe typeParameters <*> parens parameterList <*> optionMaybe typeAnnotation
parameterList = commaSep parameter
parameter = choice
[ try $ RequiredOrOptionalParameter <$> optionMaybe publicOrPrivate <*> identifier <*> optionMaybe (lexeme (char '?' >> return Optional)) <*> optionMaybe typeAnnotation
, RestParameter <$> (lexeme (string "...") *> identifier) <*> optionMaybe typeAnnotation
]
static = reserved "static" >> return Static
publicOrPrivate = choice
[ reserved "public" >> return Public
, reserved "private" >> return Private ]
stringOrNumber = choice
[ reserved "string" >> return String
, reserved "number" >> return Number ]
constructSignature = ConstructSignature <$> (reserved "new" *> optionMaybe typeParameters) <*> parens parameterList <*> optionMaybe typeAnnotation
typeIndexSignature = TypeIndexSignature <$> indexSignature
indexSignature = squares (IndexSignature <$> identifier <*> (colon *> stringOrNumber)) <*> typeAnnotation
methodSignature = MethodSignature <$> propertyName <*> optionMaybe (lexeme (char '?' >> return Optional)) <*> parameterListAndReturnType
typeParameters = angles $ commaSep1 typeParameter
typeParameter = TypeParameter <$> identifier <*> optionMaybe (reserved "extends" >> _type)
fold :: Stream s m t => ParsecT s u m a -> ParsecT s u m b -> (a -> b -> a) -> ParsecT s u m a
fold first more combine = do
a <- first
bs <- many more
return $ foldl combine a bs
_type = lexeme $ choice [ arrayType, functionType, constructorType ]
where
arrayType = fold atomicType (squares whiteSpace) (flip $ const ArrayType)
atomicType = choice $ map try
[ Predefined <$> predefinedType
, TypeReference <$> typeRef
, ObjectType <$> objectType
]
functionType = FunctionType <$> optionMaybe typeParameters <*> parens parameterList <*> returnType
constructorType = ConstructorType <$> (reserved "new" *> optionMaybe typeParameters) <*> parens parameterList <*> returnType
returnType = lexeme (string "=>") *> _type
typeRef = TypeRef <$> typeName <*> optionMaybe typeArguments
predefinedType = choice
[ reserved "any" >> return AnyType
, reserved "number" >> return NumberType
, (reserved "boolean" <|> reserved "bool") >> return BooleanType
, reserved "string" >> return StringType
, reserved "void" >> return VoidType
]
entityName = fmap toEntityName (sepBy1 identifier dot)
where
toEntityName [t] = EntityName Nothing t
toEntityName ts = EntityName (Just $ ModuleName $ init ts) (last ts)
typeName = fmap toTypeName (sepBy1 identifier dot)
where
toTypeName [t] = TypeName Nothing t
toTypeName ts = TypeName (Just $ ModuleName $ init ts) (last ts)
typeArguments = angles $ commaSep1 _type
| null | https://raw.githubusercontent.com/paf31/language-typescript/b3f7dc5f00c768232aec455a0c32461f6bda7a53/src/Language/TypeScript/Parser.hs | haskell | ---------------------------------------------------------------------------
Stability : experimental
Portability :
|
--------------------------------------------------------------------------- | Module : Language . TypeScript .
Copyright : ( c ) DICOM Grid Inc. 2013
License : MIT
Maintainer : < >
module Language.TypeScript.Parser (
declarationSourceFile,
nextIdentifier
) where
import Language.TypeScript.Types
import Language.TypeScript.Lexer
import Text.Parsec
import Text.Parsec.Expr
import Text.Parsec.String (parseFromFile)
import Control.Applicative
(Applicative(..), (<$>), (<*>), (<*), (*>))
commentPlaceholder = fmap toOffset getPosition where
toOffset pos = Left $ (sourceLine pos, sourceColumn pos)
nextIdentifier =
skipMany (choice (map (try . reserved) [ "export", "declare", "public", "private", "static" ]))
>> choice (map (try . reserved) [ "var", "function", "class", "interface", "enum", "module" ])
>> identifier
declarationSourceFile = whiteSpace >> many declarationElement <* eof
exported = reserved "export" >> return Exported
declarationElement = choice $ map try
[ InterfaceDeclaration <$> commentPlaceholder <*> optionMaybe exported <*> interface
, ExportDeclaration <$> (reserved "export" >> lexeme (char '=') *> identifier)
, ExternalImportDeclaration <$> optionMaybe exported <*> (reserved "import" *> identifier) <*> (lexeme (char '=') *> reserved "require" *> parens stringLiteral <* semi)
, ImportDeclaration <$> optionMaybe exported <*> (reserved "import" *> identifier) <*> (lexeme (char '=') *> entityName)
, AmbientDeclaration <$> commentPlaceholder <*> optionMaybe exported <*> (reserved "declare" *> ambientDeclaration)
]
ambientDeclaration = choice (map try
[ ambientVariableDeclaration
, ambientFunctionDeclaration
, ambientClassDeclaration
, ambientInterfaceDeclaration
, ambientEnumDeclaration
, ambientModuleDeclaration
, ambientExternalModuleDeclaration
])
ambientVariableDeclaration = AmbientVariableDeclaration <$> commentPlaceholder <*> (reserved "var" *> identifier) <*> (optionMaybe typeAnnotation <* semi)
ambientFunctionDeclaration = AmbientFunctionDeclaration <$> commentPlaceholder <*> (reserved "function" *> identifier) <*> (parameterListAndReturnType <* semi)
ambientClassDeclaration = AmbientClassDeclaration <$> commentPlaceholder <*> (reserved "class" *> identifier) <*> optionMaybe typeParameters <*> optionMaybe extendsClause <*> optionMaybe implementsClause <*> braces (sepEndBy ambientClassBodyElement semi)
ambientInterfaceDeclaration = AmbientInterfaceDeclaration <$> interface
ambientEnumDeclaration = AmbientEnumDeclaration <$> commentPlaceholder <*> (reserved "enum" *> identifier) <*> braces (sepEndBy enumMember comma)
where
enumMember = (,) <$> propertyName <*> optionMaybe (lexeme (char '=') >> integer)
ambientModuleDeclaration = AmbientModuleDeclaration <$> commentPlaceholder <*> (reserved "module" *> sepBy identifier dot) <*> braces (many ambientDeclaration)
ambientExternalModuleDeclaration = AmbientExternalModuleDeclaration <$> commentPlaceholder <*> (reserved "module" *> stringLiteral) <*> braces (many ambientExternalModuleElement)
ambientExternalModuleElement = choice (map try
[ AmbientModuleElement <$> ambientDeclaration
, exportAssignment
, externalImportDeclaration ])
exportAssignment = ExportAssignment <$> (reserved "export" *> lexeme (char '=') *> identifier <* semi)
externalImportDeclaration =
AmbientModuleExternalImportDeclaration <$> optionMaybe exported
<*> (reserved "import" *> identifier)
<*> (lexeme (char '=') *> reserved "require" *> stringLiteral)
ambientClassBodyElement = (,) <$> commentPlaceholder <*> (choice $ map try
[ ambientConstructorDeclaration
, ambientMemberDeclaration
, ambientIndexSignature ])
ambientConstructorDeclaration = AmbientConstructorDeclaration <$> (reserved "constructor" *> parameterList <* semi)
ambientMemberDeclaration = AmbientMemberDeclaration <$> optionMaybe publicOrPrivate <*> optionMaybe static <*> propertyName <*> choice [fmap Right parameterListAndReturnType, fmap Left (optionMaybe typeAnnotation)]
ambientIndexSignature = AmbientIndexSignature <$> indexSignature
interface = Interface <$> commentPlaceholder <*> (reserved "interface" *> identifier) <*> optionMaybe typeParameters <*> optionMaybe extendsClause <*> objectType
extendsClause = reserved "extends" >> classOrInterfaceTypeList
implementsClause = reserved "implements" >> classOrInterfaceTypeList
classOrInterfaceTypeList = commaSep typeRef
objectType = braces typeBody
typeBody = TypeBody <$> sepEndBy typeMember semi
where
typeMember = (,) <$> commentPlaceholder <*> (choice $ map try [ methodSignature, propertySignature, callSignature, constructSignature, typeIndexSignature ])
propertySignature = PropertySignature <$> propertyName <*> optionMaybe (lexeme (char '?' >> return Optional)) <*> optionMaybe typeAnnotation
propertyName = identifier <|> stringLiteral
typeAnnotation = colon >> _type
callSignature = CallSignature <$> parameterListAndReturnType
parameterListAndReturnType = ParameterListAndReturnType <$> optionMaybe typeParameters <*> parens parameterList <*> optionMaybe typeAnnotation
parameterList = commaSep parameter
parameter = choice
[ try $ RequiredOrOptionalParameter <$> optionMaybe publicOrPrivate <*> identifier <*> optionMaybe (lexeme (char '?' >> return Optional)) <*> optionMaybe typeAnnotation
, RestParameter <$> (lexeme (string "...") *> identifier) <*> optionMaybe typeAnnotation
]
static = reserved "static" >> return Static
publicOrPrivate = choice
[ reserved "public" >> return Public
, reserved "private" >> return Private ]
stringOrNumber = choice
[ reserved "string" >> return String
, reserved "number" >> return Number ]
constructSignature = ConstructSignature <$> (reserved "new" *> optionMaybe typeParameters) <*> parens parameterList <*> optionMaybe typeAnnotation
typeIndexSignature = TypeIndexSignature <$> indexSignature
indexSignature = squares (IndexSignature <$> identifier <*> (colon *> stringOrNumber)) <*> typeAnnotation
methodSignature = MethodSignature <$> propertyName <*> optionMaybe (lexeme (char '?' >> return Optional)) <*> parameterListAndReturnType
typeParameters = angles $ commaSep1 typeParameter
typeParameter = TypeParameter <$> identifier <*> optionMaybe (reserved "extends" >> _type)
fold :: Stream s m t => ParsecT s u m a -> ParsecT s u m b -> (a -> b -> a) -> ParsecT s u m a
fold first more combine = do
a <- first
bs <- many more
return $ foldl combine a bs
_type = lexeme $ choice [ arrayType, functionType, constructorType ]
where
arrayType = fold atomicType (squares whiteSpace) (flip $ const ArrayType)
atomicType = choice $ map try
[ Predefined <$> predefinedType
, TypeReference <$> typeRef
, ObjectType <$> objectType
]
functionType = FunctionType <$> optionMaybe typeParameters <*> parens parameterList <*> returnType
constructorType = ConstructorType <$> (reserved "new" *> optionMaybe typeParameters) <*> parens parameterList <*> returnType
returnType = lexeme (string "=>") *> _type
typeRef = TypeRef <$> typeName <*> optionMaybe typeArguments
predefinedType = choice
[ reserved "any" >> return AnyType
, reserved "number" >> return NumberType
, (reserved "boolean" <|> reserved "bool") >> return BooleanType
, reserved "string" >> return StringType
, reserved "void" >> return VoidType
]
entityName = fmap toEntityName (sepBy1 identifier dot)
where
toEntityName [t] = EntityName Nothing t
toEntityName ts = EntityName (Just $ ModuleName $ init ts) (last ts)
typeName = fmap toTypeName (sepBy1 identifier dot)
where
toTypeName [t] = TypeName Nothing t
toTypeName ts = TypeName (Just $ ModuleName $ init ts) (last ts)
typeArguments = angles $ commaSep1 _type
|
db1198af5ae9ba4eacbcb10696365f19f29a37c71e0d66011bfe3e69d6d18de7 | ocamllabs/ocaml-effects | pr51_ok.ml | module X=struct
module type SIG=sig type t=int val x:t end
module F(Y:SIG) : SIG = struct type t=Y.t let x=Y.x end
end;;
module DUMMY=struct type t=int let x=2 end;;
let x = (3 : X.F(DUMMY).t);;
module X2=struct
module type SIG=sig type t=int val x:t end
module F(Y:SIG)(Z:SIG) = struct type t=Y.t let x=Y.x type t'=Z.t let x'=Z.x end
end;;
let x = (3 : X2.F(DUMMY)(DUMMY).t);;
let x = (3 : X2.F(DUMMY)(DUMMY).t');;
| null | https://raw.githubusercontent.com/ocamllabs/ocaml-effects/36008b741adc201bf9b547545344507da603ae31/testsuite/tests/typing-modules-bugs/pr51_ok.ml | ocaml | module X=struct
module type SIG=sig type t=int val x:t end
module F(Y:SIG) : SIG = struct type t=Y.t let x=Y.x end
end;;
module DUMMY=struct type t=int let x=2 end;;
let x = (3 : X.F(DUMMY).t);;
module X2=struct
module type SIG=sig type t=int val x:t end
module F(Y:SIG)(Z:SIG) = struct type t=Y.t let x=Y.x type t'=Z.t let x'=Z.x end
end;;
let x = (3 : X2.F(DUMMY)(DUMMY).t);;
let x = (3 : X2.F(DUMMY)(DUMMY).t');;
| |
c29376da74786665ae96e04f3ba3d4666802bf5b05721b323a01b452b5b88b95 | igarnier/ocaml-geth | storage.ml | open Lwt.Infix
open Geth
open Geth_lwt
open Contract
open Compile
(* --------------------------------------------------------------------- *)
(* Some helpful functions *)
(* --------------------------------------------------------------------- *)
Read password from stdin in a stealthy manner
let read_secret () =
let open Unix in
let term_init = tcgetattr stdin in
let term_no_echo = {term_init with c_echo= false} in
tcsetattr stdin TCSADRAIN term_no_echo ;
let password =
try read_line ()
with _ ->
tcsetattr stdin TCSAFLUSH term_init ;
failwith "read_secret: readline failed" in
tcsetattr stdin TCSAFLUSH term_init ;
password
let input_password (account : Types.Address.t) =
Printf.printf "password for account %s: %!" (account :> string) ;
let res = read_secret () in
print_newline () ; res
(* --------------------------------------------------------------------- *)
(* Deploying a smart contract. We functorize the code over some global
parameters (like the creating account). *)
(* --------------------------------------------------------------------- *)
Testing ABI argument encoding
open SolidityTypes
*
* let _ =
* let string_t = Tatomic Tstring in
* let uint_t = Tatomic ( Tuint { w = Bits.int 32 } ) in
* let res = ABI.encode_value ( ABI.Tuple [ ABI.Int { v = 123L ; t = uint_t } ;
* ABI.Int { v = 456L ; t = uint_t } ;
* ABI.String { v = " thequickbrownfoxjumpsoverthelazydog " ; t = string_t } ;
* ABI.String { v = " shesellsseashellsontheseashore " ; t = string_t }
* ] )
* in
* Printf.printf " % s\n " ( Bitstr.(hex_as_string ( uncompress res ) ) )
*
* let _ =
* let string_t = Tatomic Tstring in
* let uint_t = Tatomic (Tuint { w = Bits.int 32 }) in
* let res = ABI.encode_value (ABI.Tuple [ ABI.Int { v = 123L; t = uint_t };
* ABI.Int { v = 456L; t = uint_t };
* ABI.String { v = "thequickbrownfoxjumpsoverthelazydog"; t = string_t };
* ABI.String { v = "shesellsseashellsontheseashore"; t = string_t }
* ])
* in
* Printf.printf "%s\n" (Bitstr.(hex_as_string (uncompress res))) *)
module Storage (X : sig
val account : Types.Address.t
val uri : Uri.t
end) =
struct
let _ =
let passphrase = input_password X.account in
Rpc.Personal.unlock_account ~account:X.account
(Uri.of_string ":8545")
~passphrase ~unlock_duration:3600
Compile solidity file using solc with the right options , parse the
result back . This includes the binary code of the contract and its ABI .
result back. This includes the binary code of the contract and its ABI. *)
let solidity_output = Compile.to_json ~filename:"storage.sol"
(* Get the contract address on chain *)
let deploy_receipt () =
deploy_rpc ~url:X.uri ~account:X.account ~gas:(Z.of_int 175000)
~contract:solidity_output
~arguments:
SolidityValue.[uint256 (Z.of_int64 0x123456L); string "This is a test"]
()
let storage_ctx_address () =
deploy_receipt ()
>>= fun x ->
match x.Types.Tx.contract_address with
| None -> Lwt.fail_with "could not get contract address from deploy receipt"
| Some addr -> Lwt.return addr
(* --------------------------------------------------------------------- *)
(* Calling a method from a solidity smart contract *)
(* --------------------------------------------------------------------- *)
let contract =
match solidity_output.contracts with
| [] | _ :: _ :: _ -> failwith "Storage: more than one contract"
| [(_, ctx)] -> ctx
let set =
let set_abi =
match Contract.find_function contract "set" with
| None -> failwith "set method not found in solidity output"
| Some abi -> abi in
fun i ->
storage_ctx_address ()
>>= fun ctx ->
execute_method ~url:X.uri ~abi:set_abi
~arguments:[SolidityValue.uint256 i] ~src:X.account ~ctx
~gas:(Z.of_int 99999) ()
>|= fun {logs; _} ->
List.fold_left
(fun acc log -> ABI.Evt.of_log contract.evts log :: acc)
[] logs
let get =
let get_abi =
match Contract.find_function contract "get" with
| None -> failwith "get method not found in solidity output"
| Some abi -> abi in
fun () ->
storage_ctx_address ()
>>= fun ctx ->
call_method ~url:X.uri ~abi:get_abi ~arguments:[] ~src:X.account ~ctx
~gas:(Z.of_int 99999) ()
let _ =
* if
* . Personal.unlock_account
* ~uri : X.uri
* ~account : X.account
* ~passphrase:(input_password X.account )
* ~unlock_duration:300
* then
* ( )
* else
* " Could not unlock account "
* if
* Rpc.Personal.unlock_account
* ~uri:X.uri
* ~account:X.account
* ~passphrase:(input_password X.account)
* ~unlock_duration:300
* then
* ()
* else
* failwith "Could not unlock account" *)
end
module X = struct
let account = Types.Address.of_0x "0x0cb903d0139c1322a52f70038332efd363f94ea8"
let uri = Uri.of_string ":8545"
end
module S = Storage (X)
let receipt = S.set (Z.of_int64 0x666L)
let main () =
S.storage_ctx_address ()
>>= fun x ->
Printf.printf "%s\n" (Types.Address.show x) ;
S.get ()
>>= fun res ->
Printf.printf "result: %s\n" res ;
Lwt.return_unit
let () = Lwt_main.run (main ())
| null | https://raw.githubusercontent.com/igarnier/ocaml-geth/e87ca9f86f79190aff108a14aaae6e925aed5641/examples/solidity/storage.ml | ocaml | ---------------------------------------------------------------------
Some helpful functions
---------------------------------------------------------------------
---------------------------------------------------------------------
Deploying a smart contract. We functorize the code over some global
parameters (like the creating account).
---------------------------------------------------------------------
Get the contract address on chain
---------------------------------------------------------------------
Calling a method from a solidity smart contract
--------------------------------------------------------------------- | open Lwt.Infix
open Geth
open Geth_lwt
open Contract
open Compile
Read password from stdin in a stealthy manner
let read_secret () =
let open Unix in
let term_init = tcgetattr stdin in
let term_no_echo = {term_init with c_echo= false} in
tcsetattr stdin TCSADRAIN term_no_echo ;
let password =
try read_line ()
with _ ->
tcsetattr stdin TCSAFLUSH term_init ;
failwith "read_secret: readline failed" in
tcsetattr stdin TCSAFLUSH term_init ;
password
let input_password (account : Types.Address.t) =
Printf.printf "password for account %s: %!" (account :> string) ;
let res = read_secret () in
print_newline () ; res
Testing ABI argument encoding
open SolidityTypes
*
* let _ =
* let string_t = Tatomic Tstring in
* let uint_t = Tatomic ( Tuint { w = Bits.int 32 } ) in
* let res = ABI.encode_value ( ABI.Tuple [ ABI.Int { v = 123L ; t = uint_t } ;
* ABI.Int { v = 456L ; t = uint_t } ;
* ABI.String { v = " thequickbrownfoxjumpsoverthelazydog " ; t = string_t } ;
* ABI.String { v = " shesellsseashellsontheseashore " ; t = string_t }
* ] )
* in
* Printf.printf " % s\n " ( Bitstr.(hex_as_string ( uncompress res ) ) )
*
* let _ =
* let string_t = Tatomic Tstring in
* let uint_t = Tatomic (Tuint { w = Bits.int 32 }) in
* let res = ABI.encode_value (ABI.Tuple [ ABI.Int { v = 123L; t = uint_t };
* ABI.Int { v = 456L; t = uint_t };
* ABI.String { v = "thequickbrownfoxjumpsoverthelazydog"; t = string_t };
* ABI.String { v = "shesellsseashellsontheseashore"; t = string_t }
* ])
* in
* Printf.printf "%s\n" (Bitstr.(hex_as_string (uncompress res))) *)
module Storage (X : sig
val account : Types.Address.t
val uri : Uri.t
end) =
struct
let _ =
let passphrase = input_password X.account in
Rpc.Personal.unlock_account ~account:X.account
(Uri.of_string ":8545")
~passphrase ~unlock_duration:3600
Compile solidity file using solc with the right options , parse the
result back . This includes the binary code of the contract and its ABI .
result back. This includes the binary code of the contract and its ABI. *)
let solidity_output = Compile.to_json ~filename:"storage.sol"
let deploy_receipt () =
deploy_rpc ~url:X.uri ~account:X.account ~gas:(Z.of_int 175000)
~contract:solidity_output
~arguments:
SolidityValue.[uint256 (Z.of_int64 0x123456L); string "This is a test"]
()
let storage_ctx_address () =
deploy_receipt ()
>>= fun x ->
match x.Types.Tx.contract_address with
| None -> Lwt.fail_with "could not get contract address from deploy receipt"
| Some addr -> Lwt.return addr
let contract =
match solidity_output.contracts with
| [] | _ :: _ :: _ -> failwith "Storage: more than one contract"
| [(_, ctx)] -> ctx
let set =
let set_abi =
match Contract.find_function contract "set" with
| None -> failwith "set method not found in solidity output"
| Some abi -> abi in
fun i ->
storage_ctx_address ()
>>= fun ctx ->
execute_method ~url:X.uri ~abi:set_abi
~arguments:[SolidityValue.uint256 i] ~src:X.account ~ctx
~gas:(Z.of_int 99999) ()
>|= fun {logs; _} ->
List.fold_left
(fun acc log -> ABI.Evt.of_log contract.evts log :: acc)
[] logs
let get =
let get_abi =
match Contract.find_function contract "get" with
| None -> failwith "get method not found in solidity output"
| Some abi -> abi in
fun () ->
storage_ctx_address ()
>>= fun ctx ->
call_method ~url:X.uri ~abi:get_abi ~arguments:[] ~src:X.account ~ctx
~gas:(Z.of_int 99999) ()
let _ =
* if
* . Personal.unlock_account
* ~uri : X.uri
* ~account : X.account
* ~passphrase:(input_password X.account )
* ~unlock_duration:300
* then
* ( )
* else
* " Could not unlock account "
* if
* Rpc.Personal.unlock_account
* ~uri:X.uri
* ~account:X.account
* ~passphrase:(input_password X.account)
* ~unlock_duration:300
* then
* ()
* else
* failwith "Could not unlock account" *)
end
module X = struct
let account = Types.Address.of_0x "0x0cb903d0139c1322a52f70038332efd363f94ea8"
let uri = Uri.of_string ":8545"
end
module S = Storage (X)
let receipt = S.set (Z.of_int64 0x666L)
let main () =
S.storage_ctx_address ()
>>= fun x ->
Printf.printf "%s\n" (Types.Address.show x) ;
S.get ()
>>= fun res ->
Printf.printf "result: %s\n" res ;
Lwt.return_unit
let () = Lwt_main.run (main ())
|
235138e669dffd2905f6e9839c2219cff6bee5af2b047f93b996832dd7cdfb4f | jaspervdj/number-six | Join.hs | -- | Module to join channels
--
{-# LANGUAGE OverloadedStrings #-}
module NumberSix.Handlers.Join
( handler
) where
import Control.Monad (forM_, when)
import Control.Applicative ((<$>))
import NumberSix.Irc
import NumberSix.Bang
import NumberSix.Util
handler :: UninitializedHandler
handler = makeHandler "Join" [autoJoinHook, joinHook, rejoinHook]
autoJoinHook :: Irc ()
autoJoinHook = onCommand "376" $ do
channels <- getChannels
forM_ channels $ writeMessage "JOIN" . return
joinHook :: Irc ()
joinHook = onBangCommand "!join" $ onGod $ do
(channel, _) <- breakWord <$> getBangCommandText
writeMessage "JOIN" [channel]
rejoinHook :: Irc ()
rejoinHook = onCommand "KICK" $ do
(channel : nick' : _) <- getParameters
myNick <- getNick
when (nick' ==? myNick) $ do
sleep 3
writeMessage "JOIN" [channel]
| null | https://raw.githubusercontent.com/jaspervdj/number-six/1aba681786bd85bd20f79406c681ea581b982cd6/src/NumberSix/Handlers/Join.hs | haskell | | Module to join channels
# LANGUAGE OverloadedStrings # | module NumberSix.Handlers.Join
( handler
) where
import Control.Monad (forM_, when)
import Control.Applicative ((<$>))
import NumberSix.Irc
import NumberSix.Bang
import NumberSix.Util
handler :: UninitializedHandler
handler = makeHandler "Join" [autoJoinHook, joinHook, rejoinHook]
autoJoinHook :: Irc ()
autoJoinHook = onCommand "376" $ do
channels <- getChannels
forM_ channels $ writeMessage "JOIN" . return
joinHook :: Irc ()
joinHook = onBangCommand "!join" $ onGod $ do
(channel, _) <- breakWord <$> getBangCommandText
writeMessage "JOIN" [channel]
rejoinHook :: Irc ()
rejoinHook = onCommand "KICK" $ do
(channel : nick' : _) <- getParameters
myNick <- getNick
when (nick' ==? myNick) $ do
sleep 3
writeMessage "JOIN" [channel]
|
a28b9a94d5aa92b3c2cf708a399d31d85d3fde0c5fce87727281382031808eb2 | juxt/shop | system_test.clj | Copyright © 2016 , JUXT LTD .
(ns edge.system-test
(:require
[clojure.test :refer :all :exclude [deftest]]
[integrant.core :as ig]
[edge.test.system :refer [with-system-fixture *system*]]
[schema.test :refer [deftest]]
[yada.test :refer [response-for]]))
(defn new-system
"Define a minimal system which is just enough for the tests in this
namespace to run"
[]
{})
(use-fixtures :once (with-system-fixture new-system))
(deftest system-test
(is *system*)
(is (= {} *system*)))
| null | https://raw.githubusercontent.com/juxt/shop/c23fc55bca1852bfbabb681a72debc12373c3a36/examples/main/test/edge/system_test.clj | clojure | Copyright © 2016 , JUXT LTD .
(ns edge.system-test
(:require
[clojure.test :refer :all :exclude [deftest]]
[integrant.core :as ig]
[edge.test.system :refer [with-system-fixture *system*]]
[schema.test :refer [deftest]]
[yada.test :refer [response-for]]))
(defn new-system
"Define a minimal system which is just enough for the tests in this
namespace to run"
[]
{})
(use-fixtures :once (with-system-fixture new-system))
(deftest system-test
(is *system*)
(is (= {} *system*)))
| |
ded62582b9cbf44cbaa3fd350087f1abcbfc659a91795319f30944ce964bd558 | returntocorp/semgrep | Testutil_files.ml |
Utilities for creating , scanning , and deleting a hierarchy
of test files .
Utilities for creating, scanning, and deleting a hierarchy
of test files.
*)
open Printf
let ( / ) = Fpath.( / )
let ( // ) = Fpath.( // )
type t =
| Dir of string * t list
| File of string * string
| Symlink of string * string
let get_name = function
| Dir (name, _)
| File (name, _)
| Symlink (name, _) ->
name
let rec sort xs =
Common.map sort_one xs
|> List.sort (fun a b -> String.compare (get_name a) (get_name b))
and sort_one x =
match x with
| Dir (name, xs) -> Dir (name, sort xs)
| File _
| Symlink _ ->
x
let flatten ?(root = Fpath.v ".") ?(include_dirs = false) files =
let rec flatten acc files = List.fold_left flatten_one acc files
and flatten_one (acc, dir) file =
match file with
| Dir (name, entries) ->
let path = dir / name in
let acc = if include_dirs then path :: acc else acc in
flatten (acc, path) entries
| File (name, _contents) ->
let file = dir / name in
(file :: acc, dir)
| Symlink (name, _dest) ->
let file = dir / name in
(file :: acc, dir)
in
let acc, _dir = flatten ([], root) files in
List.rev acc
remove the leading " ./ "
Common.map Fpath.normalize
let rec write root files = List.iter (write_one root) files
and write_one root file =
match file with
| Dir (name, entries) ->
let dir = root / name in
let dir_s = Fpath.to_string dir in
if not (Sys.file_exists dir_s) then Unix.mkdir dir_s 0o777;
write dir entries
| File (name, contents) ->
let path = root / name |> Fpath.to_string in
Common.write_file ~file:path contents
| Symlink (name, dest) ->
let path = root / name |> Fpath.to_string in
let dest_path = Fpath.v dest |> Fpath.to_string in
Unix.symlink dest_path path
let get_dir_entries path =
let dir = Unix.opendir (Fpath.to_string path) in
Fun.protect
~finally:(fun () -> Unix.closedir dir)
(fun () ->
let acc = ref [] in
try
while true do
acc := Unix.readdir dir :: !acc
done;
assert false
with
| End_of_file ->
List.rev !acc
|> List.filter (function
| ".."
| "." ->
false
| _ -> true))
let read root =
let rec read path =
let name = Fpath.basename path in
match (Unix.lstat (Fpath.to_string path)).st_kind with
| S_DIR ->
let names = get_dir_entries path in
Dir (name, Common.map (fun name -> read (path / name)) names)
| S_REG -> File (name, Common.read_file (Fpath.to_string path))
| S_LNK -> Symlink (name, Unix.readlink (Fpath.to_string path))
| _other ->
failwith
("Testutil_files.read: unsupported file type: " ^ Fpath.to_string path)
in
match (Unix.stat (Fpath.to_string root)).st_kind with
| S_DIR ->
let names = get_dir_entries root in
Common.map (fun name -> read (root / name)) names
| _other ->
failwith
("Testutil_files.read: root must be a directory: "
^ Fpath.to_string root)
let is_dir path =
match (Unix.lstat (Fpath.to_string path)).st_kind with
| S_DIR -> true
| _ -> false
let is_file path =
match (Unix.lstat (Fpath.to_string path)).st_kind with
| S_REG -> true
| _ -> false
let is_symlink path =
match (Unix.lstat (Fpath.to_string path)).st_kind with
| S_LNK -> true
| _ -> false
let mkdir ?(root = Sys.getcwd () |> Fpath.v) path =
if Fpath.is_rel root then
invalid_arg
(sprintf "Testutil_files.mkdir: root must be an absolute path: %s"
(Fpath.to_string root));
let rec mkdir path =
let abs_path = root // path in
let str = Fpath.to_string abs_path in
if not (Sys.file_exists str) then (
let parent = Fpath.parent path in
mkdir parent;
Unix.mkdir str 0o777)
in
let root_s = Fpath.to_string root in
if not (Sys.file_exists root_s) then
failwith ("Testutil_files.mkdir: root folder doesn't exist: " ^ root_s);
mkdir path
let with_chdir dir f =
let dir_s = Fpath.to_string dir in
let orig = Unix.getcwd () in
Fun.protect
~finally:(fun () -> Unix.chdir orig)
(fun () ->
Unix.chdir dir_s;
f ())
let init_rng = lazy (Random.self_init ())
let create_tempdir () =
let rec loop n =
if n > 10 then
failwith "Can't create a temporary test folder with a random name";
let name = sprintf "test-%x" (Random.bits ()) in
let path = Filename.concat (Filename.get_temp_dir_name ()) name in
if Sys.file_exists path then loop (n + 1)
else (
Unix.mkdir path 0o777;
Fpath.v path)
in
Lazy.force init_rng;
loop 1
let remove path =
let rec remove path =
let path_s = Fpath.to_string path in
match (Unix.lstat path_s).st_kind with
| S_DIR ->
let names = get_dir_entries path in
List.iter (fun name -> remove (path / name)) names;
Unix.rmdir path_s
| _other -> Sys.remove path_s
in
if Sys.file_exists (Fpath.to_string path) then remove path
let with_tempdir ?(persist = false) ?(chdir = false) func =
let dir = create_tempdir () in
Fun.protect
~finally:(fun () -> if not persist then remove dir)
(fun () -> if chdir then with_chdir dir (fun () -> func dir) else func dir)
let with_tempfiles ?persist ?chdir files func =
with_tempdir ?persist ?chdir (fun root ->
(* files are automatically deleted as part of the cleanup done by
'with_tempdir'. *)
write root files;
func root)
let () =
Testutil.test "Testutil_files" (fun () ->
with_tempdir ~chdir:true (fun root ->
assert (read root = []);
assert (read (Fpath.v ".") = []);
let tree =
[
File ("a", "hello");
File ("b", "yo");
Symlink ("c", "a");
Dir ("d", [ File ("e", "42"); Dir ("empty", []) ]);
]
in
write root tree;
let tree2 = read root in
assert (sort tree2 = sort tree);
let paths = flatten tree |> Common.map Fpath.to_string in
List.iter print_endline paths;
assert (paths = [ "a"; "b"; "c"; "d/e" ])))
| null | https://raw.githubusercontent.com/returntocorp/semgrep/88135d1c4affe447c98819b677160069fc4b3270/libs/commons/Testutil_files.ml | ocaml | files are automatically deleted as part of the cleanup done by
'with_tempdir'. |
Utilities for creating , scanning , and deleting a hierarchy
of test files .
Utilities for creating, scanning, and deleting a hierarchy
of test files.
*)
open Printf
let ( / ) = Fpath.( / )
let ( // ) = Fpath.( // )
type t =
| Dir of string * t list
| File of string * string
| Symlink of string * string
let get_name = function
| Dir (name, _)
| File (name, _)
| Symlink (name, _) ->
name
let rec sort xs =
Common.map sort_one xs
|> List.sort (fun a b -> String.compare (get_name a) (get_name b))
and sort_one x =
match x with
| Dir (name, xs) -> Dir (name, sort xs)
| File _
| Symlink _ ->
x
let flatten ?(root = Fpath.v ".") ?(include_dirs = false) files =
let rec flatten acc files = List.fold_left flatten_one acc files
and flatten_one (acc, dir) file =
match file with
| Dir (name, entries) ->
let path = dir / name in
let acc = if include_dirs then path :: acc else acc in
flatten (acc, path) entries
| File (name, _contents) ->
let file = dir / name in
(file :: acc, dir)
| Symlink (name, _dest) ->
let file = dir / name in
(file :: acc, dir)
in
let acc, _dir = flatten ([], root) files in
List.rev acc
remove the leading " ./ "
Common.map Fpath.normalize
let rec write root files = List.iter (write_one root) files
and write_one root file =
match file with
| Dir (name, entries) ->
let dir = root / name in
let dir_s = Fpath.to_string dir in
if not (Sys.file_exists dir_s) then Unix.mkdir dir_s 0o777;
write dir entries
| File (name, contents) ->
let path = root / name |> Fpath.to_string in
Common.write_file ~file:path contents
| Symlink (name, dest) ->
let path = root / name |> Fpath.to_string in
let dest_path = Fpath.v dest |> Fpath.to_string in
Unix.symlink dest_path path
let get_dir_entries path =
let dir = Unix.opendir (Fpath.to_string path) in
Fun.protect
~finally:(fun () -> Unix.closedir dir)
(fun () ->
let acc = ref [] in
try
while true do
acc := Unix.readdir dir :: !acc
done;
assert false
with
| End_of_file ->
List.rev !acc
|> List.filter (function
| ".."
| "." ->
false
| _ -> true))
let read root =
let rec read path =
let name = Fpath.basename path in
match (Unix.lstat (Fpath.to_string path)).st_kind with
| S_DIR ->
let names = get_dir_entries path in
Dir (name, Common.map (fun name -> read (path / name)) names)
| S_REG -> File (name, Common.read_file (Fpath.to_string path))
| S_LNK -> Symlink (name, Unix.readlink (Fpath.to_string path))
| _other ->
failwith
("Testutil_files.read: unsupported file type: " ^ Fpath.to_string path)
in
match (Unix.stat (Fpath.to_string root)).st_kind with
| S_DIR ->
let names = get_dir_entries root in
Common.map (fun name -> read (root / name)) names
| _other ->
failwith
("Testutil_files.read: root must be a directory: "
^ Fpath.to_string root)
let is_dir path =
match (Unix.lstat (Fpath.to_string path)).st_kind with
| S_DIR -> true
| _ -> false
let is_file path =
match (Unix.lstat (Fpath.to_string path)).st_kind with
| S_REG -> true
| _ -> false
let is_symlink path =
match (Unix.lstat (Fpath.to_string path)).st_kind with
| S_LNK -> true
| _ -> false
let mkdir ?(root = Sys.getcwd () |> Fpath.v) path =
if Fpath.is_rel root then
invalid_arg
(sprintf "Testutil_files.mkdir: root must be an absolute path: %s"
(Fpath.to_string root));
let rec mkdir path =
let abs_path = root // path in
let str = Fpath.to_string abs_path in
if not (Sys.file_exists str) then (
let parent = Fpath.parent path in
mkdir parent;
Unix.mkdir str 0o777)
in
let root_s = Fpath.to_string root in
if not (Sys.file_exists root_s) then
failwith ("Testutil_files.mkdir: root folder doesn't exist: " ^ root_s);
mkdir path
let with_chdir dir f =
let dir_s = Fpath.to_string dir in
let orig = Unix.getcwd () in
Fun.protect
~finally:(fun () -> Unix.chdir orig)
(fun () ->
Unix.chdir dir_s;
f ())
let init_rng = lazy (Random.self_init ())
let create_tempdir () =
let rec loop n =
if n > 10 then
failwith "Can't create a temporary test folder with a random name";
let name = sprintf "test-%x" (Random.bits ()) in
let path = Filename.concat (Filename.get_temp_dir_name ()) name in
if Sys.file_exists path then loop (n + 1)
else (
Unix.mkdir path 0o777;
Fpath.v path)
in
Lazy.force init_rng;
loop 1
let remove path =
let rec remove path =
let path_s = Fpath.to_string path in
match (Unix.lstat path_s).st_kind with
| S_DIR ->
let names = get_dir_entries path in
List.iter (fun name -> remove (path / name)) names;
Unix.rmdir path_s
| _other -> Sys.remove path_s
in
if Sys.file_exists (Fpath.to_string path) then remove path
let with_tempdir ?(persist = false) ?(chdir = false) func =
let dir = create_tempdir () in
Fun.protect
~finally:(fun () -> if not persist then remove dir)
(fun () -> if chdir then with_chdir dir (fun () -> func dir) else func dir)
let with_tempfiles ?persist ?chdir files func =
with_tempdir ?persist ?chdir (fun root ->
write root files;
func root)
let () =
Testutil.test "Testutil_files" (fun () ->
with_tempdir ~chdir:true (fun root ->
assert (read root = []);
assert (read (Fpath.v ".") = []);
let tree =
[
File ("a", "hello");
File ("b", "yo");
Symlink ("c", "a");
Dir ("d", [ File ("e", "42"); Dir ("empty", []) ]);
]
in
write root tree;
let tree2 = read root in
assert (sort tree2 = sort tree);
let paths = flatten tree |> Common.map Fpath.to_string in
List.iter print_endline paths;
assert (paths = [ "a"; "b"; "c"; "d/e" ])))
|
d239f44cd4b37e2b56dbb4dfbc3bb478ebc52833ec0b6d8d365b09f4dff462ab | cac-t-u-s/om-sharp | lisptools.lisp | ;============================================================================
; om#: visual programming language for computer-assisted music composition
;============================================================================
;
; This program is free software. For information on usage
; and redistribution, see the "LICENSE" file in this distribution.
;
; 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.
;
;============================================================================
File author :
;============================================================================
;;;==========================
Misc . Lisp Tools for OM
;;;==========================
(in-package :om)
(defconstant *positive-infinity* most-positive-fixnum)
(defconstant *negative-infinity* most-negative-fixnum)
;;;===========================
;;; LISTS
;;;===========================
(defun list! (thing) (if (listp thing) thing (list thing)))
(defun list+ (&rest lists) (apply 'concatenate (append (list 'list) lists)))
(defun first? (thing) (if (listp thing) (first thing) thing))
(defun max? (a b) (if a (if b (max a b) a) b))
(defun min? (a b) (if a (if b (min a b) a) b))
(defun firstn (list n )
(cond
((< (length list) n) list )
(t (butlast list (- (length list) n)))))
(defun replace-in-list (list elem pos)
(let* ((first-list (subseq list 0 pos))
(second-list (subseq list (+ pos 1))))
(append first-list (list elem) second-list)))
(defun insert-in-list (list elem pos)
(if (> pos (- (length list) 1))
(append list (list elem))
(append (subseq list 0 pos)
(list elem)
(subseq list pos))))
(defun erase-n (list pos)
(loop for item in list
for i = 0 then (+ i 1)
when (not (= i pos)) collect item))
;; pos = a list of indices
(defun erase-nn (list pos)
(loop for item in list
for i = 0 then (+ i 1)
when (not (member i pos)) collect item))
(defun list-typep (list typeList)
"Checks if every elt in 'list' belongs to one of the types in 'typelist'"
(every #'(lambda (elt) (some #'(lambda (type) (equal (type-of elt) type)) (list! typelist))) list))
(defun list-subtypep (list typeList)
"Checks if every elt in 'list' belongs to one of the subtypes in 'typelist'"
(every #'(lambda (elt) (some #'(lambda (type) (subtypep (type-of elt) type)) (list! typelist))) list))
(defun next-in-list (list item &optional (circular t))
(let* ((pos (position item list)))
(if circular
(let ((newpos (if pos (mod (1+ pos) (length list)) 0)))
(nth newpos list))
(when pos
(nth (1+ pos) list))
)))
(defun previous-in-list (list item &optional (circular t))
(let* ((pos (position item list)))
(if circular
(let ((newpos (if pos (mod (1- pos) (length list)) 0)))
(nth newpos list))
(when (and pos (> pos 0))
(nth (1- pos) list))
)))
(defmacro %car (x)
`(car (the cons ,x)))
(defmacro %cdr (x)
`(cdr (the cons ,x)))
(defmacro %cadr (x)
`(cadr (the cons ,x)))
(defun quoted-form-p (form)
(and (consp form)
(eq (%car form) 'quote)
(consp (%cdr form))
(null (%cdr (%cdr form)))))
(defun lambda-expression-p (form)
(and (consp form)
(eq (%car form) 'lambda)
(consp (%cdr form))
(listp (%cadr form))))
;push item in place but in the last position
(defmacro pushr (item place)
`(if ,place
(setf (cdr (last ,place)) (cons ,item nil))
(setf ,place (list ,item))))
(defmacro insert-in-order (object list &key (key #'identity) (test '<))
`(let ((p (position (funcall ,key ,object) ,list :test ',test :key ,key)))
(if (not p)
(nconc ,list (list ,object))
(if (= p 0)
(push ,object ,list)
(push ,object (nthcdr p ,list))))
,list))
(defmacro filter-list (list from to &key (key #'identity))
`(remove-if #'(lambda (element)
(or (< (funcall ,key element) ,from)
(>= (funcall ,key element) ,to)))
,list))
(defun in-interval (n interval &key exclude-low-bound exclude-high-bound)
(and (funcall (if exclude-low-bound '> '>=) n (car interval))
(funcall (if exclude-high-bound '< '<=) n (cadr interval))))
(defun closest-match (value list &key (key #'identity))
(let ((rep (car list))
(min (abs (- value (funcall key (car list))))))
(loop for elt in (cdr list)
do
(let ((diff (abs (- value (funcall key elt)))))
(when (< diff min)
(setf min diff
rep elt))))
rep))
;=================
;safe random
(defun om-random-value (num)
(if (= num 0) 0
(if (< num 0)
(- (random (- num)))
(random num))))
;;;==============================
;;; HASH-TABLES
;;;==============================
(defmethod hash-keys ((h hash-table))
(loop for key being the hash-keys of h collect key))
(defmethod hash-items ((h hash-table))
(loop for key in (hash-keys h) collect (gethash key h)))
;;;==============================
;;; PROPERTIES / KEY-VALUE LISTS
;;;==============================
' (: key1 : val1 : key2 : val2 ... )
(defun find-value-in-arg-list (list key)
(let ((pos (position key list :test 'equal)))
(and pos (nth (1+ pos) list))))
;;; => GETF
(defun set-value-in-arg-list (list key value)
(let ((pos (position key list :test 'equal)))
(if pos
(setf (nth (1+ pos) list) value)
(setf list (append list (list key value))))
))
' ( (: key1 : val1 ) (: key2 : val2 ) ... )
(defun find-value-in-kv-list (list key)
(cadr (find key list :test 'equal :key 'car)))
(defun set-value-in-kv-list (list key value)
(if list
(let ((kv (find key list :test 'equal :key 'car)))
(if kv (setf (cadr kv) value)
(push (list key value) list))
list)
(list (list key value))))
' ( (: key1 prop1 prop2 prop3 ... ) (: prop3 ... ) ... )
(defun find-values-in-prop-list (list key)
(remove nil ;;; ?
(cdr (find key list :test 'equal :key 'car))
))
;=======================
; types
;=======================
(defun ensure-type (object type)
(and (subtypep (type-of object) type) object))
;=======================
; FUNCTIONS / LAMBDA LIST PARSING
;=======================
(defun function-arg-list (fun)
(remove-if #'(lambda (item) (member item lambda-list-keywords :test 'equal)) (function-arglist fun)))
(defun function-main-args (fun)
(loop for item in (function-arglist fun)
while (not (member item lambda-list-keywords :test 'equal))
collect item))
(defun function-n-args (fun)
(length (function-main-args fun)))
(defun function-optional-args (fun)
(let ((al (function-arglist fun)))
(when (find '&optional al)
(subseq al (1+ (position '&optional al))
(position (remove '&optional lambda-list-keywords) al :test #'(lambda (a b) (find b a)))))))
(defun function-keyword-args (fun)
(let ((al (function-arglist fun)))
(when (find '&key al)
(subseq al (1+ (position '&key al))
(position (remove '&key lambda-list-keywords) al :test #'(lambda (a b) (find b a)))))))
(defun get-keywords-fun (fun)
(let ((args (function-arglist fun))
rep)
(loop while (and args (not rep)) do
(when (equal (pop args) '&key)
(setf rep t)))
(setf rep nil)
(loop for item in args
while (not (member item lambda-list-keywords :test 'equal)) do
(push (if (listp item) (car item) item) rep))
(reverse rep)))
(defun get-optional-fun (fun)
(let ((args (function-arglist fun))
rep)
(loop while (and args (not rep)) do
(when (equal (pop args) '&optional)
(setf rep t)))
(setf rep nil)
(loop for item in args
while (not (member item lambda-list-keywords :test 'equal)) do
(push (if (listp item) (car item) item) rep))
(reverse rep)))
(defun valued-val (val)
(if (or (symbolp val)
(and (consp val)
(or (not (symbolp (car val)))
(not (fboundp (car val))))))
val
(eval val)))
;=======================
; POSITION
;=======================
(defun interval-intersec (int1 int2)
(when (and int2 int1)
(let ((x1 (max (car int1) (car int2)))
(x2 (min (cadr int1) (cadr int2))))
(if (<= x1 x2)
(list x1 x2)))))
;; each rect = (left top right bottom)
(defun rect-intersec (rect1 rect2)
(let* ((tx (max (first rect1) (first rect2)))
(ty (max (second rect1) (second rect2)))
(t2x (min (third rect1) (third rect2)))
(t2y (min (fourth rect1) (fourth rect2))))
(if (or (< t2x tx) (< t2y ty))
nil
(list tx ty t2x t2y))))
(defun point-in-interval-p (point interval)
(and (<= point (second interval))
(>= point (first interval))))
(defun point-in-rectangle-p (point left top right bottom)
(let ((x (om-point-x point))
(y (om-point-y point)))
(and (>= x left) (<= x right)
(>= y top) (<= y bottom))))
;=======================
; MATH
;=======================
(defun 2+ (x) (+ x 2))
(defun 2- (x) (- x 2))
(defun space-ranges (range &optional (factor 0.05) (min 1))
(list (- (first range) (max min (abs (* (- (second range) (first range)) factor))))
(+ (second range) (max min (abs (* (- (second range) (first range)) factor))))
(- (third range) (max min (abs (* (- (fourth range) (third range)) factor))))
(+ (fourth range) (max min (abs (* (- (fourth range) (third range)) factor))))))
(defun average (xs weights?)
(let ((num 0) (den 0) ampl)
(loop while xs do
(setq ampl (or (if (consp weights?) (pop weights?) 1) 1))
(incf num (* ampl (pop xs)))
(incf den ampl))
(/ num den)))
finds the closest multiple of n and 2 that is greater than val
(defun next-double-of-n (val n)
(let ((rep n))
(loop while (> val rep) do
(setf rep (* rep 2)))
rep))
(defun power-of-two-p (n)
(or (= n 1) (= n 2)
(and (zerop (mod n 2))
(power-of-two-p (/ n 2)))))
| null | https://raw.githubusercontent.com/cac-t-u-s/om-sharp/74aa97891177de1d167aa5963be00f0d453a3bcd/src/visual-language/utils/lisptools.lisp | lisp | ============================================================================
om#: visual programming language for computer-assisted music composition
============================================================================
This program is free software. For information on usage
and redistribution, see the "LICENSE" file in this distribution.
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.
============================================================================
============================================================================
==========================
==========================
===========================
LISTS
===========================
pos = a list of indices
push item in place but in the last position
=================
safe random
==============================
HASH-TABLES
==============================
==============================
PROPERTIES / KEY-VALUE LISTS
==============================
=> GETF
?
=======================
types
=======================
=======================
FUNCTIONS / LAMBDA LIST PARSING
=======================
=======================
POSITION
=======================
each rect = (left top right bottom)
=======================
MATH
======================= | File author :
Misc . Lisp Tools for OM
(in-package :om)
(defconstant *positive-infinity* most-positive-fixnum)
(defconstant *negative-infinity* most-negative-fixnum)
(defun list! (thing) (if (listp thing) thing (list thing)))
(defun list+ (&rest lists) (apply 'concatenate (append (list 'list) lists)))
(defun first? (thing) (if (listp thing) (first thing) thing))
(defun max? (a b) (if a (if b (max a b) a) b))
(defun min? (a b) (if a (if b (min a b) a) b))
(defun firstn (list n )
(cond
((< (length list) n) list )
(t (butlast list (- (length list) n)))))
(defun replace-in-list (list elem pos)
(let* ((first-list (subseq list 0 pos))
(second-list (subseq list (+ pos 1))))
(append first-list (list elem) second-list)))
(defun insert-in-list (list elem pos)
(if (> pos (- (length list) 1))
(append list (list elem))
(append (subseq list 0 pos)
(list elem)
(subseq list pos))))
(defun erase-n (list pos)
(loop for item in list
for i = 0 then (+ i 1)
when (not (= i pos)) collect item))
(defun erase-nn (list pos)
(loop for item in list
for i = 0 then (+ i 1)
when (not (member i pos)) collect item))
(defun list-typep (list typeList)
"Checks if every elt in 'list' belongs to one of the types in 'typelist'"
(every #'(lambda (elt) (some #'(lambda (type) (equal (type-of elt) type)) (list! typelist))) list))
(defun list-subtypep (list typeList)
"Checks if every elt in 'list' belongs to one of the subtypes in 'typelist'"
(every #'(lambda (elt) (some #'(lambda (type) (subtypep (type-of elt) type)) (list! typelist))) list))
(defun next-in-list (list item &optional (circular t))
(let* ((pos (position item list)))
(if circular
(let ((newpos (if pos (mod (1+ pos) (length list)) 0)))
(nth newpos list))
(when pos
(nth (1+ pos) list))
)))
(defun previous-in-list (list item &optional (circular t))
(let* ((pos (position item list)))
(if circular
(let ((newpos (if pos (mod (1- pos) (length list)) 0)))
(nth newpos list))
(when (and pos (> pos 0))
(nth (1- pos) list))
)))
(defmacro %car (x)
`(car (the cons ,x)))
(defmacro %cdr (x)
`(cdr (the cons ,x)))
(defmacro %cadr (x)
`(cadr (the cons ,x)))
(defun quoted-form-p (form)
(and (consp form)
(eq (%car form) 'quote)
(consp (%cdr form))
(null (%cdr (%cdr form)))))
(defun lambda-expression-p (form)
(and (consp form)
(eq (%car form) 'lambda)
(consp (%cdr form))
(listp (%cadr form))))
(defmacro pushr (item place)
`(if ,place
(setf (cdr (last ,place)) (cons ,item nil))
(setf ,place (list ,item))))
(defmacro insert-in-order (object list &key (key #'identity) (test '<))
`(let ((p (position (funcall ,key ,object) ,list :test ',test :key ,key)))
(if (not p)
(nconc ,list (list ,object))
(if (= p 0)
(push ,object ,list)
(push ,object (nthcdr p ,list))))
,list))
(defmacro filter-list (list from to &key (key #'identity))
`(remove-if #'(lambda (element)
(or (< (funcall ,key element) ,from)
(>= (funcall ,key element) ,to)))
,list))
(defun in-interval (n interval &key exclude-low-bound exclude-high-bound)
(and (funcall (if exclude-low-bound '> '>=) n (car interval))
(funcall (if exclude-high-bound '< '<=) n (cadr interval))))
(defun closest-match (value list &key (key #'identity))
(let ((rep (car list))
(min (abs (- value (funcall key (car list))))))
(loop for elt in (cdr list)
do
(let ((diff (abs (- value (funcall key elt)))))
(when (< diff min)
(setf min diff
rep elt))))
rep))
(defun om-random-value (num)
(if (= num 0) 0
(if (< num 0)
(- (random (- num)))
(random num))))
(defmethod hash-keys ((h hash-table))
(loop for key being the hash-keys of h collect key))
(defmethod hash-items ((h hash-table))
(loop for key in (hash-keys h) collect (gethash key h)))
' (: key1 : val1 : key2 : val2 ... )
(defun find-value-in-arg-list (list key)
(let ((pos (position key list :test 'equal)))
(and pos (nth (1+ pos) list))))
(defun set-value-in-arg-list (list key value)
(let ((pos (position key list :test 'equal)))
(if pos
(setf (nth (1+ pos) list) value)
(setf list (append list (list key value))))
))
' ( (: key1 : val1 ) (: key2 : val2 ) ... )
(defun find-value-in-kv-list (list key)
(cadr (find key list :test 'equal :key 'car)))
(defun set-value-in-kv-list (list key value)
(if list
(let ((kv (find key list :test 'equal :key 'car)))
(if kv (setf (cadr kv) value)
(push (list key value) list))
list)
(list (list key value))))
' ( (: key1 prop1 prop2 prop3 ... ) (: prop3 ... ) ... )
(defun find-values-in-prop-list (list key)
(cdr (find key list :test 'equal :key 'car))
))
(defun ensure-type (object type)
(and (subtypep (type-of object) type) object))
(defun function-arg-list (fun)
(remove-if #'(lambda (item) (member item lambda-list-keywords :test 'equal)) (function-arglist fun)))
(defun function-main-args (fun)
(loop for item in (function-arglist fun)
while (not (member item lambda-list-keywords :test 'equal))
collect item))
(defun function-n-args (fun)
(length (function-main-args fun)))
(defun function-optional-args (fun)
(let ((al (function-arglist fun)))
(when (find '&optional al)
(subseq al (1+ (position '&optional al))
(position (remove '&optional lambda-list-keywords) al :test #'(lambda (a b) (find b a)))))))
(defun function-keyword-args (fun)
(let ((al (function-arglist fun)))
(when (find '&key al)
(subseq al (1+ (position '&key al))
(position (remove '&key lambda-list-keywords) al :test #'(lambda (a b) (find b a)))))))
(defun get-keywords-fun (fun)
(let ((args (function-arglist fun))
rep)
(loop while (and args (not rep)) do
(when (equal (pop args) '&key)
(setf rep t)))
(setf rep nil)
(loop for item in args
while (not (member item lambda-list-keywords :test 'equal)) do
(push (if (listp item) (car item) item) rep))
(reverse rep)))
(defun get-optional-fun (fun)
(let ((args (function-arglist fun))
rep)
(loop while (and args (not rep)) do
(when (equal (pop args) '&optional)
(setf rep t)))
(setf rep nil)
(loop for item in args
while (not (member item lambda-list-keywords :test 'equal)) do
(push (if (listp item) (car item) item) rep))
(reverse rep)))
(defun valued-val (val)
(if (or (symbolp val)
(and (consp val)
(or (not (symbolp (car val)))
(not (fboundp (car val))))))
val
(eval val)))
(defun interval-intersec (int1 int2)
(when (and int2 int1)
(let ((x1 (max (car int1) (car int2)))
(x2 (min (cadr int1) (cadr int2))))
(if (<= x1 x2)
(list x1 x2)))))
(defun rect-intersec (rect1 rect2)
(let* ((tx (max (first rect1) (first rect2)))
(ty (max (second rect1) (second rect2)))
(t2x (min (third rect1) (third rect2)))
(t2y (min (fourth rect1) (fourth rect2))))
(if (or (< t2x tx) (< t2y ty))
nil
(list tx ty t2x t2y))))
(defun point-in-interval-p (point interval)
(and (<= point (second interval))
(>= point (first interval))))
(defun point-in-rectangle-p (point left top right bottom)
(let ((x (om-point-x point))
(y (om-point-y point)))
(and (>= x left) (<= x right)
(>= y top) (<= y bottom))))
(defun 2+ (x) (+ x 2))
(defun 2- (x) (- x 2))
(defun space-ranges (range &optional (factor 0.05) (min 1))
(list (- (first range) (max min (abs (* (- (second range) (first range)) factor))))
(+ (second range) (max min (abs (* (- (second range) (first range)) factor))))
(- (third range) (max min (abs (* (- (fourth range) (third range)) factor))))
(+ (fourth range) (max min (abs (* (- (fourth range) (third range)) factor))))))
(defun average (xs weights?)
(let ((num 0) (den 0) ampl)
(loop while xs do
(setq ampl (or (if (consp weights?) (pop weights?) 1) 1))
(incf num (* ampl (pop xs)))
(incf den ampl))
(/ num den)))
finds the closest multiple of n and 2 that is greater than val
(defun next-double-of-n (val n)
(let ((rep n))
(loop while (> val rep) do
(setf rep (* rep 2)))
rep))
(defun power-of-two-p (n)
(or (= n 1) (= n 2)
(and (zerop (mod n 2))
(power-of-two-p (/ n 2)))))
|
ff4402c60da54d83218ae3fd4505583cf00010035d0204d97fab625fe04c2d58 | crategus/cl-cffi-gtk | rtest-gtk-notebook.lisp | (def-suite gtk-notebook :in gtk-suite)
(in-suite gtk-notebook)
;;; --- Types and Values -------------------------------------------------------
;;; GtkNotebook
(test gtk-notebook-class
;; Type check
(is (g-type-is-object "GtkNotebook"))
;; Check the registered name
(is (eq 'gtk-notebook
(registered-object-type-by-name "GtkNotebook")))
;; Check the type initializer
(is (eq (gtype "GtkNotebook")
(gtype (foreign-funcall "gtk_notebook_get_type" g-size))))
;; Check the parent
(is (eq (gtype "GtkContainer") (g-type-parent "GtkNotebook")))
;; Check the children
(is (equal '()
(mapcar #'g-type-name (g-type-children "GtkNotebook"))))
;; Check the interfaces
(is (equal '("AtkImplementorIface" "GtkBuildable")
(mapcar #'g-type-name (g-type-interfaces "GtkNotebook"))))
;; Check the class properties
(is (equal '("enable-popup" "group-name" "page" "scrollable" "show-border"
"show-tabs" "tab-pos")
(list-class-property-names "GtkNotebook")))
;; Get the names of the style properties.
(is (equal '("arrow-spacing" "has-backward-stepper" "has-forward-stepper"
"has-secondary-backward-stepper" "has-secondary-forward-stepper"
"has-tab-gap" "initial-gap" "tab-curvature" "tab-overlap")
(list-class-style-property-names "GtkNotebook")))
;; Get the names of the child properties
(is (equal '("detachable" "menu-label" "position" "reorderable" "tab-expand"
"tab-fill" "tab-label")
(list-class-child-property-names "GtkNotebook")))
;; Check the class definition
(is (equal '(DEFINE-G-OBJECT-CLASS "GtkNotebook" GTK-NOTEBOOK
(:SUPERCLASS GTK-CONTAINER :EXPORT T :INTERFACES
("AtkImplementorIface" "GtkBuildable")
:TYPE-INITIALIZER "gtk_notebook_get_type")
((ENABLE-POPUP GTK-NOTEBOOK-ENABLE-POPUP "enable-popup"
"gboolean" T T)
(GROUP-NAME GTK-NOTEBOOK-GROUP-NAME "group-name"
"gchararray" T T)
(PAGE GTK-NOTEBOOK-PAGE "page" "gint" T T)
(SCROLLABLE GTK-NOTEBOOK-SCROLLABLE "scrollable"
"gboolean" T T)
(SHOW-BORDER GTK-NOTEBOOK-SHOW-BORDER "show-border"
"gboolean" T T)
(SHOW-TABS GTK-NOTEBOOK-SHOW-TABS "show-tabs"
"gboolean" T T)
(TAB-POS GTK-NOTEBOOK-TAB-POS "tab-pos"
"GtkPositionType" T T)))
(get-g-type-definition "GtkNotebook"))))
;;; --- Properties -------------------------------------------------------------
(test gtk-notebook-properties
(let ((notebook (make-instance 'gtk-notebook)))
(is-false (gtk-notebook-enable-popup notebook))
(is-false (gtk-notebook-group-name notebook))
(is (= -1 (gtk-notebook-page notebook)))
(is-false (gtk-notebook-scrollable notebook))
(is-true (gtk-notebook-show-border notebook))
(is-true (gtk-notebook-show-tabs notebook))
(is (eq :top (gtk-notebook-tab-pos notebook)))))
;;; --- Child Properties -------------------------------------------------------
(test gtk-notebook-child-properties
(let ((notebook (make-instance 'gtk-notebook))
(child (make-instance 'gtk-frame))
(label (make-instance 'gtk-label :label "label")))
(is (= 0 (gtk-notebook-append-page notebook child label)))
(is-false (gtk-notebook-child-detachable notebook child))
(is-false (gtk-notebook-child-menu-label notebook child))
(is (= 0 (gtk-notebook-child-position notebook child)))
(is-false (gtk-notebook-child-reorderable notebook child))
(is-false (gtk-notebook-child-tab-expand notebook child))
(is-true (gtk-notebook-child-tab-fill notebook child))
(is (string= "label" (gtk-notebook-child-tab-label notebook child)))))
;;; --- Style Properties -------------------------------------------------------
(test gtk-notebook-style-properties
(let ((notebook (make-instance 'gtk-notebook)))
(is (= 0 (gtk-widget-style-property notebook "arrow-spacing")))
(is-true (gtk-widget-style-property notebook "has-backward-stepper"))
(is-true (gtk-widget-style-property notebook "has-forward-stepper"))
(is-false (gtk-widget-style-property notebook "has-secondary-backward-stepper"))
(is-false (gtk-widget-style-property notebook "has-secondary-forward-stepper"))
(is-true (gtk-widget-style-property notebook "has-tab-gap"))
(is (= 0 (gtk-widget-style-property notebook "initial-gap")))
(is (= 1 (gtk-widget-style-property notebook "tab-curvature")))
(is (= 2 (gtk-widget-style-property notebook "tab-overlap")))))
;;; --- Functions --------------------------------------------------------------
;;; gtk_notebook_new
(test gtk-notebook-new
(is (eq 'gtk-notebook (type-of (gtk-notebook-new)))))
;;; gtk_notebook_append_page
;;; gtk_notebook_append_page_menu
gtk_notebook_prepend_page
;;; gtk_notebook_prepend_page_menu
gtk_notebook_insert_page
;;; gtk_notebook_insert_page_menu
;;; gtk_notebook_remove_page
(test gtk-notebook-add-page.1
(let ((notebook (make-instance 'gtk-notebook))
(page1 (make-instance 'gtk-frame))
(page2 (make-instance 'gtk-frame))
(page3 (make-instance 'gtk-frame))
(page4 (make-instance 'gtk-frame))
(page5 (make-instance 'gtk-frame))
(page6 (make-instance 'gtk-frame))
(label1 (make-instance 'gtk-label :label "label1"))
(label2 (make-instance 'gtk-label :label "label2"))
(label3 (make-instance 'gtk-label :label "label3")))
(is (= 0 (gtk-notebook-append-page notebook page1 nil)))
(is (= 1 (gtk-notebook-append-page notebook page2 label1)))
(is (= 0 (gtk-notebook-prepend-page notebook page3 nil)))
(is (= 0 (gtk-notebook-prepend-page notebook page4 label2)))
(is (= 3 (gtk-notebook-insert-page notebook page5 nil 3)))
(is (= 3 (gtk-notebook-insert-page notebook page6 label3 3)))
(is (= 6 (length (gtk-container-children notebook))))
(is-false (gtk-notebook-remove-page notebook 0))
(is (= 5 (length (gtk-container-children notebook))))
(is-false (gtk-notebook-remove-page notebook page6))
(is (= 4 (length (gtk-container-children notebook))))
))
(test gtk-notebook-add-page.2
(let ((notebook (make-instance 'gtk-notebook))
(page1 (make-instance 'gtk-frame))
(page2 (make-instance 'gtk-frame))
(page3 (make-instance 'gtk-frame))
(label1 (make-instance 'gtk-label :label "label1"))
(label2 (make-instance 'gtk-label :label "label2"))
(label3 (make-instance 'gtk-label :label "label3"))
(menu-label1 (make-instance 'gtk-label :label "menu-label1"))
(menu-label2 (make-instance 'gtk-label :label "menu-label2"))
(menu-label3 (make-instance 'gtk-label :label "menu-label3")))
(is (= 0 (gtk-notebook-append-page-menu notebook page1 label1 menu-label1)))
(is (= 0 (gtk-notebook-prepend-page-menu notebook page2 label2 menu-label2)))
(is (= 1 (gtk-notebook-insert-page-menu notebook page3 label3 menu-label3 1)))
))
(test gtk-notebook-add-page.3
(let ((notebook (make-instance 'gtk-notebook))
(page1 (make-instance 'gtk-frame))
(page2 (make-instance 'gtk-frame))
(page3 (make-instance 'gtk-frame))
(page4 (make-instance 'gtk-frame))
(page5 (make-instance 'gtk-frame))
(page6 (make-instance 'gtk-frame))
(label1 (make-instance 'gtk-label :label "label1"))
(label2 (make-instance 'gtk-label :label "label2"))
(label3 (make-instance 'gtk-label :label "label3"))
(label4 (make-instance 'gtk-label :label "label4"))
(label5 (make-instance 'gtk-label :label "label5"))
(label6 (make-instance 'gtk-label :label "label6"))
(menu-label1 (make-instance 'gtk-label :label "menu-label1"))
(menu-label2 (make-instance 'gtk-label :label "menu-label2"))
(menu-label3 (make-instance 'gtk-label :label "menu-label3")))
(is (= 0 (gtk-notebook-add-page notebook page1 label1)))
(is (= 0 (gtk-notebook-add-page notebook page2 label2 :position :start)))
(is (= 1 (gtk-notebook-add-page notebook page3 label3 :position 1)))
(is (= 3 (gtk-notebook-add-page notebook page4 label4 :menu menu-label1)))
(is (= 0 (gtk-notebook-add-page notebook page5 label5 :position :start
:menu menu-label2)))
(is (= 1 (gtk-notebook-add-page notebook page6 label6 :position 1
:menu menu-label3)))))
;;; gtk_notebook_detach_tab
;;; gtk_notebook_page_num
;;; gtk_notebook_next_page
;;; gtk_notebook_prev_page
;;; gtk_notebook_reorder_child
;;; gtk_notebook_popup_enable
;;; gtk_notebook_popup_disable
;;; gtk_notebook_get_current_page
;;; gtk_notebook_get_menu_label
;;; gtk_notebook_get_nth_page
;;; gtk_notebook_get_n_pages
;;; gtk_notebook_get_tab_label
;;; gtk_notebook_set_menu_label
gtk_notebook_set_menu_label_text
;;; gtk_notebook_set_tab_label
;;; gtk_notebook_set_tab_label_text
;;; gtk_notebook_set_tab_reorderable
;;; gtk_notebook_set_tab_detachable
;;; gtk_notebook_get_menu_label_text
gtk_notebook_get_tab_label_text
;;; gtk_notebook_get_tab_reorderable
;;; gtk_notebook_get_tab_detachable
gtk_notebook_get_tab_hborder deprecated
;;; gtk_notebook_get_tab_vborder deprecated
;;; gtk_notebook_set_current_page
;;; gtk_notebook_set_action_widget
;;; gtk_notebook_get_action_widget
2021 - 10 - 19
| null | https://raw.githubusercontent.com/crategus/cl-cffi-gtk/ba198f7d29cb06de1e8965e1b8a78522d5430516/test/rtest-gtk-notebook.lisp | lisp | --- Types and Values -------------------------------------------------------
GtkNotebook
Type check
Check the registered name
Check the type initializer
Check the parent
Check the children
Check the interfaces
Check the class properties
Get the names of the style properties.
Get the names of the child properties
Check the class definition
--- Properties -------------------------------------------------------------
--- Child Properties -------------------------------------------------------
--- Style Properties -------------------------------------------------------
--- Functions --------------------------------------------------------------
gtk_notebook_new
gtk_notebook_append_page
gtk_notebook_append_page_menu
gtk_notebook_prepend_page_menu
gtk_notebook_insert_page_menu
gtk_notebook_remove_page
gtk_notebook_detach_tab
gtk_notebook_page_num
gtk_notebook_next_page
gtk_notebook_prev_page
gtk_notebook_reorder_child
gtk_notebook_popup_enable
gtk_notebook_popup_disable
gtk_notebook_get_current_page
gtk_notebook_get_menu_label
gtk_notebook_get_nth_page
gtk_notebook_get_n_pages
gtk_notebook_get_tab_label
gtk_notebook_set_menu_label
gtk_notebook_set_tab_label
gtk_notebook_set_tab_label_text
gtk_notebook_set_tab_reorderable
gtk_notebook_set_tab_detachable
gtk_notebook_get_menu_label_text
gtk_notebook_get_tab_reorderable
gtk_notebook_get_tab_detachable
gtk_notebook_get_tab_vborder deprecated
gtk_notebook_set_current_page
gtk_notebook_set_action_widget
gtk_notebook_get_action_widget | (def-suite gtk-notebook :in gtk-suite)
(in-suite gtk-notebook)
(test gtk-notebook-class
(is (g-type-is-object "GtkNotebook"))
(is (eq 'gtk-notebook
(registered-object-type-by-name "GtkNotebook")))
(is (eq (gtype "GtkNotebook")
(gtype (foreign-funcall "gtk_notebook_get_type" g-size))))
(is (eq (gtype "GtkContainer") (g-type-parent "GtkNotebook")))
(is (equal '()
(mapcar #'g-type-name (g-type-children "GtkNotebook"))))
(is (equal '("AtkImplementorIface" "GtkBuildable")
(mapcar #'g-type-name (g-type-interfaces "GtkNotebook"))))
(is (equal '("enable-popup" "group-name" "page" "scrollable" "show-border"
"show-tabs" "tab-pos")
(list-class-property-names "GtkNotebook")))
(is (equal '("arrow-spacing" "has-backward-stepper" "has-forward-stepper"
"has-secondary-backward-stepper" "has-secondary-forward-stepper"
"has-tab-gap" "initial-gap" "tab-curvature" "tab-overlap")
(list-class-style-property-names "GtkNotebook")))
(is (equal '("detachable" "menu-label" "position" "reorderable" "tab-expand"
"tab-fill" "tab-label")
(list-class-child-property-names "GtkNotebook")))
(is (equal '(DEFINE-G-OBJECT-CLASS "GtkNotebook" GTK-NOTEBOOK
(:SUPERCLASS GTK-CONTAINER :EXPORT T :INTERFACES
("AtkImplementorIface" "GtkBuildable")
:TYPE-INITIALIZER "gtk_notebook_get_type")
((ENABLE-POPUP GTK-NOTEBOOK-ENABLE-POPUP "enable-popup"
"gboolean" T T)
(GROUP-NAME GTK-NOTEBOOK-GROUP-NAME "group-name"
"gchararray" T T)
(PAGE GTK-NOTEBOOK-PAGE "page" "gint" T T)
(SCROLLABLE GTK-NOTEBOOK-SCROLLABLE "scrollable"
"gboolean" T T)
(SHOW-BORDER GTK-NOTEBOOK-SHOW-BORDER "show-border"
"gboolean" T T)
(SHOW-TABS GTK-NOTEBOOK-SHOW-TABS "show-tabs"
"gboolean" T T)
(TAB-POS GTK-NOTEBOOK-TAB-POS "tab-pos"
"GtkPositionType" T T)))
(get-g-type-definition "GtkNotebook"))))
(test gtk-notebook-properties
(let ((notebook (make-instance 'gtk-notebook)))
(is-false (gtk-notebook-enable-popup notebook))
(is-false (gtk-notebook-group-name notebook))
(is (= -1 (gtk-notebook-page notebook)))
(is-false (gtk-notebook-scrollable notebook))
(is-true (gtk-notebook-show-border notebook))
(is-true (gtk-notebook-show-tabs notebook))
(is (eq :top (gtk-notebook-tab-pos notebook)))))
(test gtk-notebook-child-properties
(let ((notebook (make-instance 'gtk-notebook))
(child (make-instance 'gtk-frame))
(label (make-instance 'gtk-label :label "label")))
(is (= 0 (gtk-notebook-append-page notebook child label)))
(is-false (gtk-notebook-child-detachable notebook child))
(is-false (gtk-notebook-child-menu-label notebook child))
(is (= 0 (gtk-notebook-child-position notebook child)))
(is-false (gtk-notebook-child-reorderable notebook child))
(is-false (gtk-notebook-child-tab-expand notebook child))
(is-true (gtk-notebook-child-tab-fill notebook child))
(is (string= "label" (gtk-notebook-child-tab-label notebook child)))))
(test gtk-notebook-style-properties
(let ((notebook (make-instance 'gtk-notebook)))
(is (= 0 (gtk-widget-style-property notebook "arrow-spacing")))
(is-true (gtk-widget-style-property notebook "has-backward-stepper"))
(is-true (gtk-widget-style-property notebook "has-forward-stepper"))
(is-false (gtk-widget-style-property notebook "has-secondary-backward-stepper"))
(is-false (gtk-widget-style-property notebook "has-secondary-forward-stepper"))
(is-true (gtk-widget-style-property notebook "has-tab-gap"))
(is (= 0 (gtk-widget-style-property notebook "initial-gap")))
(is (= 1 (gtk-widget-style-property notebook "tab-curvature")))
(is (= 2 (gtk-widget-style-property notebook "tab-overlap")))))
(test gtk-notebook-new
(is (eq 'gtk-notebook (type-of (gtk-notebook-new)))))
gtk_notebook_prepend_page
gtk_notebook_insert_page
(test gtk-notebook-add-page.1
(let ((notebook (make-instance 'gtk-notebook))
(page1 (make-instance 'gtk-frame))
(page2 (make-instance 'gtk-frame))
(page3 (make-instance 'gtk-frame))
(page4 (make-instance 'gtk-frame))
(page5 (make-instance 'gtk-frame))
(page6 (make-instance 'gtk-frame))
(label1 (make-instance 'gtk-label :label "label1"))
(label2 (make-instance 'gtk-label :label "label2"))
(label3 (make-instance 'gtk-label :label "label3")))
(is (= 0 (gtk-notebook-append-page notebook page1 nil)))
(is (= 1 (gtk-notebook-append-page notebook page2 label1)))
(is (= 0 (gtk-notebook-prepend-page notebook page3 nil)))
(is (= 0 (gtk-notebook-prepend-page notebook page4 label2)))
(is (= 3 (gtk-notebook-insert-page notebook page5 nil 3)))
(is (= 3 (gtk-notebook-insert-page notebook page6 label3 3)))
(is (= 6 (length (gtk-container-children notebook))))
(is-false (gtk-notebook-remove-page notebook 0))
(is (= 5 (length (gtk-container-children notebook))))
(is-false (gtk-notebook-remove-page notebook page6))
(is (= 4 (length (gtk-container-children notebook))))
))
(test gtk-notebook-add-page.2
(let ((notebook (make-instance 'gtk-notebook))
(page1 (make-instance 'gtk-frame))
(page2 (make-instance 'gtk-frame))
(page3 (make-instance 'gtk-frame))
(label1 (make-instance 'gtk-label :label "label1"))
(label2 (make-instance 'gtk-label :label "label2"))
(label3 (make-instance 'gtk-label :label "label3"))
(menu-label1 (make-instance 'gtk-label :label "menu-label1"))
(menu-label2 (make-instance 'gtk-label :label "menu-label2"))
(menu-label3 (make-instance 'gtk-label :label "menu-label3")))
(is (= 0 (gtk-notebook-append-page-menu notebook page1 label1 menu-label1)))
(is (= 0 (gtk-notebook-prepend-page-menu notebook page2 label2 menu-label2)))
(is (= 1 (gtk-notebook-insert-page-menu notebook page3 label3 menu-label3 1)))
))
(test gtk-notebook-add-page.3
(let ((notebook (make-instance 'gtk-notebook))
(page1 (make-instance 'gtk-frame))
(page2 (make-instance 'gtk-frame))
(page3 (make-instance 'gtk-frame))
(page4 (make-instance 'gtk-frame))
(page5 (make-instance 'gtk-frame))
(page6 (make-instance 'gtk-frame))
(label1 (make-instance 'gtk-label :label "label1"))
(label2 (make-instance 'gtk-label :label "label2"))
(label3 (make-instance 'gtk-label :label "label3"))
(label4 (make-instance 'gtk-label :label "label4"))
(label5 (make-instance 'gtk-label :label "label5"))
(label6 (make-instance 'gtk-label :label "label6"))
(menu-label1 (make-instance 'gtk-label :label "menu-label1"))
(menu-label2 (make-instance 'gtk-label :label "menu-label2"))
(menu-label3 (make-instance 'gtk-label :label "menu-label3")))
(is (= 0 (gtk-notebook-add-page notebook page1 label1)))
(is (= 0 (gtk-notebook-add-page notebook page2 label2 :position :start)))
(is (= 1 (gtk-notebook-add-page notebook page3 label3 :position 1)))
(is (= 3 (gtk-notebook-add-page notebook page4 label4 :menu menu-label1)))
(is (= 0 (gtk-notebook-add-page notebook page5 label5 :position :start
:menu menu-label2)))
(is (= 1 (gtk-notebook-add-page notebook page6 label6 :position 1
:menu menu-label3)))))
gtk_notebook_set_menu_label_text
gtk_notebook_get_tab_label_text
gtk_notebook_get_tab_hborder deprecated
2021 - 10 - 19
|
774f00f7bdd71c7faf4202e85a1f8de1c5662883c3e3e0ed2ebd50752e6b05e1 | lem-project/lem | main.lisp | (uiop:define-package :lem-encodings-table/main
(:use :cl)
(:export :generate-table))
(in-package :lem-encodings-table/main)
(defun generate-table ()
(lem-encodings-table/sjis:generate-table
(asdf:system-relative-pathname :lem-encodings "cp932.table")
"CP932")
(lem-encodings-table/euc:generate-table
(asdf:system-relative-pathname :lem-encodings "gb2312.table")
"GB2312")
(lem-encodings-table/euc:generate-table
(asdf:system-relative-pathname :lem-encodings "euc-jp.table")
"EUC-JP" :country :jp)
(lem-encodings-table/8bit:generate-table
(asdf:system-relative-pathname :lem-encodings "koi8-u.table")
"KOI8-U")
(lem-encodings-table/8bit:generate-table
(asdf:system-relative-pathname :lem-encodings "iso-8859-2.table")
"ISO-8859-2")
(lem-encodings-table/8bit:generate-table
(asdf:system-relative-pathname :lem-encodings "iso-8859-5.table")
"ISO-8859-5")
(lem-encodings-table/8bit:generate-table
(asdf:system-relative-pathname :lem-encodings "iso-8859-6.table")
"ISO-8859-6")
(lem-encodings-table/8bit:generate-table
(asdf:system-relative-pathname :lem-encodings "iso-8859-7.table")
"ISO-8859-7")
(lem-encodings-table/8bit:generate-table
(asdf:system-relative-pathname :lem-encodings "iso-8859-8.table")
"ISO-8859-8")
(lem-encodings-table/8bit:generate-table
(asdf:system-relative-pathname :lem-encodings "iso-8859-9.table")
"ISO-8859-9")
(lem-encodings-table/8bit:generate-table
(asdf:system-relative-pathname :lem-encodings "iso-8859-13.table")
"ISO-8859-13")
(lem-encodings-table/8bit:generate-table
(asdf:system-relative-pathname :lem-encodings "koi8-r.table")
"KOI8-R")
(lem-encodings-table/8bit:generate-table
(asdf:system-relative-pathname :lem-encodings "cp866.table")
"CP866")
(lem-encodings-table/8bit:generate-table
(asdf:system-relative-pathname :lem-encodings "cp1250.table")
"CP1250")
(lem-encodings-table/8bit:generate-table
(asdf:system-relative-pathname :lem-encodings "cp1251.table")
"CP1251")
(lem-encodings-table/8bit:generate-table
(asdf:system-relative-pathname :lem-encodings "cp1253.table")
"CP1253")
(lem-encodings-table/8bit:generate-table
(asdf:system-relative-pathname :lem-encodings "cp1254.table")
"CP1254")
(lem-encodings-table/8bit:generate-table
(asdf:system-relative-pathname :lem-encodings "cp1255.table")
"CP1255")
(lem-encodings-table/8bit:generate-table
(asdf:system-relative-pathname :lem-encodings "cp1256.table")
"CP1256")
(lem-encodings-table/8bit:generate-table
(asdf:system-relative-pathname :lem-encodings "cp1257.table")
"CP1257"))
| null | https://raw.githubusercontent.com/lem-project/lem/2efd909118a24434623907330de7302143358f1c/lib/encodings/encodings-table/main.lisp | lisp | (uiop:define-package :lem-encodings-table/main
(:use :cl)
(:export :generate-table))
(in-package :lem-encodings-table/main)
(defun generate-table ()
(lem-encodings-table/sjis:generate-table
(asdf:system-relative-pathname :lem-encodings "cp932.table")
"CP932")
(lem-encodings-table/euc:generate-table
(asdf:system-relative-pathname :lem-encodings "gb2312.table")
"GB2312")
(lem-encodings-table/euc:generate-table
(asdf:system-relative-pathname :lem-encodings "euc-jp.table")
"EUC-JP" :country :jp)
(lem-encodings-table/8bit:generate-table
(asdf:system-relative-pathname :lem-encodings "koi8-u.table")
"KOI8-U")
(lem-encodings-table/8bit:generate-table
(asdf:system-relative-pathname :lem-encodings "iso-8859-2.table")
"ISO-8859-2")
(lem-encodings-table/8bit:generate-table
(asdf:system-relative-pathname :lem-encodings "iso-8859-5.table")
"ISO-8859-5")
(lem-encodings-table/8bit:generate-table
(asdf:system-relative-pathname :lem-encodings "iso-8859-6.table")
"ISO-8859-6")
(lem-encodings-table/8bit:generate-table
(asdf:system-relative-pathname :lem-encodings "iso-8859-7.table")
"ISO-8859-7")
(lem-encodings-table/8bit:generate-table
(asdf:system-relative-pathname :lem-encodings "iso-8859-8.table")
"ISO-8859-8")
(lem-encodings-table/8bit:generate-table
(asdf:system-relative-pathname :lem-encodings "iso-8859-9.table")
"ISO-8859-9")
(lem-encodings-table/8bit:generate-table
(asdf:system-relative-pathname :lem-encodings "iso-8859-13.table")
"ISO-8859-13")
(lem-encodings-table/8bit:generate-table
(asdf:system-relative-pathname :lem-encodings "koi8-r.table")
"KOI8-R")
(lem-encodings-table/8bit:generate-table
(asdf:system-relative-pathname :lem-encodings "cp866.table")
"CP866")
(lem-encodings-table/8bit:generate-table
(asdf:system-relative-pathname :lem-encodings "cp1250.table")
"CP1250")
(lem-encodings-table/8bit:generate-table
(asdf:system-relative-pathname :lem-encodings "cp1251.table")
"CP1251")
(lem-encodings-table/8bit:generate-table
(asdf:system-relative-pathname :lem-encodings "cp1253.table")
"CP1253")
(lem-encodings-table/8bit:generate-table
(asdf:system-relative-pathname :lem-encodings "cp1254.table")
"CP1254")
(lem-encodings-table/8bit:generate-table
(asdf:system-relative-pathname :lem-encodings "cp1255.table")
"CP1255")
(lem-encodings-table/8bit:generate-table
(asdf:system-relative-pathname :lem-encodings "cp1256.table")
"CP1256")
(lem-encodings-table/8bit:generate-table
(asdf:system-relative-pathname :lem-encodings "cp1257.table")
"CP1257"))
| |
9e15cdfab652728ad6b07a4e3b46b5c8db8f733f467288dcf0eeb173e91cc8a7 | snowleopard/hadrian | Alex.hs | module Settings.Builders.Alex (alexBuilderArgs) where
import Settings.Builders.Common
alexBuilderArgs :: Args
alexBuilderArgs = builder Alex ? mconcat [ arg "-g"
, arg =<< getInput
, arg "-o", arg =<< getOutput ]
| null | https://raw.githubusercontent.com/snowleopard/hadrian/b9a3f9521b315942e1dabb006688ee7c9902f5fe/src/Settings/Builders/Alex.hs | haskell | module Settings.Builders.Alex (alexBuilderArgs) where
import Settings.Builders.Common
alexBuilderArgs :: Args
alexBuilderArgs = builder Alex ? mconcat [ arg "-g"
, arg =<< getInput
, arg "-o", arg =<< getOutput ]
| |
21cc9a94bef02c96ebef38b7649a072440e09e821bd049647e898385fe19e0d9 | facebookarchive/pfff | pervasives.mli | (***********************************************************************)
(* *)
(* Objective Caml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
(* the special exception on linking described in file ../LICENSE. *)
(* *)
(***********************************************************************)
$ I d : pervasives.mli , v 1.99.2.3 2005/01/31 12:47:53 doligez Exp $
(** The initially opened module.
This module provides the basic operations over the built-in types
(numbers, booleans, strings, exceptions, references, lists, arrays,
input-output channels, ...)
This module is automatically opened at the beginning of each compilation.
All components of this module can therefore be referred by their short
name, without prefixing them by [Pervasives].
*)
* { 6 Exceptions }
external raise : exn -> 'a = "%raise"
(** Raise the given exception value *)
val invalid_arg : string -> 'a
(** Raise exception [Invalid_argument] with the given string. *)
val failwith : string -> 'a
(** Raise exception [Failure] with the given string. *)
exception Exit
(** The [Exit] exception is not raised by any library function. It is
provided for use in your programs.*)
* { 6 Comparisons }
external ( = ) : 'a -> 'a -> bool = "%equal"
* [ e1 = e2 ] tests for structural equality of [ e1 ] and [ e2 ] .
Mutable structures ( e.g. references and arrays ) are equal
if and only if their current contents are structurally equal ,
even if the two mutable objects are not the same physical object .
Equality between functional values raises [ Invalid_argument ] .
Equality between cyclic data structures does not terminate .
Mutable structures (e.g. references and arrays) are equal
if and only if their current contents are structurally equal,
even if the two mutable objects are not the same physical object.
Equality between functional values raises [Invalid_argument].
Equality between cyclic data structures does not terminate. *)
external ( <> ) : 'a -> 'a -> bool = "%notequal"
(** Negation of {!Pervasives.(=)}. *)
external ( < ) : 'a -> 'a -> bool = "%lessthan"
(** See {!Pervasives.(>=)}. *)
external ( > ) : 'a -> 'a -> bool = "%greaterthan"
(** See {!Pervasives.(>=)}. *)
external ( <= ) : 'a -> 'a -> bool = "%lessequal"
(** See {!Pervasives.(>=)}. *)
external ( >= ) : 'a -> 'a -> bool = "%greaterequal"
(** Structural ordering functions. These functions coincide with
the usual orderings over integers, characters, strings
and floating-point numbers, and extend them to a
total ordering over all types.
The ordering is compatible with [(=)]. As in the case
of [(=)], mutable structures are compared by contents.
Comparison between functional values raises [Invalid_argument].
Comparison between cyclic structures does not terminate. *)
external compare : 'a -> 'a -> int = "%compare"
* [ compare x y ] returns [ 0 ] if [ x ] is equal to [ y ] ,
a negative integer if [ x ] is less than [ y ] , and a positive integer
if [ x ] is greater than [ y ] . The ordering implemented by [ compare ]
is compatible with the comparison predicates [ =] , [ < ] and [ > ]
defined above , with one difference on the treatment of the float value
{ ! } . Namely , the comparison predicates treat [ nan ]
as different from any other float value , including itself ;
while [ compare ] treats [ nan ] as equal to itself and less than any
other float value . This treatment of ensures that [ compare ]
defines a total ordering relation .
[ compare ] applied to functional values may raise [ Invalid_argument ] .
[ compare ] applied to cyclic structures may not terminate .
The [ compare ] function can be used as the comparison function
required by the { ! Set . Make } and { ! Map . Make } functors , as well as
the { ! List.sort } and { ! Array.sort } functions .
a negative integer if [x] is less than [y], and a positive integer
if [x] is greater than [y]. The ordering implemented by [compare]
is compatible with the comparison predicates [=], [<] and [>]
defined above, with one difference on the treatment of the float value
{!Pervasives.nan}. Namely, the comparison predicates treat [nan]
as different from any other float value, including itself;
while [compare] treats [nan] as equal to itself and less than any
other float value. This treatment of [nan] ensures that [compare]
defines a total ordering relation.
[compare] applied to functional values may raise [Invalid_argument].
[compare] applied to cyclic structures may not terminate.
The [compare] function can be used as the comparison function
required by the {!Set.Make} and {!Map.Make} functors, as well as
the {!List.sort} and {!Array.sort} functions. *)
val min : 'a -> 'a -> 'a
* Return the smaller of the two arguments .
val max : 'a -> 'a -> 'a
* Return the greater of the two arguments .
external ( == ) : 'a -> 'a -> bool = "%eq"
(** [e1 == e2] tests for physical equality of [e1] and [e2].
On integers and characters, physical equality is identical to structural
equality. On mutable structures, [e1 == e2] is true if and only if
physical modification of [e1] also affects [e2].
On non-mutable structures, the behavior of [(==)] is
implementation-dependent; however, it is guaranteed that
[e1 == e2] implies [compare e1 e2 = 0]. *)
external ( != ) : 'a -> 'a -> bool = "%noteq"
(** Negation of {!Pervasives.(==)}. *)
* { 6 Boolean operations }
external not : bool -> bool = "%boolnot"
(** The boolean negation. *)
external ( && ) : bool -> bool -> bool = "%sequand"
* The boolean ` ` and '' . Evaluation is sequential , left - to - right :
in [ e1 & & e2 ] , [ e1 ] is evaluated first , and if it returns [ false ] ,
[ e2 ] is not evaluated at all .
in [e1 && e2], [e1] is evaluated first, and if it returns [false],
[e2] is not evaluated at all. *)
external ( & ) : bool -> bool -> bool = "%sequand"
(** @deprecated {!Pervasives.(&&)} should be used instead. *)
external ( || ) : bool -> bool -> bool = "%sequor"
* The boolean ` ` or '' . Evaluation is sequential , left - to - right :
in [ e1 || e2 ] , [ e1 ] is evaluated first , and if it returns [ true ] ,
[ e2 ] is not evaluated at all .
in [e1 || e2], [e1] is evaluated first, and if it returns [true],
[e2] is not evaluated at all. *)
external ( or ) : bool -> bool -> bool = "%sequor"
* @deprecated { ! ) } should be used instead .
* { 6 Integer arithmetic }
* Integers are 31 bits wide ( or 63 bits on 64 - bit processors ) .
All operations are taken modulo 2{^31 } ( or 2{^63 } ) .
They do not fail on overflow .
All operations are taken modulo 2{^31} (or 2{^63}).
They do not fail on overflow. *)
external ( ~- ) : int -> int = "%negint"
(** Unary negation. You can also write [-e] instead of [~-e]. *)
external succ : int -> int = "%succint"
(** [succ x] is [x+1]. *)
external pred : int -> int = "%predint"
(** [pred x] is [x-1]. *)
external ( + ) : int -> int -> int = "%addint"
(** Integer addition. *)
external ( - ) : int -> int -> int = "%subint"
(** Integer subtraction. *)
external ( * ) : int -> int -> int = "%mulint"
(** Integer multiplication. *)
external ( / ) : int -> int -> int = "%divint"
* Integer division .
Raise [ Division_by_zero ] if the second argument is 0 .
Integer division rounds the real quotient of its arguments towards zero .
More precisely , if [ x > = 0 ] and [ y > 0 ] , [ x / y ] is the greatest integer
less than or equal to the real quotient of [ x ] by [ y ] . Moreover ,
[ ( -x ) / y = x / ( -y ) = -(x / y ) ] .
Raise [Division_by_zero] if the second argument is 0.
Integer division rounds the real quotient of its arguments towards zero.
More precisely, if [x >= 0] and [y > 0], [x / y] is the greatest integer
less than or equal to the real quotient of [x] by [y]. Moreover,
[(-x) / y = x / (-y) = -(x / y)]. *)
external ( mod ) : int -> int -> int = "%modint"
* Integer remainder . If [ y ] is not zero , the result
of [ x mod y ] satisfies the following properties :
[ x = ( x / y ) * y + x mod y ] and
[ ) < = abs(y)-1 ] .
If [ y = 0 ] , [ x mod y ] raises [ Division_by_zero ] .
Notice that [ x mod y ] is negative if and only if [ x < 0 ] .
of [x mod y] satisfies the following properties:
[x = (x / y) * y + x mod y] and
[abs(x mod y) <= abs(y)-1].
If [y = 0], [x mod y] raises [Division_by_zero].
Notice that [x mod y] is negative if and only if [x < 0]. *)
val abs : int -> int
(** Return the absolute value of the argument. *)
val max_int : int
(** The greatest representable integer. *)
val min_int : int
(** The smallest representable integer. *)
* { 7 Bitwise operations }
external ( land ) : int -> int -> int = "%andint"
(** Bitwise logical and. *)
external ( lor ) : int -> int -> int = "%orint"
(** Bitwise logical or. *)
external ( lxor ) : int -> int -> int = "%xorint"
(** Bitwise logical exclusive or. *)
val lnot : int -> int
(** Bitwise logical negation. *)
external ( lsl ) : int -> int -> int = "%lslint"
* [ n lsl m ] shifts [ n ] to the left by [ m ] bits .
The result is unspecified if [ m < 0 ] or [ m > = bitsize ] ,
where [ bitsize ] is [ 32 ] on a 32 - bit platform and
[ 64 ] on a 64 - bit platform .
The result is unspecified if [m < 0] or [m >= bitsize],
where [bitsize] is [32] on a 32-bit platform and
[64] on a 64-bit platform. *)
external ( lsr ) : int -> int -> int = "%lsrint"
* [ n lsr m ] shifts [ n ] to the right by [ m ] bits .
This is a logical shift : zeroes are inserted regardless of
the sign of [ n ] .
The result is unspecified if [ m < 0 ] or [ m > = bitsize ] .
This is a logical shift: zeroes are inserted regardless of
the sign of [n].
The result is unspecified if [m < 0] or [m >= bitsize]. *)
external ( asr ) : int -> int -> int = "%asrint"
(** [n asr m] shifts [n] to the right by [m] bits.
This is an arithmetic shift: the sign bit of [n] is replicated.
The result is unspecified if [m < 0] or [m >= bitsize]. *)
* { 6 Floating - point arithmetic }
's floating - point numbers follow the
IEEE 754 standard , using double precision ( 64 bits ) numbers .
Floating - point operations never raise an exception on overflow ,
underflow , division by zero , etc . Instead , special IEEE numbers
are returned as appropriate , such as [ infinity ] for [ 1.0 /. 0.0 ] ,
[ neg_infinity ] for [ -1.0 /. 0.0 ] , and [ ] ( ` ` not a number '' )
for [ 0.0 /. 0.0 ] . These special numbers then propagate through
floating - point computations as expected : for instance ,
[ 1.0 /. infinity ] is [ 0.0 ] , and any operation with [ ] as
argument returns [ nan ] as result .
Caml's floating-point numbers follow the
IEEE 754 standard, using double precision (64 bits) numbers.
Floating-point operations never raise an exception on overflow,
underflow, division by zero, etc. Instead, special IEEE numbers
are returned as appropriate, such as [infinity] for [1.0 /. 0.0],
[neg_infinity] for [-1.0 /. 0.0], and [nan] (``not a number'')
for [0.0 /. 0.0]. These special numbers then propagate through
floating-point computations as expected: for instance,
[1.0 /. infinity] is [0.0], and any operation with [nan] as
argument returns [nan] as result.
*)
external ( ~-. ) : float -> float = "%negfloat"
(** Unary negation. You can also write [-.e] instead of [~-.e]. *)
external ( +. ) : float -> float -> float = "%addfloat"
(** Floating-point addition *)
external ( -. ) : float -> float -> float = "%subfloat"
(** Floating-point subtraction *)
external ( *. ) : float -> float -> float = "%mulfloat"
(** Floating-point multiplication *)
external ( /. ) : float -> float -> float = "%divfloat"
(** Floating-point division. *)
external ( ** ) : float -> float -> float = "caml_power_float" "pow" "float"
(** Exponentiation *)
external sqrt : float -> float = "caml_sqrt_float" "sqrt" "float"
(** Square root *)
external exp : float -> float = "caml_exp_float" "exp" "float"
(** Exponential. *)
external log : float -> float = "caml_log_float" "log" "float"
(** Natural logarithm. *)
external log10 : float -> float = "caml_log10_float" "log10" "float"
(** Base 10 logarithm. *)
external cos : float -> float = "caml_cos_float" "cos" "float"
(** See {!Pervasives.atan2}. *)
external sin : float -> float = "caml_sin_float" "sin" "float"
(** See {!Pervasives.atan2}. *)
external tan : float -> float = "caml_tan_float" "tan" "float"
(** See {!Pervasives.atan2}. *)
external acos : float -> float = "caml_acos_float" "acos" "float"
(** See {!Pervasives.atan2}. *)
external asin : float -> float = "caml_asin_float" "asin" "float"
(** See {!Pervasives.atan2}. *)
external atan : float -> float = "caml_atan_float" "atan" "float"
(** See {!Pervasives.atan2}. *)
external atan2 : float -> float -> float = "caml_atan2_float" "atan2" "float"
(** The usual trigonometric functions. *)
external cosh : float -> float = "caml_cosh_float" "cosh" "float"
(** See {!Pervasives.tanh}. *)
external sinh : float -> float = "caml_sinh_float" "sinh" "float"
(** See {!Pervasives.tanh}. *)
external tanh : float -> float = "caml_tanh_float" "tanh" "float"
(** The usual hyperbolic trigonometric functions. *)
external ceil : float -> float = "caml_ceil_float" "ceil" "float"
* See { ! Pervasives.floor } .
external floor : float -> float = "caml_floor_float" "floor" "float"
(** Round the given float to an integer value.
[floor f] returns the greatest integer value less than or
equal to [f].
[ceil f] returns the least integer value greater than or
equal to [f]. *)
external abs_float : float -> float = "%absfloat"
(** Return the absolute value of the argument. *)
external mod_float : float -> float -> float = "caml_fmod_float" "fmod" "float"
* [ mod_float a b ] returns the remainder of [ a ] with respect to
[ b ] . The returned value is [ a - . n * . b ] , where [ n ]
is the quotient [ a /. b ] rounded towards zero to an integer .
[b]. The returned value is [a -. n *. b], where [n]
is the quotient [a /. b] rounded towards zero to an integer. *)
external frexp : float -> float * int = "caml_frexp_float"
* [ frexp f ] returns the pair of the significant
and the exponent of [ f ] . When [ f ] is zero , the
significant [ x ] and the exponent [ n ] of [ f ] are equal to
zero . When [ f ] is non - zero , they are defined by
[ f = x * . 2 * * n ] and [ 0.5 < = x < 1.0 ] .
and the exponent of [f]. When [f] is zero, the
significant [x] and the exponent [n] of [f] are equal to
zero. When [f] is non-zero, they are defined by
[f = x *. 2 ** n] and [0.5 <= x < 1.0]. *)
external ldexp : float -> int -> float = "caml_ldexp_float"
* [ ldexp x n ] returns [ x * . 2 * * n ] .
external modf : float -> float * float = "caml_modf_float"
(** [modf f] returns the pair of the fractional and integral
part of [f]. *)
external float : int -> float = "%floatofint"
(** Same as {!Pervasives.float_of_int}. *)
external float_of_int : int -> float = "%floatofint"
(** Convert an integer to floating-point. *)
external truncate : float -> int = "%intoffloat"
(** Same as {!Pervasives.int_of_float}. *)
external int_of_float : float -> int = "%intoffloat"
* the given floating - point number to an integer .
The result is unspecified if it falls outside the
range of representable integers .
The result is unspecified if it falls outside the
range of representable integers. *)
val infinity : float
(** Positive infinity. *)
val neg_infinity : float
(** Negative infinity. *)
val nan : float
* A special floating - point value denoting the result of an
undefined operation such as [ 0.0 /. 0.0 ] . Stands for
` ` not a number '' . Any floating - point operation with [ ] as
argument returns [ nan ] as result . As for floating - point comparisons ,
[ =] , [ < ] , [ < =] , [ > ] and [ > =] return [ false ] and [ < > ] returns [ true ]
if one or both of their arguments is [ nan ] .
undefined operation such as [0.0 /. 0.0]. Stands for
``not a number''. Any floating-point operation with [nan] as
argument returns [nan] as result. As for floating-point comparisons,
[=], [<], [<=], [>] and [>=] return [false] and [<>] returns [true]
if one or both of their arguments is [nan]. *)
val max_float : float
(** The largest positive finite value of type [float]. *)
val min_float : float
* The smallest positive , non - zero , non - denormalized value of type [ float ] .
val epsilon_float : float
* The smallest positive float [ x ] such that [ 1.0 + . x < > 1.0 ] .
type fpclass =
FP_normal (** Normal number, none of the below *)
* Number very close to 0.0 , has reduced precision
* Number is 0.0 or -0.0
| FP_infinite (** Number is positive or negative infinity *)
| FP_nan (** Not a number: result of an undefined operation *)
* The five classes of floating - point numbers , as determined by
the { ! } function .
the {!Pervasives.classify_float} function. *)
external classify_float : float -> fpclass = "caml_classify_float"
* Return the class of the given floating - point number :
normal , subnormal , zero , infinite , or not a number .
normal, subnormal, zero, infinite, or not a number. *)
* { 6 String operations }
More string operations are provided in module { ! String } .
More string operations are provided in module {!String}.
*)
val ( ^ ) : string -> string -> string
(** String concatenation. *)
* { 6 Character operations }
More character operations are provided in module { ! } .
More character operations are provided in module {!Char}.
*)
external int_of_char : char -> int = "%identity"
(** Return the ASCII code of the argument. *)
val char_of_int : int -> char
(** Return the character with the given ASCII code.
Raise [Invalid_argument "char_of_int"] if the argument is
outside the range 0--255. *)
* { 6 Unit operations }
external ignore : 'a -> unit = "%ignore"
(** Discard the value of its argument and return [()].
For instance, [ignore(f x)] discards the result of
the side-effecting function [f]. It is equivalent to
[f x; ()], except that the latter may generate a
compiler warning; writing [ignore(f x)] instead
avoids the warning. *)
* { 6 String conversion functions }
val string_of_bool : bool -> string
(** Return the string representation of a boolean. *)
val bool_of_string : string -> bool
(** Convert the given string to a boolean.
Raise [Invalid_argument "bool_of_string"] if the string is not
["true"] or ["false"]. *)
val string_of_int : int -> string
(** Return the string representation of an integer, in decimal. *)
external int_of_string : string -> int = "caml_int_of_string"
* Convert the given string to an integer .
The string is read in decimal ( by default ) or in hexadecimal ( if it
begins with [ 0x ] or [ 0X ] ) , octal ( if it begins with [ 0o ] or [ 0O ] ) ,
or binary ( if it begins with [ 0b ] or [ ] ) .
Raise [ Failure " int_of_string " ] if the given string is not
a valid representation of an integer , or if the integer represented
exceeds the range of integers representable in type [ int ] .
The string is read in decimal (by default) or in hexadecimal (if it
begins with [0x] or [0X]), octal (if it begins with [0o] or [0O]),
or binary (if it begins with [0b] or [0B]).
Raise [Failure "int_of_string"] if the given string is not
a valid representation of an integer, or if the integer represented
exceeds the range of integers representable in type [int]. *)
val string_of_float : float -> string
(** Return the string representation of a floating-point number. *)
external float_of_string : string -> float = "caml_float_of_string"
(** Convert the given string to a float. Raise [Failure "float_of_string"]
if the given string is not a valid representation of a float. *)
* { 6 Pair operations }
external fst : 'a * 'b -> 'a = "%field0"
* Return the first component of a pair .
external snd : 'a * 'b -> 'b = "%field1"
* Return the second component of a pair .
* { 6 List operations }
More list operations are provided in module { ! List } .
More list operations are provided in module {!List}.
*)
val ( @ ) : 'a list -> 'a list -> 'a list
(** List concatenation. *)
* { 6 Input / output }
type in_channel
(** The type of input channel. *)
type out_channel
(** The type of output channel. *)
val stdin : in_channel
(** The standard input for the process. *)
val stdout : out_channel
(** The standard output for the process. *)
val stderr : out_channel
(** The standard error ouput for the process. *)
* { 7 Output functions on standard output }
val print_char : char -> unit
(** Print a character on standard output. *)
val print_string : string -> unit
(** Print a string on standard output. *)
val print_int : int -> unit
(** Print an integer, in decimal, on standard output. *)
val print_float : float -> unit
(** Print a floating-point number, in decimal, on standard output. *)
val print_endline : string -> unit
(** Print a string, followed by a newline character, on
standard output and flush standard output. *)
val print_newline : unit -> unit
(** Print a newline character on standard output, and flush
standard output. This can be used to simulate line
buffering of standard output. *)
* { 7 Output functions on standard error }
val prerr_char : char -> unit
(** Print a character on standard error. *)
val prerr_string : string -> unit
(** Print a string on standard error. *)
val prerr_int : int -> unit
(** Print an integer, in decimal, on standard error. *)
val prerr_float : float -> unit
(** Print a floating-point number, in decimal, on standard error. *)
val prerr_endline : string -> unit
(** Print a string, followed by a newline character on standard error
and flush standard error. *)
val prerr_newline : unit -> unit
(** Print a newline character on standard error, and flush
standard error. *)
* { 7 Input functions on standard input }
val read_line : unit -> string
(** Flush standard output, then read characters from standard input
until a newline character is encountered. Return the string of
all characters read, without the newline character at the end. *)
val read_int : unit -> int
* Flush standard output , then read one line from standard input
and convert it to an integer . Raise [ Failure " int_of_string " ]
if the line read is not a valid representation of an integer .
and convert it to an integer. Raise [Failure "int_of_string"]
if the line read is not a valid representation of an integer. *)
val read_float : unit -> float
* Flush standard output , then read one line from standard input
and convert it to a floating - point number .
The result is unspecified if the line read is not a valid
representation of a floating - point number .
and convert it to a floating-point number.
The result is unspecified if the line read is not a valid
representation of a floating-point number. *)
* { 7 General output functions }
type open_flag =
Open_rdonly (** open for reading. *)
| Open_wronly (** open for writing. *)
| Open_append (** open for appending: always write at end of file. *)
| Open_creat (** create the file if it does not exist. *)
| Open_trunc (** empty the file if it already exists. *)
| Open_excl (** fail if Open_creat and the file already exists. *)
| Open_binary (** open in binary mode (no conversion). *)
| Open_text (** open in text mode (may perform conversions). *)
| Open_nonblock (** open in non-blocking mode. *)
* Opening modes for { ! } and { ! } .
val open_out : string -> out_channel
* Open the named file for writing , and return a new output channel
on that file , positionned at the beginning of the file . The
file is truncated to zero length if it already exists . It
is created if it does not already exists .
Raise [ Sys_error ] if the file could not be opened .
on that file, positionned at the beginning of the file. The
file is truncated to zero length if it already exists. It
is created if it does not already exists.
Raise [Sys_error] if the file could not be opened. *)
val open_out_bin : string -> out_channel
* Same as { ! Pervasives.open_out } , but the file is opened in binary mode ,
so that no translation takes place during writes . On operating
systems that do not distinguish between text mode and binary
mode , this function behaves like { ! Pervasives.open_out } .
so that no translation takes place during writes. On operating
systems that do not distinguish between text mode and binary
mode, this function behaves like {!Pervasives.open_out}. *)
val open_out_gen : open_flag list -> int -> string -> out_channel
* Open the named file for writing , as above . The extra argument [ mode ]
specify the opening mode . The extra argument [ perm ] specifies
the file permissions , in case the file must be created .
{ ! Pervasives.open_out } and { ! Pervasives.open_out_bin } are special
cases of this function .
specify the opening mode. The extra argument [perm] specifies
the file permissions, in case the file must be created.
{!Pervasives.open_out} and {!Pervasives.open_out_bin} are special
cases of this function. *)
val flush : out_channel -> unit
(** Flush the buffer associated with the given output channel,
performing all pending writes on that channel.
Interactive programs must be careful about flushing standard
output and standard error at the right time. *)
val flush_all : unit -> unit
(** Flush all open output channels; ignore errors. *)
val output_char : out_channel -> char -> unit
(** Write the character on the given output channel. *)
val output_string : out_channel -> string -> unit
(** Write the string on the given output channel. *)
val output : out_channel -> string -> int -> int -> unit
* [ output oc buf pos len ] writes [ len ] characters from string [ buf ] ,
starting at offset [ pos ] , to the given output channel [ oc ] .
Raise [ Invalid_argument " output " ] if [ pos ] and [ len ] do not
designate a valid substring of [ buf ] .
starting at offset [pos], to the given output channel [oc].
Raise [Invalid_argument "output"] if [pos] and [len] do not
designate a valid substring of [buf]. *)
val output_byte : out_channel -> int -> unit
* Write one 8 - bit integer ( as the single character with that code )
on the given output channel . The given integer is taken modulo
256 .
on the given output channel. The given integer is taken modulo
256. *)
val output_binary_int : out_channel -> int -> unit
* Write one integer in binary format ( 4 bytes , big - endian )
on the given output channel .
The given integer is taken modulo 2{^32 } .
The only reliable way to read it back is through the
{ ! Pervasives.input_binary_int } function . The format is compatible across
all machines for a given version of .
on the given output channel.
The given integer is taken modulo 2{^32}.
The only reliable way to read it back is through the
{!Pervasives.input_binary_int} function. The format is compatible across
all machines for a given version of Objective Caml. *)
val output_value : out_channel -> 'a -> unit
(** Write the representation of a structured value of any type
to a channel. Circularities and sharing inside the value
are detected and preserved. The object can be read back,
by the function {!Pervasives.input_value}. See the description of module
{!Marshal} for more information. {!Pervasives.output_value} is equivalent
to {!Marshal.to_channel} with an empty list of flags. *)
val seek_out : out_channel -> int -> unit
* [ seek_out ] sets the current writing position to [ pos ]
for channel [ chan ] . This works only for regular files . On
files of other kinds ( such as terminals , pipes and sockets ) ,
the behavior is unspecified .
for channel [chan]. This works only for regular files. On
files of other kinds (such as terminals, pipes and sockets),
the behavior is unspecified. *)
val pos_out : out_channel -> int
(** Return the current writing position for the given channel. Does
not work on channels opened with the [Open_append] flag (returns
unspecified results). *)
val out_channel_length : out_channel -> int
(** Return the size (number of characters) of the regular file
on which the given channel is opened. If the channel is opened
on a file that is not a regular file, the result is meaningless. *)
val close_out : out_channel -> unit
* Close the given channel , flushing all buffered write operations .
Output functions raise a [ Sys_error ] exception when they are
applied to a closed output channel , except [ close_out ] and [ flush ] ,
which do nothing when applied to an already closed channel .
Note that [ close_out ] may raise [ ] if the operating
system signals an error when flushing or closing .
Output functions raise a [Sys_error] exception when they are
applied to a closed output channel, except [close_out] and [flush],
which do nothing when applied to an already closed channel.
Note that [close_out] may raise [Sys_error] if the operating
system signals an error when flushing or closing. *)
val close_out_noerr : out_channel -> unit
(** Same as [close_out], but ignore all errors. *)
val set_binary_mode_out : out_channel -> bool -> unit
* [ set_binary_mode_out oc true ] sets the channel [ oc ] to binary
mode : no translations take place during output .
[ set_binary_mode_out oc false ] sets the channel [ oc ] to text
mode : depending on the operating system , some translations
may take place during output . For instance , under Windows ,
end - of - lines will be translated from [ \n ] to [ \r\n ] .
This function has no effect under operating systems that
do not distinguish between text mode and binary mode .
mode: no translations take place during output.
[set_binary_mode_out oc false] sets the channel [oc] to text
mode: depending on the operating system, some translations
may take place during output. For instance, under Windows,
end-of-lines will be translated from [\n] to [\r\n].
This function has no effect under operating systems that
do not distinguish between text mode and binary mode. *)
* { 7 General input functions }
val open_in : string -> in_channel
(** Open the named file for reading, and return a new input channel
on that file, positionned at the beginning of the file.
Raise [Sys_error] if the file could not be opened. *)
val open_in_bin : string -> in_channel
(** Same as {!Pervasives.open_in}, but the file is opened in binary mode,
so that no translation takes place during reads. On operating
systems that do not distinguish between text mode and binary
mode, this function behaves like {!Pervasives.open_in}. *)
val open_in_gen : open_flag list -> int -> string -> in_channel
(** Open the named file for reading, as above. The extra arguments
[mode] and [perm] specify the opening mode and file permissions.
{!Pervasives.open_in} and {!Pervasives.open_in_bin} are special
cases of this function. *)
val input_char : in_channel -> char
* Read one character from the given input channel .
Raise [ End_of_file ] if there are no more characters to read .
Raise [End_of_file] if there are no more characters to read. *)
val input_line : in_channel -> string
(** Read characters from the given input channel, until a
newline character is encountered. Return the string of
all characters read, without the newline character at the end.
Raise [End_of_file] if the end of the file is reached
at the beginning of line. *)
val input : in_channel -> string -> int -> int -> int
* [ input ic buf pos len ] reads up to [ len ] characters from
the given channel [ ic ] , storing them in string [ buf ] , starting at
character number [ pos ] .
It returns the actual number of characters read , between 0 and
[ len ] ( inclusive ) .
A return value of 0 means that the end of file was reached .
A return value between 0 and [ len ] exclusive means that
not all requested [ len ] characters were read , either because
no more characters were available at that time , or because
the implementation found it convenient to do a partial read ;
[ input ] must be called again to read the remaining characters ,
if desired . ( See also { ! Pervasives.really_input } for reading
exactly [ len ] characters . )
Exception [ Invalid_argument " input " ] is raised if [ pos ] and [ len ]
do not designate a valid substring of [ buf ] .
the given channel [ic], storing them in string [buf], starting at
character number [pos].
It returns the actual number of characters read, between 0 and
[len] (inclusive).
A return value of 0 means that the end of file was reached.
A return value between 0 and [len] exclusive means that
not all requested [len] characters were read, either because
no more characters were available at that time, or because
the implementation found it convenient to do a partial read;
[input] must be called again to read the remaining characters,
if desired. (See also {!Pervasives.really_input} for reading
exactly [len] characters.)
Exception [Invalid_argument "input"] is raised if [pos] and [len]
do not designate a valid substring of [buf]. *)
val really_input : in_channel -> string -> int -> int -> unit
* [ really_input ic buf pos len ] reads [ len ] characters from channel [ ic ] ,
storing them in string [ buf ] , starting at character number [ pos ] .
Raise [ End_of_file ] if the end of file is reached before [ len ]
characters have been read .
Raise [ Invalid_argument " really_input " ] if
[ pos ] and [ len ] do not designate a valid substring of [ buf ] .
storing them in string [buf], starting at character number [pos].
Raise [End_of_file] if the end of file is reached before [len]
characters have been read.
Raise [Invalid_argument "really_input"] if
[pos] and [len] do not designate a valid substring of [buf]. *)
val input_byte : in_channel -> int
* Same as { ! Pervasives.input_char } , but return the 8 - bit integer representing
the character .
Raise [ End_of_file ] if an end of file was reached .
the character.
Raise [End_of_file] if an end of file was reached. *)
val input_binary_int : in_channel -> int
* Read an integer encoded in binary format ( 4 bytes , big - endian )
from the given input channel . See { ! Pervasives.output_binary_int } .
Raise [ End_of_file ] if an end of file was reached while reading the
integer .
from the given input channel. See {!Pervasives.output_binary_int}.
Raise [End_of_file] if an end of file was reached while reading the
integer. *)
val input_value : in_channel -> 'a
(** Read the representation of a structured value, as produced
by {!Pervasives.output_value}, and return the corresponding value.
This function is identical to {!Marshal.from_channel};
see the description of module {!Marshal} for more information,
in particular concerning the lack of type safety. *)
val seek_in : in_channel -> int -> unit
(** [seek_in chan pos] sets the current reading position to [pos]
for channel [chan]. This works only for regular files. On
files of other kinds, the behavior is unspecified. *)
val pos_in : in_channel -> int
(** Return the current reading position for the given channel. *)
val in_channel_length : in_channel -> int
(** Return the size (number of characters) of the regular file
on which the given channel is opened. If the channel is opened
on a file that is not a regular file, the result is meaningless.
The returned size does not take into account the end-of-line
translations that can be performed when reading from a channel
opened in text mode. *)
val close_in : in_channel -> unit
* Close the given channel . Input functions raise a [ Sys_error ]
exception when they are applied to a closed input channel ,
except [ close_in ] , which does nothing when applied to an already
closed channel . Note that [ close_in ] may raise [ ] if
the operating system signals an error .
exception when they are applied to a closed input channel,
except [close_in], which does nothing when applied to an already
closed channel. Note that [close_in] may raise [Sys_error] if
the operating system signals an error. *)
val close_in_noerr : in_channel -> unit
(** Same as [close_in], but ignore all errors. *)
val set_binary_mode_in : in_channel -> bool -> unit
* [ set_binary_mode_in ic true ] sets the channel [ ic ] to binary
mode : no translations take place during input .
[ set_binary_mode_out ic false ] sets the channel [ ic ] to text
mode : depending on the operating system , some translations
may take place during input . For instance , under Windows ,
end - of - lines will be translated from [ \r\n ] to [ \n ] .
This function has no effect under operating systems that
do not distinguish between text mode and binary mode .
mode: no translations take place during input.
[set_binary_mode_out ic false] sets the channel [ic] to text
mode: depending on the operating system, some translations
may take place during input. For instance, under Windows,
end-of-lines will be translated from [\r\n] to [\n].
This function has no effect under operating systems that
do not distinguish between text mode and binary mode. *)
* { 7 Operations on large files }
module LargeFile :
sig
val seek_out : out_channel -> int64 -> unit
val pos_out : out_channel -> int64
val out_channel_length : out_channel -> int64
val seek_in : in_channel -> int64 -> unit
val pos_in : in_channel -> int64
val in_channel_length : in_channel -> int64
end
* Operations on large files .
This sub - module provides 64 - bit variants of the channel functions
that manipulate file positions and file sizes . By representing
positions and sizes by 64 - bit integers ( type [ int64 ] ) instead of
regular integers ( type [ int ] ) , these alternate functions allow
operating on files whose sizes are greater than [ max_int ] .
This sub-module provides 64-bit variants of the channel functions
that manipulate file positions and file sizes. By representing
positions and sizes by 64-bit integers (type [int64]) instead of
regular integers (type [int]), these alternate functions allow
operating on files whose sizes are greater than [max_int]. *)
(** {6 References} *)
type 'a ref = { mutable contents : 'a }
(** The type of references (mutable indirection cells) containing
a value of type ['a]. *)
external ref : 'a -> 'a ref = "%makemutable"
(** Return a fresh reference containing the given value. *)
external ( ! ) : 'a ref -> 'a = "%field0"
(** [!r] returns the current contents of reference [r].
Equivalent to [fun r -> r.contents]. *)
external ( := ) : 'a ref -> 'a -> unit = "%setfield0"
(** [r := a] stores the value of [a] in reference [r].
Equivalent to [fun r v -> r.contents <- v]. *)
external incr : int ref -> unit = "%incr"
(** Increment the integer contained in the given reference.
Equivalent to [fun r -> r := succ !r]. *)
external decr : int ref -> unit = "%decr"
(** Decrement the integer contained in the given reference.
Equivalent to [fun r -> r := pred !r]. *)
* { 6 Operations on format strings }
(** See modules {!Printf} and {!Scanf} for more operations on
format strings. *)
type ('a, 'b, 'c) format = ('a, 'b, 'c, 'c) format4
* Simplified type for format strings , included for backward compatibility
with earlier releases of [ ' a ] is the type of the parameters of the format ,
[ ' c ] is the result type for the " printf"-style function ,
and [ ' b ] is the type of the first argument given to
[ % a ] and [ % t ] printing functions .
with earlier releases of Objective Caml.
['a] is the type of the parameters of the format,
['c] is the result type for the "printf"-style function,
and ['b] is the type of the first argument given to
[%a] and [%t] printing functions. *)
val string_of_format : ('a, 'b, 'c, 'd) format4 -> string
(** Converts a format string into a string. *)
external format_of_string :
('a, 'b, 'c, 'd) format4 -> ('a, 'b, 'c, 'd) format4 = "%identity"
(** [format_of_string s] returns a format string read from the string
literal [s]. *)
val ( ^^ ) :
('a, 'b, 'c, 'd) format4 -> ('d, 'b, 'c, 'e) format4 ->
('a, 'b, 'c, 'e) format4;;
(** [f1 ^^ f2] catenates formats [f1] and [f2]. The result is a format
that accepts arguments from [f1], then arguments from [f2]. *)
* { 6 Program termination }
val exit : int -> 'a
* Terminate the process , returning the given status code
to the operating system : usually 0 to indicate no errors ,
and a small positive integer to indicate failure .
All open output channels are flushed with flush_all .
An implicit [ exit 0 ] is performed each time a program
terminates normally . An implicit [ exit 2 ] is performed if the program
terminates early because of an uncaught exception .
to the operating system: usually 0 to indicate no errors,
and a small positive integer to indicate failure.
All open output channels are flushed with flush_all.
An implicit [exit 0] is performed each time a program
terminates normally. An implicit [exit 2] is performed if the program
terminates early because of an uncaught exception. *)
val at_exit : (unit -> unit) -> unit
* Register the given function to be called at program
termination time . The functions registered with [ at_exit ]
will be called when the program executes { ! Pervasives.exit } ,
or terminates , either normally or because of an uncaught exception .
The functions are called in ` ` last in , first out '' order :
the function most recently added with [ at_exit ] is called first .
termination time. The functions registered with [at_exit]
will be called when the program executes {!Pervasives.exit},
or terminates, either normally or because of an uncaught exception.
The functions are called in ``last in, first out'' order:
the function most recently added with [at_exit] is called first. *)
(**/**)
* { 6 For system use only , not for the casual user }
val valid_float_lexem : string -> string
val unsafe_really_input : in_channel -> string -> int -> int -> unit
val do_at_exit : unit -> unit
| null | https://raw.githubusercontent.com/facebookarchive/pfff/ec21095ab7d445559576513a63314e794378c367/external/stdlib/pervasives.mli | ocaml | *********************************************************************
Objective Caml
the special exception on linking described in file ../LICENSE.
*********************************************************************
* The initially opened module.
This module provides the basic operations over the built-in types
(numbers, booleans, strings, exceptions, references, lists, arrays,
input-output channels, ...)
This module is automatically opened at the beginning of each compilation.
All components of this module can therefore be referred by their short
name, without prefixing them by [Pervasives].
* Raise the given exception value
* Raise exception [Invalid_argument] with the given string.
* Raise exception [Failure] with the given string.
* The [Exit] exception is not raised by any library function. It is
provided for use in your programs.
* Negation of {!Pervasives.(=)}.
* See {!Pervasives.(>=)}.
* See {!Pervasives.(>=)}.
* See {!Pervasives.(>=)}.
* Structural ordering functions. These functions coincide with
the usual orderings over integers, characters, strings
and floating-point numbers, and extend them to a
total ordering over all types.
The ordering is compatible with [(=)]. As in the case
of [(=)], mutable structures are compared by contents.
Comparison between functional values raises [Invalid_argument].
Comparison between cyclic structures does not terminate.
* [e1 == e2] tests for physical equality of [e1] and [e2].
On integers and characters, physical equality is identical to structural
equality. On mutable structures, [e1 == e2] is true if and only if
physical modification of [e1] also affects [e2].
On non-mutable structures, the behavior of [(==)] is
implementation-dependent; however, it is guaranteed that
[e1 == e2] implies [compare e1 e2 = 0].
* Negation of {!Pervasives.(==)}.
* The boolean negation.
* @deprecated {!Pervasives.(&&)} should be used instead.
* Unary negation. You can also write [-e] instead of [~-e].
* [succ x] is [x+1].
* [pred x] is [x-1].
* Integer addition.
* Integer subtraction.
* Integer multiplication.
* Return the absolute value of the argument.
* The greatest representable integer.
* The smallest representable integer.
* Bitwise logical and.
* Bitwise logical or.
* Bitwise logical exclusive or.
* Bitwise logical negation.
* [n asr m] shifts [n] to the right by [m] bits.
This is an arithmetic shift: the sign bit of [n] is replicated.
The result is unspecified if [m < 0] or [m >= bitsize].
* Unary negation. You can also write [-.e] instead of [~-.e].
* Floating-point addition
* Floating-point subtraction
* Floating-point multiplication
* Floating-point division.
* Exponentiation
* Square root
* Exponential.
* Natural logarithm.
* Base 10 logarithm.
* See {!Pervasives.atan2}.
* See {!Pervasives.atan2}.
* See {!Pervasives.atan2}.
* See {!Pervasives.atan2}.
* See {!Pervasives.atan2}.
* See {!Pervasives.atan2}.
* The usual trigonometric functions.
* See {!Pervasives.tanh}.
* See {!Pervasives.tanh}.
* The usual hyperbolic trigonometric functions.
* Round the given float to an integer value.
[floor f] returns the greatest integer value less than or
equal to [f].
[ceil f] returns the least integer value greater than or
equal to [f].
* Return the absolute value of the argument.
* [modf f] returns the pair of the fractional and integral
part of [f].
* Same as {!Pervasives.float_of_int}.
* Convert an integer to floating-point.
* Same as {!Pervasives.int_of_float}.
* Positive infinity.
* Negative infinity.
* The largest positive finite value of type [float].
* Normal number, none of the below
* Number is positive or negative infinity
* Not a number: result of an undefined operation
* String concatenation.
* Return the ASCII code of the argument.
* Return the character with the given ASCII code.
Raise [Invalid_argument "char_of_int"] if the argument is
outside the range 0--255.
* Discard the value of its argument and return [()].
For instance, [ignore(f x)] discards the result of
the side-effecting function [f]. It is equivalent to
[f x; ()], except that the latter may generate a
compiler warning; writing [ignore(f x)] instead
avoids the warning.
* Return the string representation of a boolean.
* Convert the given string to a boolean.
Raise [Invalid_argument "bool_of_string"] if the string is not
["true"] or ["false"].
* Return the string representation of an integer, in decimal.
* Return the string representation of a floating-point number.
* Convert the given string to a float. Raise [Failure "float_of_string"]
if the given string is not a valid representation of a float.
* List concatenation.
* The type of input channel.
* The type of output channel.
* The standard input for the process.
* The standard output for the process.
* The standard error ouput for the process.
* Print a character on standard output.
* Print a string on standard output.
* Print an integer, in decimal, on standard output.
* Print a floating-point number, in decimal, on standard output.
* Print a string, followed by a newline character, on
standard output and flush standard output.
* Print a newline character on standard output, and flush
standard output. This can be used to simulate line
buffering of standard output.
* Print a character on standard error.
* Print a string on standard error.
* Print an integer, in decimal, on standard error.
* Print a floating-point number, in decimal, on standard error.
* Print a string, followed by a newline character on standard error
and flush standard error.
* Print a newline character on standard error, and flush
standard error.
* Flush standard output, then read characters from standard input
until a newline character is encountered. Return the string of
all characters read, without the newline character at the end.
* open for reading.
* open for writing.
* open for appending: always write at end of file.
* create the file if it does not exist.
* empty the file if it already exists.
* fail if Open_creat and the file already exists.
* open in binary mode (no conversion).
* open in text mode (may perform conversions).
* open in non-blocking mode.
* Flush the buffer associated with the given output channel,
performing all pending writes on that channel.
Interactive programs must be careful about flushing standard
output and standard error at the right time.
* Flush all open output channels; ignore errors.
* Write the character on the given output channel.
* Write the string on the given output channel.
* Write the representation of a structured value of any type
to a channel. Circularities and sharing inside the value
are detected and preserved. The object can be read back,
by the function {!Pervasives.input_value}. See the description of module
{!Marshal} for more information. {!Pervasives.output_value} is equivalent
to {!Marshal.to_channel} with an empty list of flags.
* Return the current writing position for the given channel. Does
not work on channels opened with the [Open_append] flag (returns
unspecified results).
* Return the size (number of characters) of the regular file
on which the given channel is opened. If the channel is opened
on a file that is not a regular file, the result is meaningless.
* Same as [close_out], but ignore all errors.
* Open the named file for reading, and return a new input channel
on that file, positionned at the beginning of the file.
Raise [Sys_error] if the file could not be opened.
* Same as {!Pervasives.open_in}, but the file is opened in binary mode,
so that no translation takes place during reads. On operating
systems that do not distinguish between text mode and binary
mode, this function behaves like {!Pervasives.open_in}.
* Open the named file for reading, as above. The extra arguments
[mode] and [perm] specify the opening mode and file permissions.
{!Pervasives.open_in} and {!Pervasives.open_in_bin} are special
cases of this function.
* Read characters from the given input channel, until a
newline character is encountered. Return the string of
all characters read, without the newline character at the end.
Raise [End_of_file] if the end of the file is reached
at the beginning of line.
* Read the representation of a structured value, as produced
by {!Pervasives.output_value}, and return the corresponding value.
This function is identical to {!Marshal.from_channel};
see the description of module {!Marshal} for more information,
in particular concerning the lack of type safety.
* [seek_in chan pos] sets the current reading position to [pos]
for channel [chan]. This works only for regular files. On
files of other kinds, the behavior is unspecified.
* Return the current reading position for the given channel.
* Return the size (number of characters) of the regular file
on which the given channel is opened. If the channel is opened
on a file that is not a regular file, the result is meaningless.
The returned size does not take into account the end-of-line
translations that can be performed when reading from a channel
opened in text mode.
* Same as [close_in], but ignore all errors.
* {6 References}
* The type of references (mutable indirection cells) containing
a value of type ['a].
* Return a fresh reference containing the given value.
* [!r] returns the current contents of reference [r].
Equivalent to [fun r -> r.contents].
* [r := a] stores the value of [a] in reference [r].
Equivalent to [fun r v -> r.contents <- v].
* Increment the integer contained in the given reference.
Equivalent to [fun r -> r := succ !r].
* Decrement the integer contained in the given reference.
Equivalent to [fun r -> r := pred !r].
* See modules {!Printf} and {!Scanf} for more operations on
format strings.
* Converts a format string into a string.
* [format_of_string s] returns a format string read from the string
literal [s].
* [f1 ^^ f2] catenates formats [f1] and [f2]. The result is a format
that accepts arguments from [f1], then arguments from [f2].
*/* | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
$ I d : pervasives.mli , v 1.99.2.3 2005/01/31 12:47:53 doligez Exp $
* { 6 Exceptions }
external raise : exn -> 'a = "%raise"
val invalid_arg : string -> 'a
val failwith : string -> 'a
exception Exit
* { 6 Comparisons }
external ( = ) : 'a -> 'a -> bool = "%equal"
* [ e1 = e2 ] tests for structural equality of [ e1 ] and [ e2 ] .
Mutable structures ( e.g. references and arrays ) are equal
if and only if their current contents are structurally equal ,
even if the two mutable objects are not the same physical object .
Equality between functional values raises [ Invalid_argument ] .
Equality between cyclic data structures does not terminate .
Mutable structures (e.g. references and arrays) are equal
if and only if their current contents are structurally equal,
even if the two mutable objects are not the same physical object.
Equality between functional values raises [Invalid_argument].
Equality between cyclic data structures does not terminate. *)
external ( <> ) : 'a -> 'a -> bool = "%notequal"
external ( < ) : 'a -> 'a -> bool = "%lessthan"
external ( > ) : 'a -> 'a -> bool = "%greaterthan"
external ( <= ) : 'a -> 'a -> bool = "%lessequal"
external ( >= ) : 'a -> 'a -> bool = "%greaterequal"
external compare : 'a -> 'a -> int = "%compare"
* [ compare x y ] returns [ 0 ] if [ x ] is equal to [ y ] ,
a negative integer if [ x ] is less than [ y ] , and a positive integer
if [ x ] is greater than [ y ] . The ordering implemented by [ compare ]
is compatible with the comparison predicates [ =] , [ < ] and [ > ]
defined above , with one difference on the treatment of the float value
{ ! } . Namely , the comparison predicates treat [ nan ]
as different from any other float value , including itself ;
while [ compare ] treats [ nan ] as equal to itself and less than any
other float value . This treatment of ensures that [ compare ]
defines a total ordering relation .
[ compare ] applied to functional values may raise [ Invalid_argument ] .
[ compare ] applied to cyclic structures may not terminate .
The [ compare ] function can be used as the comparison function
required by the { ! Set . Make } and { ! Map . Make } functors , as well as
the { ! List.sort } and { ! Array.sort } functions .
a negative integer if [x] is less than [y], and a positive integer
if [x] is greater than [y]. The ordering implemented by [compare]
is compatible with the comparison predicates [=], [<] and [>]
defined above, with one difference on the treatment of the float value
{!Pervasives.nan}. Namely, the comparison predicates treat [nan]
as different from any other float value, including itself;
while [compare] treats [nan] as equal to itself and less than any
other float value. This treatment of [nan] ensures that [compare]
defines a total ordering relation.
[compare] applied to functional values may raise [Invalid_argument].
[compare] applied to cyclic structures may not terminate.
The [compare] function can be used as the comparison function
required by the {!Set.Make} and {!Map.Make} functors, as well as
the {!List.sort} and {!Array.sort} functions. *)
val min : 'a -> 'a -> 'a
* Return the smaller of the two arguments .
val max : 'a -> 'a -> 'a
* Return the greater of the two arguments .
external ( == ) : 'a -> 'a -> bool = "%eq"
external ( != ) : 'a -> 'a -> bool = "%noteq"
* { 6 Boolean operations }
external not : bool -> bool = "%boolnot"
external ( && ) : bool -> bool -> bool = "%sequand"
* The boolean ` ` and '' . Evaluation is sequential , left - to - right :
in [ e1 & & e2 ] , [ e1 ] is evaluated first , and if it returns [ false ] ,
[ e2 ] is not evaluated at all .
in [e1 && e2], [e1] is evaluated first, and if it returns [false],
[e2] is not evaluated at all. *)
external ( & ) : bool -> bool -> bool = "%sequand"
external ( || ) : bool -> bool -> bool = "%sequor"
* The boolean ` ` or '' . Evaluation is sequential , left - to - right :
in [ e1 || e2 ] , [ e1 ] is evaluated first , and if it returns [ true ] ,
[ e2 ] is not evaluated at all .
in [e1 || e2], [e1] is evaluated first, and if it returns [true],
[e2] is not evaluated at all. *)
external ( or ) : bool -> bool -> bool = "%sequor"
* @deprecated { ! ) } should be used instead .
* { 6 Integer arithmetic }
* Integers are 31 bits wide ( or 63 bits on 64 - bit processors ) .
All operations are taken modulo 2{^31 } ( or 2{^63 } ) .
They do not fail on overflow .
All operations are taken modulo 2{^31} (or 2{^63}).
They do not fail on overflow. *)
external ( ~- ) : int -> int = "%negint"
external succ : int -> int = "%succint"
external pred : int -> int = "%predint"
external ( + ) : int -> int -> int = "%addint"
external ( - ) : int -> int -> int = "%subint"
external ( * ) : int -> int -> int = "%mulint"
external ( / ) : int -> int -> int = "%divint"
* Integer division .
Raise [ Division_by_zero ] if the second argument is 0 .
Integer division rounds the real quotient of its arguments towards zero .
More precisely , if [ x > = 0 ] and [ y > 0 ] , [ x / y ] is the greatest integer
less than or equal to the real quotient of [ x ] by [ y ] . Moreover ,
[ ( -x ) / y = x / ( -y ) = -(x / y ) ] .
Raise [Division_by_zero] if the second argument is 0.
Integer division rounds the real quotient of its arguments towards zero.
More precisely, if [x >= 0] and [y > 0], [x / y] is the greatest integer
less than or equal to the real quotient of [x] by [y]. Moreover,
[(-x) / y = x / (-y) = -(x / y)]. *)
external ( mod ) : int -> int -> int = "%modint"
* Integer remainder . If [ y ] is not zero , the result
of [ x mod y ] satisfies the following properties :
[ x = ( x / y ) * y + x mod y ] and
[ ) < = abs(y)-1 ] .
If [ y = 0 ] , [ x mod y ] raises [ Division_by_zero ] .
Notice that [ x mod y ] is negative if and only if [ x < 0 ] .
of [x mod y] satisfies the following properties:
[x = (x / y) * y + x mod y] and
[abs(x mod y) <= abs(y)-1].
If [y = 0], [x mod y] raises [Division_by_zero].
Notice that [x mod y] is negative if and only if [x < 0]. *)
val abs : int -> int
val max_int : int
val min_int : int
* { 7 Bitwise operations }
external ( land ) : int -> int -> int = "%andint"
external ( lor ) : int -> int -> int = "%orint"
external ( lxor ) : int -> int -> int = "%xorint"
val lnot : int -> int
external ( lsl ) : int -> int -> int = "%lslint"
* [ n lsl m ] shifts [ n ] to the left by [ m ] bits .
The result is unspecified if [ m < 0 ] or [ m > = bitsize ] ,
where [ bitsize ] is [ 32 ] on a 32 - bit platform and
[ 64 ] on a 64 - bit platform .
The result is unspecified if [m < 0] or [m >= bitsize],
where [bitsize] is [32] on a 32-bit platform and
[64] on a 64-bit platform. *)
external ( lsr ) : int -> int -> int = "%lsrint"
* [ n lsr m ] shifts [ n ] to the right by [ m ] bits .
This is a logical shift : zeroes are inserted regardless of
the sign of [ n ] .
The result is unspecified if [ m < 0 ] or [ m > = bitsize ] .
This is a logical shift: zeroes are inserted regardless of
the sign of [n].
The result is unspecified if [m < 0] or [m >= bitsize]. *)
external ( asr ) : int -> int -> int = "%asrint"
* { 6 Floating - point arithmetic }
's floating - point numbers follow the
IEEE 754 standard , using double precision ( 64 bits ) numbers .
Floating - point operations never raise an exception on overflow ,
underflow , division by zero , etc . Instead , special IEEE numbers
are returned as appropriate , such as [ infinity ] for [ 1.0 /. 0.0 ] ,
[ neg_infinity ] for [ -1.0 /. 0.0 ] , and [ ] ( ` ` not a number '' )
for [ 0.0 /. 0.0 ] . These special numbers then propagate through
floating - point computations as expected : for instance ,
[ 1.0 /. infinity ] is [ 0.0 ] , and any operation with [ ] as
argument returns [ nan ] as result .
Caml's floating-point numbers follow the
IEEE 754 standard, using double precision (64 bits) numbers.
Floating-point operations never raise an exception on overflow,
underflow, division by zero, etc. Instead, special IEEE numbers
are returned as appropriate, such as [infinity] for [1.0 /. 0.0],
[neg_infinity] for [-1.0 /. 0.0], and [nan] (``not a number'')
for [0.0 /. 0.0]. These special numbers then propagate through
floating-point computations as expected: for instance,
[1.0 /. infinity] is [0.0], and any operation with [nan] as
argument returns [nan] as result.
*)
external ( ~-. ) : float -> float = "%negfloat"
external ( +. ) : float -> float -> float = "%addfloat"
external ( -. ) : float -> float -> float = "%subfloat"
external ( *. ) : float -> float -> float = "%mulfloat"
external ( /. ) : float -> float -> float = "%divfloat"
external ( ** ) : float -> float -> float = "caml_power_float" "pow" "float"
external sqrt : float -> float = "caml_sqrt_float" "sqrt" "float"
external exp : float -> float = "caml_exp_float" "exp" "float"
external log : float -> float = "caml_log_float" "log" "float"
external log10 : float -> float = "caml_log10_float" "log10" "float"
external cos : float -> float = "caml_cos_float" "cos" "float"
external sin : float -> float = "caml_sin_float" "sin" "float"
external tan : float -> float = "caml_tan_float" "tan" "float"
external acos : float -> float = "caml_acos_float" "acos" "float"
external asin : float -> float = "caml_asin_float" "asin" "float"
external atan : float -> float = "caml_atan_float" "atan" "float"
external atan2 : float -> float -> float = "caml_atan2_float" "atan2" "float"
external cosh : float -> float = "caml_cosh_float" "cosh" "float"
external sinh : float -> float = "caml_sinh_float" "sinh" "float"
external tanh : float -> float = "caml_tanh_float" "tanh" "float"
external ceil : float -> float = "caml_ceil_float" "ceil" "float"
* See { ! Pervasives.floor } .
external floor : float -> float = "caml_floor_float" "floor" "float"
external abs_float : float -> float = "%absfloat"
external mod_float : float -> float -> float = "caml_fmod_float" "fmod" "float"
* [ mod_float a b ] returns the remainder of [ a ] with respect to
[ b ] . The returned value is [ a - . n * . b ] , where [ n ]
is the quotient [ a /. b ] rounded towards zero to an integer .
[b]. The returned value is [a -. n *. b], where [n]
is the quotient [a /. b] rounded towards zero to an integer. *)
external frexp : float -> float * int = "caml_frexp_float"
* [ frexp f ] returns the pair of the significant
and the exponent of [ f ] . When [ f ] is zero , the
significant [ x ] and the exponent [ n ] of [ f ] are equal to
zero . When [ f ] is non - zero , they are defined by
[ f = x * . 2 * * n ] and [ 0.5 < = x < 1.0 ] .
and the exponent of [f]. When [f] is zero, the
significant [x] and the exponent [n] of [f] are equal to
zero. When [f] is non-zero, they are defined by
[f = x *. 2 ** n] and [0.5 <= x < 1.0]. *)
external ldexp : float -> int -> float = "caml_ldexp_float"
* [ ldexp x n ] returns [ x * . 2 * * n ] .
external modf : float -> float * float = "caml_modf_float"
external float : int -> float = "%floatofint"
external float_of_int : int -> float = "%floatofint"
external truncate : float -> int = "%intoffloat"
external int_of_float : float -> int = "%intoffloat"
* the given floating - point number to an integer .
The result is unspecified if it falls outside the
range of representable integers .
The result is unspecified if it falls outside the
range of representable integers. *)
val infinity : float
val neg_infinity : float
val nan : float
* A special floating - point value denoting the result of an
undefined operation such as [ 0.0 /. 0.0 ] . Stands for
` ` not a number '' . Any floating - point operation with [ ] as
argument returns [ nan ] as result . As for floating - point comparisons ,
[ =] , [ < ] , [ < =] , [ > ] and [ > =] return [ false ] and [ < > ] returns [ true ]
if one or both of their arguments is [ nan ] .
undefined operation such as [0.0 /. 0.0]. Stands for
``not a number''. Any floating-point operation with [nan] as
argument returns [nan] as result. As for floating-point comparisons,
[=], [<], [<=], [>] and [>=] return [false] and [<>] returns [true]
if one or both of their arguments is [nan]. *)
val max_float : float
val min_float : float
* The smallest positive , non - zero , non - denormalized value of type [ float ] .
val epsilon_float : float
* The smallest positive float [ x ] such that [ 1.0 + . x < > 1.0 ] .
type fpclass =
* Number very close to 0.0 , has reduced precision
* Number is 0.0 or -0.0
* The five classes of floating - point numbers , as determined by
the { ! } function .
the {!Pervasives.classify_float} function. *)
external classify_float : float -> fpclass = "caml_classify_float"
* Return the class of the given floating - point number :
normal , subnormal , zero , infinite , or not a number .
normal, subnormal, zero, infinite, or not a number. *)
* { 6 String operations }
More string operations are provided in module { ! String } .
More string operations are provided in module {!String}.
*)
val ( ^ ) : string -> string -> string
* { 6 Character operations }
More character operations are provided in module { ! } .
More character operations are provided in module {!Char}.
*)
external int_of_char : char -> int = "%identity"
val char_of_int : int -> char
* { 6 Unit operations }
external ignore : 'a -> unit = "%ignore"
* { 6 String conversion functions }
val string_of_bool : bool -> string
val bool_of_string : string -> bool
val string_of_int : int -> string
external int_of_string : string -> int = "caml_int_of_string"
* Convert the given string to an integer .
The string is read in decimal ( by default ) or in hexadecimal ( if it
begins with [ 0x ] or [ 0X ] ) , octal ( if it begins with [ 0o ] or [ 0O ] ) ,
or binary ( if it begins with [ 0b ] or [ ] ) .
Raise [ Failure " int_of_string " ] if the given string is not
a valid representation of an integer , or if the integer represented
exceeds the range of integers representable in type [ int ] .
The string is read in decimal (by default) or in hexadecimal (if it
begins with [0x] or [0X]), octal (if it begins with [0o] or [0O]),
or binary (if it begins with [0b] or [0B]).
Raise [Failure "int_of_string"] if the given string is not
a valid representation of an integer, or if the integer represented
exceeds the range of integers representable in type [int]. *)
val string_of_float : float -> string
external float_of_string : string -> float = "caml_float_of_string"
* { 6 Pair operations }
external fst : 'a * 'b -> 'a = "%field0"
* Return the first component of a pair .
external snd : 'a * 'b -> 'b = "%field1"
* Return the second component of a pair .
* { 6 List operations }
More list operations are provided in module { ! List } .
More list operations are provided in module {!List}.
*)
val ( @ ) : 'a list -> 'a list -> 'a list
* { 6 Input / output }
type in_channel
type out_channel
val stdin : in_channel
val stdout : out_channel
val stderr : out_channel
* { 7 Output functions on standard output }
val print_char : char -> unit
val print_string : string -> unit
val print_int : int -> unit
val print_float : float -> unit
val print_endline : string -> unit
val print_newline : unit -> unit
* { 7 Output functions on standard error }
val prerr_char : char -> unit
val prerr_string : string -> unit
val prerr_int : int -> unit
val prerr_float : float -> unit
val prerr_endline : string -> unit
val prerr_newline : unit -> unit
* { 7 Input functions on standard input }
val read_line : unit -> string
val read_int : unit -> int
* Flush standard output , then read one line from standard input
and convert it to an integer . Raise [ Failure " int_of_string " ]
if the line read is not a valid representation of an integer .
and convert it to an integer. Raise [Failure "int_of_string"]
if the line read is not a valid representation of an integer. *)
val read_float : unit -> float
* Flush standard output , then read one line from standard input
and convert it to a floating - point number .
The result is unspecified if the line read is not a valid
representation of a floating - point number .
and convert it to a floating-point number.
The result is unspecified if the line read is not a valid
representation of a floating-point number. *)
* { 7 General output functions }
type open_flag =
* Opening modes for { ! } and { ! } .
val open_out : string -> out_channel
* Open the named file for writing , and return a new output channel
on that file , positionned at the beginning of the file . The
file is truncated to zero length if it already exists . It
is created if it does not already exists .
Raise [ Sys_error ] if the file could not be opened .
on that file, positionned at the beginning of the file. The
file is truncated to zero length if it already exists. It
is created if it does not already exists.
Raise [Sys_error] if the file could not be opened. *)
val open_out_bin : string -> out_channel
* Same as { ! Pervasives.open_out } , but the file is opened in binary mode ,
so that no translation takes place during writes . On operating
systems that do not distinguish between text mode and binary
mode , this function behaves like { ! Pervasives.open_out } .
so that no translation takes place during writes. On operating
systems that do not distinguish between text mode and binary
mode, this function behaves like {!Pervasives.open_out}. *)
val open_out_gen : open_flag list -> int -> string -> out_channel
* Open the named file for writing , as above . The extra argument [ mode ]
specify the opening mode . The extra argument [ perm ] specifies
the file permissions , in case the file must be created .
{ ! Pervasives.open_out } and { ! Pervasives.open_out_bin } are special
cases of this function .
specify the opening mode. The extra argument [perm] specifies
the file permissions, in case the file must be created.
{!Pervasives.open_out} and {!Pervasives.open_out_bin} are special
cases of this function. *)
val flush : out_channel -> unit
val flush_all : unit -> unit
val output_char : out_channel -> char -> unit
val output_string : out_channel -> string -> unit
val output : out_channel -> string -> int -> int -> unit
* [ output oc buf pos len ] writes [ len ] characters from string [ buf ] ,
starting at offset [ pos ] , to the given output channel [ oc ] .
Raise [ Invalid_argument " output " ] if [ pos ] and [ len ] do not
designate a valid substring of [ buf ] .
starting at offset [pos], to the given output channel [oc].
Raise [Invalid_argument "output"] if [pos] and [len] do not
designate a valid substring of [buf]. *)
val output_byte : out_channel -> int -> unit
* Write one 8 - bit integer ( as the single character with that code )
on the given output channel . The given integer is taken modulo
256 .
on the given output channel. The given integer is taken modulo
256. *)
val output_binary_int : out_channel -> int -> unit
* Write one integer in binary format ( 4 bytes , big - endian )
on the given output channel .
The given integer is taken modulo 2{^32 } .
The only reliable way to read it back is through the
{ ! Pervasives.input_binary_int } function . The format is compatible across
all machines for a given version of .
on the given output channel.
The given integer is taken modulo 2{^32}.
The only reliable way to read it back is through the
{!Pervasives.input_binary_int} function. The format is compatible across
all machines for a given version of Objective Caml. *)
val output_value : out_channel -> 'a -> unit
val seek_out : out_channel -> int -> unit
* [ seek_out ] sets the current writing position to [ pos ]
for channel [ chan ] . This works only for regular files . On
files of other kinds ( such as terminals , pipes and sockets ) ,
the behavior is unspecified .
for channel [chan]. This works only for regular files. On
files of other kinds (such as terminals, pipes and sockets),
the behavior is unspecified. *)
val pos_out : out_channel -> int
val out_channel_length : out_channel -> int
val close_out : out_channel -> unit
* Close the given channel , flushing all buffered write operations .
Output functions raise a [ Sys_error ] exception when they are
applied to a closed output channel , except [ close_out ] and [ flush ] ,
which do nothing when applied to an already closed channel .
Note that [ close_out ] may raise [ ] if the operating
system signals an error when flushing or closing .
Output functions raise a [Sys_error] exception when they are
applied to a closed output channel, except [close_out] and [flush],
which do nothing when applied to an already closed channel.
Note that [close_out] may raise [Sys_error] if the operating
system signals an error when flushing or closing. *)
val close_out_noerr : out_channel -> unit
val set_binary_mode_out : out_channel -> bool -> unit
* [ set_binary_mode_out oc true ] sets the channel [ oc ] to binary
mode : no translations take place during output .
[ set_binary_mode_out oc false ] sets the channel [ oc ] to text
mode : depending on the operating system , some translations
may take place during output . For instance , under Windows ,
end - of - lines will be translated from [ \n ] to [ \r\n ] .
This function has no effect under operating systems that
do not distinguish between text mode and binary mode .
mode: no translations take place during output.
[set_binary_mode_out oc false] sets the channel [oc] to text
mode: depending on the operating system, some translations
may take place during output. For instance, under Windows,
end-of-lines will be translated from [\n] to [\r\n].
This function has no effect under operating systems that
do not distinguish between text mode and binary mode. *)
* { 7 General input functions }
val open_in : string -> in_channel
val open_in_bin : string -> in_channel
val open_in_gen : open_flag list -> int -> string -> in_channel
val input_char : in_channel -> char
* Read one character from the given input channel .
Raise [ End_of_file ] if there are no more characters to read .
Raise [End_of_file] if there are no more characters to read. *)
val input_line : in_channel -> string
val input : in_channel -> string -> int -> int -> int
* [ input ic buf pos len ] reads up to [ len ] characters from
the given channel [ ic ] , storing them in string [ buf ] , starting at
character number [ pos ] .
It returns the actual number of characters read , between 0 and
[ len ] ( inclusive ) .
A return value of 0 means that the end of file was reached .
A return value between 0 and [ len ] exclusive means that
not all requested [ len ] characters were read , either because
no more characters were available at that time , or because
the implementation found it convenient to do a partial read ;
[ input ] must be called again to read the remaining characters ,
if desired . ( See also { ! Pervasives.really_input } for reading
exactly [ len ] characters . )
Exception [ Invalid_argument " input " ] is raised if [ pos ] and [ len ]
do not designate a valid substring of [ buf ] .
the given channel [ic], storing them in string [buf], starting at
character number [pos].
It returns the actual number of characters read, between 0 and
[len] (inclusive).
A return value of 0 means that the end of file was reached.
A return value between 0 and [len] exclusive means that
not all requested [len] characters were read, either because
no more characters were available at that time, or because
the implementation found it convenient to do a partial read;
[input] must be called again to read the remaining characters,
if desired. (See also {!Pervasives.really_input} for reading
exactly [len] characters.)
Exception [Invalid_argument "input"] is raised if [pos] and [len]
do not designate a valid substring of [buf]. *)
val really_input : in_channel -> string -> int -> int -> unit
* [ really_input ic buf pos len ] reads [ len ] characters from channel [ ic ] ,
storing them in string [ buf ] , starting at character number [ pos ] .
Raise [ End_of_file ] if the end of file is reached before [ len ]
characters have been read .
Raise [ Invalid_argument " really_input " ] if
[ pos ] and [ len ] do not designate a valid substring of [ buf ] .
storing them in string [buf], starting at character number [pos].
Raise [End_of_file] if the end of file is reached before [len]
characters have been read.
Raise [Invalid_argument "really_input"] if
[pos] and [len] do not designate a valid substring of [buf]. *)
val input_byte : in_channel -> int
* Same as { ! Pervasives.input_char } , but return the 8 - bit integer representing
the character .
Raise [ End_of_file ] if an end of file was reached .
the character.
Raise [End_of_file] if an end of file was reached. *)
val input_binary_int : in_channel -> int
* Read an integer encoded in binary format ( 4 bytes , big - endian )
from the given input channel . See { ! Pervasives.output_binary_int } .
Raise [ End_of_file ] if an end of file was reached while reading the
integer .
from the given input channel. See {!Pervasives.output_binary_int}.
Raise [End_of_file] if an end of file was reached while reading the
integer. *)
val input_value : in_channel -> 'a
val seek_in : in_channel -> int -> unit
val pos_in : in_channel -> int
val in_channel_length : in_channel -> int
val close_in : in_channel -> unit
* Close the given channel . Input functions raise a [ Sys_error ]
exception when they are applied to a closed input channel ,
except [ close_in ] , which does nothing when applied to an already
closed channel . Note that [ close_in ] may raise [ ] if
the operating system signals an error .
exception when they are applied to a closed input channel,
except [close_in], which does nothing when applied to an already
closed channel. Note that [close_in] may raise [Sys_error] if
the operating system signals an error. *)
val close_in_noerr : in_channel -> unit
val set_binary_mode_in : in_channel -> bool -> unit
* [ set_binary_mode_in ic true ] sets the channel [ ic ] to binary
mode : no translations take place during input .
[ set_binary_mode_out ic false ] sets the channel [ ic ] to text
mode : depending on the operating system , some translations
may take place during input . For instance , under Windows ,
end - of - lines will be translated from [ \r\n ] to [ \n ] .
This function has no effect under operating systems that
do not distinguish between text mode and binary mode .
mode: no translations take place during input.
[set_binary_mode_out ic false] sets the channel [ic] to text
mode: depending on the operating system, some translations
may take place during input. For instance, under Windows,
end-of-lines will be translated from [\r\n] to [\n].
This function has no effect under operating systems that
do not distinguish between text mode and binary mode. *)
* { 7 Operations on large files }
module LargeFile :
sig
val seek_out : out_channel -> int64 -> unit
val pos_out : out_channel -> int64
val out_channel_length : out_channel -> int64
val seek_in : in_channel -> int64 -> unit
val pos_in : in_channel -> int64
val in_channel_length : in_channel -> int64
end
* Operations on large files .
This sub - module provides 64 - bit variants of the channel functions
that manipulate file positions and file sizes . By representing
positions and sizes by 64 - bit integers ( type [ int64 ] ) instead of
regular integers ( type [ int ] ) , these alternate functions allow
operating on files whose sizes are greater than [ max_int ] .
This sub-module provides 64-bit variants of the channel functions
that manipulate file positions and file sizes. By representing
positions and sizes by 64-bit integers (type [int64]) instead of
regular integers (type [int]), these alternate functions allow
operating on files whose sizes are greater than [max_int]. *)
type 'a ref = { mutable contents : 'a }
external ref : 'a -> 'a ref = "%makemutable"
external ( ! ) : 'a ref -> 'a = "%field0"
external ( := ) : 'a ref -> 'a -> unit = "%setfield0"
external incr : int ref -> unit = "%incr"
external decr : int ref -> unit = "%decr"
* { 6 Operations on format strings }
type ('a, 'b, 'c) format = ('a, 'b, 'c, 'c) format4
* Simplified type for format strings , included for backward compatibility
with earlier releases of [ ' a ] is the type of the parameters of the format ,
[ ' c ] is the result type for the " printf"-style function ,
and [ ' b ] is the type of the first argument given to
[ % a ] and [ % t ] printing functions .
with earlier releases of Objective Caml.
['a] is the type of the parameters of the format,
['c] is the result type for the "printf"-style function,
and ['b] is the type of the first argument given to
[%a] and [%t] printing functions. *)
val string_of_format : ('a, 'b, 'c, 'd) format4 -> string
external format_of_string :
('a, 'b, 'c, 'd) format4 -> ('a, 'b, 'c, 'd) format4 = "%identity"
val ( ^^ ) :
('a, 'b, 'c, 'd) format4 -> ('d, 'b, 'c, 'e) format4 ->
('a, 'b, 'c, 'e) format4;;
* { 6 Program termination }
val exit : int -> 'a
* Terminate the process , returning the given status code
to the operating system : usually 0 to indicate no errors ,
and a small positive integer to indicate failure .
All open output channels are flushed with flush_all .
An implicit [ exit 0 ] is performed each time a program
terminates normally . An implicit [ exit 2 ] is performed if the program
terminates early because of an uncaught exception .
to the operating system: usually 0 to indicate no errors,
and a small positive integer to indicate failure.
All open output channels are flushed with flush_all.
An implicit [exit 0] is performed each time a program
terminates normally. An implicit [exit 2] is performed if the program
terminates early because of an uncaught exception. *)
val at_exit : (unit -> unit) -> unit
* Register the given function to be called at program
termination time . The functions registered with [ at_exit ]
will be called when the program executes { ! Pervasives.exit } ,
or terminates , either normally or because of an uncaught exception .
The functions are called in ` ` last in , first out '' order :
the function most recently added with [ at_exit ] is called first .
termination time. The functions registered with [at_exit]
will be called when the program executes {!Pervasives.exit},
or terminates, either normally or because of an uncaught exception.
The functions are called in ``last in, first out'' order:
the function most recently added with [at_exit] is called first. *)
* { 6 For system use only , not for the casual user }
val valid_float_lexem : string -> string
val unsafe_really_input : in_channel -> string -> int -> int -> unit
val do_at_exit : unit -> unit
|
9590cfa45bb7e13263340f43adb233dfc4d722a9772333438c1a12bfd25f8675 | joewilliams/erl_geo_dns | geo_dns_sup.erl | -module(geo_dns_sup).
-behaviour(supervisor).
-export([start_link/0, init/1]).
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
init(_) ->
{ok, Port} = application:get_env(geo_dns, port),
{ok, Host} = application:get_env(geo_dns, host),
GeoDNSSpec =
[
{geo_dns_udp, {geo_dns_udp, start_link, [Host, Port]}, permanent, brutal_kill, worker, [geo_dns_udp]}
],
io:format("starting: ~p~n", [GeoDNSSpec]),
{ok, {{one_for_one, 1, 1}, GeoDNSSpec}}.
| null | https://raw.githubusercontent.com/joewilliams/erl_geo_dns/682c3925959db61ead99f13160ef8bd77486a871/apps/geo_dns/src/geo_dns_sup.erl | erlang | -module(geo_dns_sup).
-behaviour(supervisor).
-export([start_link/0, init/1]).
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
init(_) ->
{ok, Port} = application:get_env(geo_dns, port),
{ok, Host} = application:get_env(geo_dns, host),
GeoDNSSpec =
[
{geo_dns_udp, {geo_dns_udp, start_link, [Host, Port]}, permanent, brutal_kill, worker, [geo_dns_udp]}
],
io:format("starting: ~p~n", [GeoDNSSpec]),
{ok, {{one_for_one, 1, 1}, GeoDNSSpec}}.
| |
ba70b1881657c23d32e56a92de47325fca1c562a10496e3d9a331962f4970eaf | eugeneia/athens | streams.lisp | #+xcvb (module (:depends-on ("package")))
(in-package :trivial-gray-streams)
(defclass fundamental-stream (impl-specific-gray:fundamental-stream) ())
(defclass fundamental-input-stream
(fundamental-stream impl-specific-gray:fundamental-input-stream) ())
(defclass fundamental-output-stream
(fundamental-stream impl-specific-gray:fundamental-output-stream) ())
(defclass fundamental-character-stream
(fundamental-stream impl-specific-gray:fundamental-character-stream) ())
(defclass fundamental-binary-stream
(fundamental-stream impl-specific-gray:fundamental-binary-stream) ())
(defclass fundamental-character-input-stream
(fundamental-input-stream fundamental-character-stream
impl-specific-gray:fundamental-character-input-stream) ())
(defclass fundamental-character-output-stream
(fundamental-output-stream fundamental-character-stream
impl-specific-gray:fundamental-character-output-stream) ())
(defclass fundamental-binary-input-stream
(fundamental-input-stream fundamental-binary-stream
impl-specific-gray:fundamental-binary-input-stream) ())
(defclass fundamental-binary-output-stream
(fundamental-output-stream fundamental-binary-stream
impl-specific-gray:fundamental-binary-output-stream) ())
(defgeneric stream-read-sequence
(stream sequence start end &key &allow-other-keys))
(defgeneric stream-write-sequence
(stream sequence start end &key &allow-other-keys))
(defgeneric stream-file-position (stream))
(defgeneric (setf stream-file-position) (newval stream))
;;; Default methods for stream-read/write-sequence.
;;;
;;; It would be nice to implement default methods
;;; in trivial gray streams, maybe borrowing the code
from some of CL implementations . But now , for
;;; simplicity we will fallback to default implementation
;;; of the implementation-specific analogue function which calls us.
(defmethod stream-read-sequence ((stream fundamental-input-stream) seq start end &key)
(declare (ignore seq start end))
'fallback)
(defmethod stream-write-sequence ((stream fundamental-output-stream) seq start end &key)
(declare (ignore seq start end))
'fallback)
(defmacro or-fallback (&body body)
`(let ((result ,@body))
(if (eq result (quote fallback))
(call-next-method)
result)))
;; Implementations should provide this default method, I believe, but
;; at least sbcl and allegro don't.
(defmethod stream-terpri ((stream fundamental-output-stream))
(write-char #\newline stream))
;; stream-file-position could be specialized to
;; fundamental-stream, but to support backward
;; compatibility with flexi-streams, we specialize
;; it on T. The reason: flexi-streams calls stream-file-position
;; for non-gray stream:
;; -streams/issues/4
(defmethod stream-file-position ((stream t))
nil)
(defmethod (setf stream-file-position) (newval (stream t))
(declare (ignore newval))
nil)
#+abcl
(progn
(defmethod gray-streams:stream-read-sequence
((s fundamental-input-stream) seq &optional start end)
(or-fallback (stream-read-sequence s seq (or start 0) (or end (length seq)))))
(defmethod gray-streams:stream-write-sequence
((s fundamental-output-stream) seq &optional start end)
(or-fallback (stream-write-sequence s seq (or start 0) (or end (length seq)))))
(defmethod gray-streams:stream-write-string
((stream xp::xp-structure) string &optional (start 0) (end (length string)))
(xp::write-string+ string stream start end))
#+#.(cl:if (cl:and (cl:find-package :gray-streams)
(cl:find-symbol "STREAM-FILE-POSITION" :gray-streams))
'(:and)
'(:or))
(defmethod gray-streams:stream-file-position
((s fundamental-stream) &optional position)
(if position
(setf (stream-file-position s) position)
(stream-file-position s))))
#+allegro
(progn
(defmethod excl:stream-read-sequence
((s fundamental-input-stream) seq &optional start end)
(or-fallback (stream-read-sequence s seq (or start 0) (or end (length seq)))))
(defmethod excl:stream-write-sequence
((s fundamental-output-stream) seq &optional start end)
(or-fallback (stream-write-sequence s seq (or start 0) (or end (length seq)))))
(defmethod excl::stream-file-position
((stream fundamental-stream) &optional position)
(if position
(setf (stream-file-position stream) position)
(stream-file-position stream))))
Untill 2014 - 08 - 09 CMUCL did not have stream - file - position :
;; -lisp.net/cmucl/ticket/100
#+cmu
(eval-when (:compile-toplevel :load-toplevel :execute)
(when (find-symbol (string '#:stream-file-position) '#:ext)
(pushnew :cmu-has-stream-file-position *features*)))
#+cmu
(progn
(defmethod ext:stream-read-sequence
((s fundamental-input-stream) seq &optional start end)
(or-fallback (stream-read-sequence s seq (or start 0) (or end (length seq)))))
(defmethod ext:stream-write-sequence
((s fundamental-output-stream) seq &optional start end)
(or-fallback (stream-write-sequence s seq (or start 0) (or end (length seq)))))
#+cmu-has-stream-file-position
(defmethod ext:stream-file-position ((stream fundamental-stream))
(stream-file-position stream))
#+cmu-has-stream-file-position
(defmethod (setf ext:stream-file-position) (position (stream fundamental-stream))
(setf (stream-file-position stream) position)))
#+lispworks
(progn
(defmethod stream:stream-read-sequence
((s fundamental-input-stream) seq start end)
(or-fallback (stream-read-sequence s seq start end)))
(defmethod stream:stream-write-sequence
((s fundamental-output-stream) seq start end)
(or-fallback (stream-write-sequence s seq start end)))
(defmethod stream:stream-file-position ((stream fundamental-stream))
(stream-file-position stream))
(defmethod (setf stream:stream-file-position)
(newval (stream fundamental-stream))
(setf (stream-file-position stream) newval)))
#+openmcl
(progn
(defmethod ccl:stream-read-vector
((s fundamental-input-stream) seq start end)
(or-fallback (stream-read-sequence s seq start end)))
(defmethod ccl:stream-write-vector
((s fundamental-output-stream) seq start end)
(or-fallback (stream-write-sequence s seq start end)))
(defmethod ccl:stream-read-list ((s fundamental-input-stream) list count)
(or-fallback (stream-read-sequence s list 0 count)))
(defmethod ccl:stream-write-list ((s fundamental-output-stream) list count)
(or-fallback (stream-write-sequence s list 0 count)))
(defmethod ccl::stream-position ((stream fundamental-stream) &optional new-position)
(if new-position
(setf (stream-file-position stream) new-position)
(stream-file-position stream))))
up to version 2.43 there were no
;; stream-read-sequence, stream-write-sequence
functions in CLISP
#+clisp
(eval-when (:compile-toplevel :load-toplevel :execute)
(when (find-symbol (string '#:stream-read-sequence) '#:gray)
(pushnew :clisp-has-stream-read/write-sequence *features*)))
#+clisp
(progn
#+clisp-has-stream-read/write-sequence
(defmethod gray:stream-read-sequence
(seq (s fundamental-input-stream) &key start end)
(or-fallback (stream-read-sequence s seq (or start 0) (or end (length seq)))))
#+clisp-has-stream-read/write-sequence
(defmethod gray:stream-write-sequence
(seq (s fundamental-output-stream) &key start end)
(or-fallback (stream-write-sequence s seq (or start 0) (or end (length seq)))))
for old CLISP
(defmethod gray:stream-read-byte-sequence
((s fundamental-input-stream)
seq
&optional start end no-hang interactive)
(when no-hang
(error "this stream does not support the NO-HANG argument"))
(when interactive
(error "this stream does not support the INTERACTIVE argument"))
(or-fallback (stream-read-sequence s seq start end)))
(defmethod gray:stream-write-byte-sequence
((s fundamental-output-stream)
seq
&optional start end no-hang interactive)
(when no-hang
(error "this stream does not support the NO-HANG argument"))
(when interactive
(error "this stream does not support the INTERACTIVE argument"))
(or-fallback (stream-write-sequence s seq start end)))
(defmethod gray:stream-read-char-sequence
((s fundamental-input-stream) seq &optional start end)
(or-fallback (stream-read-sequence s seq start end)))
(defmethod gray:stream-write-char-sequence
((s fundamental-output-stream) seq &optional start end)
(or-fallback (stream-write-sequence s seq start end)))
end of old CLISP read / write - sequence support
(defmethod gray:stream-position ((stream fundamental-stream) position)
(if position
(setf (stream-file-position stream) position)
(stream-file-position stream))))
#+sbcl
(progn
(defmethod sb-gray:stream-read-sequence
((s fundamental-input-stream) seq &optional start end)
(or-fallback (stream-read-sequence s seq (or start 0) (or end (length seq)))))
(defmethod sb-gray:stream-write-sequence
((s fundamental-output-stream) seq &optional start end)
(or-fallback (stream-write-sequence s seq (or start 0) (or end (length seq)))))
(defmethod sb-gray:stream-file-position
((stream fundamental-stream) &optional position)
(if position
(setf (stream-file-position stream) position)
(stream-file-position stream)))
SBCL extension :
(defmethod sb-gray:stream-line-length ((stream fundamental-stream))
80))
#+ecl
(progn
(defmethod gray::stream-file-position
((stream fundamental-stream) &optional position)
(if position
(setf (stream-file-position stream) position)
(stream-file-position stream)))
(defmethod gray:stream-read-sequence
((s fundamental-input-stream) seq &optional start end)
(or-fallback (stream-read-sequence s seq (or start 0) (or end (length seq)))))
(defmethod gray:stream-write-sequence
((s fundamental-output-stream) seq &optional start end)
(or-fallback (stream-write-sequence s seq (or start 0) (or end (length seq))))))
#+mocl
(progn
(defmethod gray:stream-read-sequence
((s fundamental-input-stream) seq &optional start end)
(or-fallback (stream-read-sequence s seq (or start 0) (or end (length seq)))))
(defmethod gray:stream-write-sequence
((s fundamental-output-stream) seq &optional start end)
(or-fallback (stream-write-sequence s seq (or start 0) (or end (length seq)))))
(defmethod gray:stream-file-position
((stream fundamental-stream) &optional position)
(if position
(setf (stream-file-position stream) position)
(stream-file-position stream))))
#+genera
(progn
(defmethod gray-streams:stream-read-sequence
((s fundamental-input-stream) seq &optional start end)
(or-fallback (stream-read-sequence s seq (or start 0) (or end (length seq)))))
(defmethod gray-streams:stream-write-sequence
((s fundamental-output-stream) seq &optional start end)
(or-fallback (stream-write-sequence s seq (or start 0) (or end (length seq)))))
(defmethod gray-streams:stream-file-position
((stream fundamental-stream))
(stream-file-position stream))
(defmethod (setf gray-streams:stream-file-position)
(position (stream fundamental-stream))
(setf (stream-file-position stream) position)))
;; deprecated
(defclass trivial-gray-stream-mixin () ())
| null | https://raw.githubusercontent.com/eugeneia/athens/cc9d456edd3891b764b0fbf0202a3e2f58865cbf/quicklisp/dists/quicklisp/software/trivial-gray-streams-20180328-git/streams.lisp | lisp | Default methods for stream-read/write-sequence.
It would be nice to implement default methods
in trivial gray streams, maybe borrowing the code
simplicity we will fallback to default implementation
of the implementation-specific analogue function which calls us.
Implementations should provide this default method, I believe, but
at least sbcl and allegro don't.
stream-file-position could be specialized to
fundamental-stream, but to support backward
compatibility with flexi-streams, we specialize
it on T. The reason: flexi-streams calls stream-file-position
for non-gray stream:
-streams/issues/4
-lisp.net/cmucl/ticket/100
stream-read-sequence, stream-write-sequence
deprecated | #+xcvb (module (:depends-on ("package")))
(in-package :trivial-gray-streams)
(defclass fundamental-stream (impl-specific-gray:fundamental-stream) ())
(defclass fundamental-input-stream
(fundamental-stream impl-specific-gray:fundamental-input-stream) ())
(defclass fundamental-output-stream
(fundamental-stream impl-specific-gray:fundamental-output-stream) ())
(defclass fundamental-character-stream
(fundamental-stream impl-specific-gray:fundamental-character-stream) ())
(defclass fundamental-binary-stream
(fundamental-stream impl-specific-gray:fundamental-binary-stream) ())
(defclass fundamental-character-input-stream
(fundamental-input-stream fundamental-character-stream
impl-specific-gray:fundamental-character-input-stream) ())
(defclass fundamental-character-output-stream
(fundamental-output-stream fundamental-character-stream
impl-specific-gray:fundamental-character-output-stream) ())
(defclass fundamental-binary-input-stream
(fundamental-input-stream fundamental-binary-stream
impl-specific-gray:fundamental-binary-input-stream) ())
(defclass fundamental-binary-output-stream
(fundamental-output-stream fundamental-binary-stream
impl-specific-gray:fundamental-binary-output-stream) ())
(defgeneric stream-read-sequence
(stream sequence start end &key &allow-other-keys))
(defgeneric stream-write-sequence
(stream sequence start end &key &allow-other-keys))
(defgeneric stream-file-position (stream))
(defgeneric (setf stream-file-position) (newval stream))
from some of CL implementations . But now , for
(defmethod stream-read-sequence ((stream fundamental-input-stream) seq start end &key)
(declare (ignore seq start end))
'fallback)
(defmethod stream-write-sequence ((stream fundamental-output-stream) seq start end &key)
(declare (ignore seq start end))
'fallback)
(defmacro or-fallback (&body body)
`(let ((result ,@body))
(if (eq result (quote fallback))
(call-next-method)
result)))
(defmethod stream-terpri ((stream fundamental-output-stream))
(write-char #\newline stream))
(defmethod stream-file-position ((stream t))
nil)
(defmethod (setf stream-file-position) (newval (stream t))
(declare (ignore newval))
nil)
#+abcl
(progn
(defmethod gray-streams:stream-read-sequence
((s fundamental-input-stream) seq &optional start end)
(or-fallback (stream-read-sequence s seq (or start 0) (or end (length seq)))))
(defmethod gray-streams:stream-write-sequence
((s fundamental-output-stream) seq &optional start end)
(or-fallback (stream-write-sequence s seq (or start 0) (or end (length seq)))))
(defmethod gray-streams:stream-write-string
((stream xp::xp-structure) string &optional (start 0) (end (length string)))
(xp::write-string+ string stream start end))
#+#.(cl:if (cl:and (cl:find-package :gray-streams)
(cl:find-symbol "STREAM-FILE-POSITION" :gray-streams))
'(:and)
'(:or))
(defmethod gray-streams:stream-file-position
((s fundamental-stream) &optional position)
(if position
(setf (stream-file-position s) position)
(stream-file-position s))))
#+allegro
(progn
(defmethod excl:stream-read-sequence
((s fundamental-input-stream) seq &optional start end)
(or-fallback (stream-read-sequence s seq (or start 0) (or end (length seq)))))
(defmethod excl:stream-write-sequence
((s fundamental-output-stream) seq &optional start end)
(or-fallback (stream-write-sequence s seq (or start 0) (or end (length seq)))))
(defmethod excl::stream-file-position
((stream fundamental-stream) &optional position)
(if position
(setf (stream-file-position stream) position)
(stream-file-position stream))))
Untill 2014 - 08 - 09 CMUCL did not have stream - file - position :
#+cmu
(eval-when (:compile-toplevel :load-toplevel :execute)
(when (find-symbol (string '#:stream-file-position) '#:ext)
(pushnew :cmu-has-stream-file-position *features*)))
#+cmu
(progn
(defmethod ext:stream-read-sequence
((s fundamental-input-stream) seq &optional start end)
(or-fallback (stream-read-sequence s seq (or start 0) (or end (length seq)))))
(defmethod ext:stream-write-sequence
((s fundamental-output-stream) seq &optional start end)
(or-fallback (stream-write-sequence s seq (or start 0) (or end (length seq)))))
#+cmu-has-stream-file-position
(defmethod ext:stream-file-position ((stream fundamental-stream))
(stream-file-position stream))
#+cmu-has-stream-file-position
(defmethod (setf ext:stream-file-position) (position (stream fundamental-stream))
(setf (stream-file-position stream) position)))
#+lispworks
(progn
(defmethod stream:stream-read-sequence
((s fundamental-input-stream) seq start end)
(or-fallback (stream-read-sequence s seq start end)))
(defmethod stream:stream-write-sequence
((s fundamental-output-stream) seq start end)
(or-fallback (stream-write-sequence s seq start end)))
(defmethod stream:stream-file-position ((stream fundamental-stream))
(stream-file-position stream))
(defmethod (setf stream:stream-file-position)
(newval (stream fundamental-stream))
(setf (stream-file-position stream) newval)))
#+openmcl
(progn
(defmethod ccl:stream-read-vector
((s fundamental-input-stream) seq start end)
(or-fallback (stream-read-sequence s seq start end)))
(defmethod ccl:stream-write-vector
((s fundamental-output-stream) seq start end)
(or-fallback (stream-write-sequence s seq start end)))
(defmethod ccl:stream-read-list ((s fundamental-input-stream) list count)
(or-fallback (stream-read-sequence s list 0 count)))
(defmethod ccl:stream-write-list ((s fundamental-output-stream) list count)
(or-fallback (stream-write-sequence s list 0 count)))
(defmethod ccl::stream-position ((stream fundamental-stream) &optional new-position)
(if new-position
(setf (stream-file-position stream) new-position)
(stream-file-position stream))))
up to version 2.43 there were no
functions in CLISP
#+clisp
(eval-when (:compile-toplevel :load-toplevel :execute)
(when (find-symbol (string '#:stream-read-sequence) '#:gray)
(pushnew :clisp-has-stream-read/write-sequence *features*)))
#+clisp
(progn
#+clisp-has-stream-read/write-sequence
(defmethod gray:stream-read-sequence
(seq (s fundamental-input-stream) &key start end)
(or-fallback (stream-read-sequence s seq (or start 0) (or end (length seq)))))
#+clisp-has-stream-read/write-sequence
(defmethod gray:stream-write-sequence
(seq (s fundamental-output-stream) &key start end)
(or-fallback (stream-write-sequence s seq (or start 0) (or end (length seq)))))
for old CLISP
(defmethod gray:stream-read-byte-sequence
((s fundamental-input-stream)
seq
&optional start end no-hang interactive)
(when no-hang
(error "this stream does not support the NO-HANG argument"))
(when interactive
(error "this stream does not support the INTERACTIVE argument"))
(or-fallback (stream-read-sequence s seq start end)))
(defmethod gray:stream-write-byte-sequence
((s fundamental-output-stream)
seq
&optional start end no-hang interactive)
(when no-hang
(error "this stream does not support the NO-HANG argument"))
(when interactive
(error "this stream does not support the INTERACTIVE argument"))
(or-fallback (stream-write-sequence s seq start end)))
(defmethod gray:stream-read-char-sequence
((s fundamental-input-stream) seq &optional start end)
(or-fallback (stream-read-sequence s seq start end)))
(defmethod gray:stream-write-char-sequence
((s fundamental-output-stream) seq &optional start end)
(or-fallback (stream-write-sequence s seq start end)))
end of old CLISP read / write - sequence support
(defmethod gray:stream-position ((stream fundamental-stream) position)
(if position
(setf (stream-file-position stream) position)
(stream-file-position stream))))
#+sbcl
(progn
(defmethod sb-gray:stream-read-sequence
((s fundamental-input-stream) seq &optional start end)
(or-fallback (stream-read-sequence s seq (or start 0) (or end (length seq)))))
(defmethod sb-gray:stream-write-sequence
((s fundamental-output-stream) seq &optional start end)
(or-fallback (stream-write-sequence s seq (or start 0) (or end (length seq)))))
(defmethod sb-gray:stream-file-position
((stream fundamental-stream) &optional position)
(if position
(setf (stream-file-position stream) position)
(stream-file-position stream)))
SBCL extension :
(defmethod sb-gray:stream-line-length ((stream fundamental-stream))
80))
#+ecl
(progn
(defmethod gray::stream-file-position
((stream fundamental-stream) &optional position)
(if position
(setf (stream-file-position stream) position)
(stream-file-position stream)))
(defmethod gray:stream-read-sequence
((s fundamental-input-stream) seq &optional start end)
(or-fallback (stream-read-sequence s seq (or start 0) (or end (length seq)))))
(defmethod gray:stream-write-sequence
((s fundamental-output-stream) seq &optional start end)
(or-fallback (stream-write-sequence s seq (or start 0) (or end (length seq))))))
#+mocl
(progn
(defmethod gray:stream-read-sequence
((s fundamental-input-stream) seq &optional start end)
(or-fallback (stream-read-sequence s seq (or start 0) (or end (length seq)))))
(defmethod gray:stream-write-sequence
((s fundamental-output-stream) seq &optional start end)
(or-fallback (stream-write-sequence s seq (or start 0) (or end (length seq)))))
(defmethod gray:stream-file-position
((stream fundamental-stream) &optional position)
(if position
(setf (stream-file-position stream) position)
(stream-file-position stream))))
#+genera
(progn
(defmethod gray-streams:stream-read-sequence
((s fundamental-input-stream) seq &optional start end)
(or-fallback (stream-read-sequence s seq (or start 0) (or end (length seq)))))
(defmethod gray-streams:stream-write-sequence
((s fundamental-output-stream) seq &optional start end)
(or-fallback (stream-write-sequence s seq (or start 0) (or end (length seq)))))
(defmethod gray-streams:stream-file-position
((stream fundamental-stream))
(stream-file-position stream))
(defmethod (setf gray-streams:stream-file-position)
(position (stream fundamental-stream))
(setf (stream-file-position stream) position)))
(defclass trivial-gray-stream-mixin () ())
|
be05f040ded92b6479b77b31ba0dcd61f01ec08f7aca598fd75b100e6ef4a453 | AdRoll/rebar3_format | sort_arity_qualifiers_uppercase_names.erl | -module(sort_arity_qualifiers_uppercase_names).
-format #{sort_arity_qualifiers => true}.
-export(['SECOND_FUNCTION'/3, 'ABC_FIRST_FUNCTION'/1, 'SECOND_FUNCTION'/2, lowercase_function/0]).
'ABC_FIRST_FUNCTION'(_) ->
ok.
'SECOND_FUNCTION'(_, _, _) ->
'SECOND_FUNCTION'().
'SECOND_FUNCTION'() ->
ok.
'SECOND_FUNCTION'(_, _) ->
ok.
lowercase_function() ->
ok.
| null | https://raw.githubusercontent.com/AdRoll/rebar3_format/7292c4e309491a19294ec5b2ff0b86a98b01d72c/test_app/src/sort_arity_qualifiers/sort_arity_qualifiers_uppercase_names.erl | erlang | -module(sort_arity_qualifiers_uppercase_names).
-format #{sort_arity_qualifiers => true}.
-export(['SECOND_FUNCTION'/3, 'ABC_FIRST_FUNCTION'/1, 'SECOND_FUNCTION'/2, lowercase_function/0]).
'ABC_FIRST_FUNCTION'(_) ->
ok.
'SECOND_FUNCTION'(_, _, _) ->
'SECOND_FUNCTION'().
'SECOND_FUNCTION'() ->
ok.
'SECOND_FUNCTION'(_, _) ->
ok.
lowercase_function() ->
ok.
| |
da599cf231aaf47ab79340d76b80ac64a0db9033912f9ce93bbcb9f775e0ab6b | geophf/1HaskellADay | Solution.hs | module Y2020.M07.D29.Solution where
-
" How many days from today until ... ? "
' Days ' are an interesting concept , thanks to The Real World(tm ) calendar .
So , computing number of days from here to there is not a metric calculation .
Today , we 're going to compute the number of days until ... April 15th , 2021 ,
say , or some other day in the next year , or so .
-
"How many days from today until ...?"
'Days' are an interesting concept, thanks to The Real World(tm) calendar.
So, computing number of days from here to there is not a metric calculation.
Today, we're going to compute the number of days until ... April 15th, 2021,
say, or some other day in the next year, or so.
--}
import Data.Time
import Data.Time.Calendar
import Data.Time.Clock
daysTo :: Day -> IO Integer
daysTo someDateInTheFuture =
getCurrentTime >>= return . diffDays someDateInTheFuture . utctDay
-
> > > daysTo ( read " 2021 - 04 - 15 " )
260
-
>>> daysTo (read "2021-04-15")
260
--}
| null | https://raw.githubusercontent.com/geophf/1HaskellADay/514792071226cd1e2ba7640af942667b85601006/exercises/HAD/Y2020/M07/D29/Solution.hs | haskell | }
} | module Y2020.M07.D29.Solution where
-
" How many days from today until ... ? "
' Days ' are an interesting concept , thanks to The Real World(tm ) calendar .
So , computing number of days from here to there is not a metric calculation .
Today , we 're going to compute the number of days until ... April 15th , 2021 ,
say , or some other day in the next year , or so .
-
"How many days from today until ...?"
'Days' are an interesting concept, thanks to The Real World(tm) calendar.
So, computing number of days from here to there is not a metric calculation.
Today, we're going to compute the number of days until ... April 15th, 2021,
say, or some other day in the next year, or so.
import Data.Time
import Data.Time.Calendar
import Data.Time.Clock
daysTo :: Day -> IO Integer
daysTo someDateInTheFuture =
getCurrentTime >>= return . diffDays someDateInTheFuture . utctDay
-
> > > daysTo ( read " 2021 - 04 - 15 " )
260
-
>>> daysTo (read "2021-04-15")
260
|
1f6cb28142569fb7f1b14352f0ef0c90f58924af01bcd2c4485bfc6f81a110fa | janegca/htdp2e | Exercise-229-WordGameWithLocalDefns.rkt | The first three lines of this file were inserted by . They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-intermediate-reader.ss" "lang")((modname Exercise-229-WordGameWithLocalDefns) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp")))))
Exercise 229 .
;
; Use a local expression to organize the functions for rearranging words
from Word Games , the Heart of the Problem .
; 1String List-of-words -> List-of-words
; insert the given 1String into every position in every word
; in the given list of words
(check-expect (insert-everywhere/in-all-words "d" (list (list "r" "e")
(list "e" "r")))
(list
(list "r" "e" "d")
(list "r" "d" "e")
(list "d" "r" "e")
(list "e" "r" "d")
(list "e" "d" "r")
(list "d" "e" "r")))
(define (insert-everywhere/in-all-words c low)
(local (
; 1String Word -> List-of-words
; insert the given 1String in the front, back and in-between each
; letter in the given word returning a list of new letter arrangements
(define (insert-in-word c n w)
(cond [(= 0 n) (list (insert c 0 w))]
[ else (append (list (insert c n w))
(insert-in-word c (- n 1) w))]))
; 1String Number Word -> Word
; inserts a character into a word at the given position
(define (insert c n w)
(cond [(= 0 n) (cons c w)]
[else (cons (first w) (insert c (- n 1) (rest w)))]))
)
; - IN -
(cond [(empty? low) '()]
[else (append (insert-in-word c (length (first low)) (first low))
(insert-everywhere/in-all-words c (rest low)))])))
| null | https://raw.githubusercontent.com/janegca/htdp2e/2d50378135edc2b8b1816204021f8763f8b2707b/03-Abstractions/Exercise-229-WordGameWithLocalDefns.rkt | racket | about the language level of this file in a form that our tools can easily process.
Use a local expression to organize the functions for rearranging words
1String List-of-words -> List-of-words
insert the given 1String into every position in every word
in the given list of words
1String Word -> List-of-words
insert the given 1String in the front, back and in-between each
letter in the given word returning a list of new letter arrangements
1String Number Word -> Word
inserts a character into a word at the given position
- IN - | The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-intermediate-reader.ss" "lang")((modname Exercise-229-WordGameWithLocalDefns) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp")))))
Exercise 229 .
from Word Games , the Heart of the Problem .
(check-expect (insert-everywhere/in-all-words "d" (list (list "r" "e")
(list "e" "r")))
(list
(list "r" "e" "d")
(list "r" "d" "e")
(list "d" "r" "e")
(list "e" "r" "d")
(list "e" "d" "r")
(list "d" "e" "r")))
(define (insert-everywhere/in-all-words c low)
(local (
(define (insert-in-word c n w)
(cond [(= 0 n) (list (insert c 0 w))]
[ else (append (list (insert c n w))
(insert-in-word c (- n 1) w))]))
(define (insert c n w)
(cond [(= 0 n) (cons c w)]
[else (cons (first w) (insert c (- n 1) (rest w)))]))
)
(cond [(empty? low) '()]
[else (append (insert-in-word c (length (first low)) (first low))
(insert-everywhere/in-all-words c (rest low)))])))
|
a613ae4909c66e962d231e9cbde45852842f10f530a01b149b189dc476dabd6f | sanette/oplot | logistique.ml | (* Oplot example of User object: bifurcation diagram for the logistic map *)
open Oplot.Plt
open Oplot.Points.Point2
let rec iterate r x_init i =
if i == 1 then x_init
else
let x = iterate r x_init (i - 1) in
r *. x *. (1.0 -. x)
let rec trace ~progress x0 x1 step v dev =
if x0 > x1 then ()
else
let imax = int_of_float (exp 4. *. (x0 -. 2.)) in
let rec loop i list =
if i >= imax then list
else
let x_init = Random.float 1.0 in
let x_final = iterate x0 x_init 500 in
let p = point (x0, x_final) in
loop (i + 1) (p :: list)
in
object_plot (Points (loop 0 [])) (Some v) ~dev;
set_color { r = x0 /. 4.; g = 0.5; b = 0.5 } ~dev;
if progress (* we force showing the picture in progress: *) then
if elapsed () mod 34 = 0 then (
copy_back_buffer ();
user_flush dev);
trace ~progress (x0 +. step) x1 step v dev
let logistique ?(progress = true) ~step v dev =
trace ~progress (fst v).x (snd v).x step v dev;
copy_back_buffer ()
thanks to this , the picture is not erased in the second display invocation
below when there is no Pause .
below when there is no Pause. *)
let v = view 2.4 0. 4. 1.
let a = axis 2.5 0.
let compute = text "Computing..." 2.7 0.3
let finished = text "Done." 2.9 0.3;;
display
[ v; a; compute; Pause 1; User (logistique ~step:0.001); finished; Freeze 0 ]
;;
display
[
v;
a;
compute;
Pause 1 ;
User (logistique ~progress:false ~step:0.001);
finished;
Freeze 0;
]
;;
(* BUG: Freeze prevents proper rescaling of the window *)
quit ()
| null | https://raw.githubusercontent.com/sanette/oplot/02b35d794fd0f42407a75edded11c2a58d7a3f29/bin/logistique.ml | ocaml | Oplot example of User object: bifurcation diagram for the logistic map
we force showing the picture in progress:
BUG: Freeze prevents proper rescaling of the window |
open Oplot.Plt
open Oplot.Points.Point2
let rec iterate r x_init i =
if i == 1 then x_init
else
let x = iterate r x_init (i - 1) in
r *. x *. (1.0 -. x)
let rec trace ~progress x0 x1 step v dev =
if x0 > x1 then ()
else
let imax = int_of_float (exp 4. *. (x0 -. 2.)) in
let rec loop i list =
if i >= imax then list
else
let x_init = Random.float 1.0 in
let x_final = iterate x0 x_init 500 in
let p = point (x0, x_final) in
loop (i + 1) (p :: list)
in
object_plot (Points (loop 0 [])) (Some v) ~dev;
set_color { r = x0 /. 4.; g = 0.5; b = 0.5 } ~dev;
if elapsed () mod 34 = 0 then (
copy_back_buffer ();
user_flush dev);
trace ~progress (x0 +. step) x1 step v dev
let logistique ?(progress = true) ~step v dev =
trace ~progress (fst v).x (snd v).x step v dev;
copy_back_buffer ()
thanks to this , the picture is not erased in the second display invocation
below when there is no Pause .
below when there is no Pause. *)
let v = view 2.4 0. 4. 1.
let a = axis 2.5 0.
let compute = text "Computing..." 2.7 0.3
let finished = text "Done." 2.9 0.3;;
display
[ v; a; compute; Pause 1; User (logistique ~step:0.001); finished; Freeze 0 ]
;;
display
[
v;
a;
compute;
Pause 1 ;
User (logistique ~progress:false ~step:0.001);
finished;
Freeze 0;
]
;;
quit ()
|
02b62721547a77f59615455ff4ec5c3264c25f497ba577d19728d8d8cf7917da | ucsd-progsys/nate | frx_toplevel.mli | (***********************************************************************)
(* *)
MLTk , Tcl / Tk interface of Objective Caml
(* *)
, , and
projet Cristal , INRIA Rocquencourt
, Kyoto University RIMS
(* *)
Copyright 2002 Institut National de Recherche en Informatique et
en Automatique and Kyoto University . All rights reserved .
This file is distributed under the terms of the GNU Library
General Public License , with the special exception on linking
(* described in file LICENSE found in the Objective Caml source tree. *)
(* *)
(***********************************************************************)
open Widget
val make_visible : Widget -> unit
| null | https://raw.githubusercontent.com/ucsd-progsys/nate/8b1267cd8b10283d8bc239d16a28c654a4cb8942/eval/sherrloc/easyocaml%2B%2B/otherlibs/labltk/frx/frx_toplevel.mli | ocaml | *********************************************************************
described in file LICENSE found in the Objective Caml source tree.
********************************************************************* | MLTk , Tcl / Tk interface of Objective Caml
, , and
projet Cristal , INRIA Rocquencourt
, Kyoto University RIMS
Copyright 2002 Institut National de Recherche en Informatique et
en Automatique and Kyoto University . All rights reserved .
This file is distributed under the terms of the GNU Library
General Public License , with the special exception on linking
open Widget
val make_visible : Widget -> unit
|
fe202bac22296ca8cb69e154bc5a85825f4da020ae8a1a5ab5b79fc8f3876012 | zaneli/hdbc-clickhouse | Server.hs | module Database.HDBC.ClickHouse.Protocol.PacketTypes.Server where
import Data.Word
hello :: Word8
hello = 0
blockOfData :: Word8
blockOfData = 1
exception :: Word8
exception = 2
progress :: Word8
progress = 3
pong :: Word8
pong = 4
endOfStream :: Word8
endOfStream = 5
profileInfo :: Word8
profileInfo = 6
totals :: Word8
totals = 7
extremes :: Word8
extremes = 8
tablesStatusResponse :: Word8
tablesStatusResponse = 9
log :: Word8
log = 10
tableColumns :: Word8
tableColumns = 11
| null | https://raw.githubusercontent.com/zaneli/hdbc-clickhouse/bf2ea2583ba5de63b943e95f597f17ac336920d8/src/Database/HDBC/ClickHouse/Protocol/PacketTypes/Server.hs | haskell | module Database.HDBC.ClickHouse.Protocol.PacketTypes.Server where
import Data.Word
hello :: Word8
hello = 0
blockOfData :: Word8
blockOfData = 1
exception :: Word8
exception = 2
progress :: Word8
progress = 3
pong :: Word8
pong = 4
endOfStream :: Word8
endOfStream = 5
profileInfo :: Word8
profileInfo = 6
totals :: Word8
totals = 7
extremes :: Word8
extremes = 8
tablesStatusResponse :: Word8
tablesStatusResponse = 9
log :: Word8
log = 10
tableColumns :: Word8
tableColumns = 11
| |
903e7595e2a11b35015e700527a51b75c9e97c20b1b817486250f825983ea764 | ZHaskell/stdio | BitTwiddle.hs | # LANGUAGE CPP #
# LANGUAGE MagicHash #
{-# LANGUAGE UnliftedFFITypes #-}
|
Module : Std . Data . PrimArray . BitTwiddle
Description : Primitive bits twiddling
Copyright : ( c ) , 2017 - 2018
License : BSD
Maintainer :
Stability : experimental
Portability : non - portable
This module implement some bit twiddling with ghc primitives .
We currently did n't use functions from this module though : the performance is not
catching up c version yet . But this module and relevant benchmarks are kept in hope
that once we have fully SIMD support in GHC , we might optimize these functions further
to compete with c.
Reference :
* /~seander/bithacks.html
* -check-for-zero-byte.html
Module : Std.Data.PrimArray.BitTwiddle
Description : Primitive bits twiddling
Copyright : (c) Dong Han, 2017-2018
License : BSD
Maintainer :
Stability : experimental
Portability : non-portable
This module implement some bit twiddling with ghc primitives.
We currently didn't use functions from this module though: the performance is not
catching up c version yet. But this module and relevant benchmarks are kept in hope
that once we have fully SIMD support in GHC, we might optimize these functions further
to compete with c.
Reference:
* /~seander/bithacks.html
* -check-for-zero-byte.html
-}
module Std.Data.PrimArray.BitTwiddle where
import GHC.Prim
import GHC.Types
import GHC.Word
import Data.Primitive.PrimArray
-- we need to know word size
#include "MachDeps.h"
#if SIZEOF_HSWORD == 4
# define CAST_OFFSET_WORD_TO_BYTE(x) (x `uncheckedIShiftL#` 2#)
# define CAST_OFFSET_BYTE_TO_WORD(x) (x `uncheckedIShiftRA#` 2#)
#else
# define CAST_OFFSET_WORD_TO_BYTE(x) (x `uncheckedIShiftL#` 3#)
# define CAST_OFFSET_BYTE_TO_WORD(x) (x `uncheckedIShiftRA#` 3#)
#endif
isOffsetAligned# :: Int# -> Bool
# INLINE isOffsetAligned # #
isOffsetAligned# s# = isTrue# ((SIZEOF_HSWORD# -# 1#) `andI#` s# ==# 0#)
mkMask# :: Word# -> Word#
# INLINE mkMask # #
mkMask# w8# =
#if SIZEOF_HSWORD == 4
let w16# = w8# `or#` (w8# `uncheckedShiftL#` 8#)
in w16# `or#` (w16# `uncheckedShiftL#` 16#)
#else
let w16# = w8# `or#` (w8# `uncheckedShiftL#` 8#)
w32# = w16# `or#` (w16# `uncheckedShiftL#` 16#)
in w32# `or#` (w32# `uncheckedShiftL#` 32#)
#endif
-- -check-for-zero-byte.html
--
nullByteMagic# :: Word# -> Word#
# INLINE nullByteMagic # #
nullByteMagic# w# =
#if SIZEOF_HSWORD == 4
(w# `minusWord#` 0x01010101##) `and#` (not# w#) `and#` 0x80808080##
#else
(w# `minusWord#` 0x0101010101010101##) `and#` (not# w#) `and#` 0x8080808080808080##
#endif
-- | Search a word8 in array.
--
-- Currently this function is ~4 times slow than c version, so we didn't use it.
--
memchr :: PrimArray Word8 -- array
-> Word8 -- target
-> Int -- start offset
-> Int -- search length
-> Int
# INLINE memchr #
memchr (PrimArray ba#) (W8# c#) (I# s#) (I# siz#) =
I# (memchr# ba# c# s# siz#)
| The unboxed version of ' memchr '
--
memchr# :: ByteArray# -> Word# -> Int# -> Int# -> Int#
# NOINLINE memchr # #
memchr# ba# c# s# siz# = beforeAlignedLoop# ba# c# s# (s# +# siz#)
where
beforeAlignedLoop# :: ByteArray# -> Word# -> Int# -> Int# -> Int#
beforeAlignedLoop# ba# c# s# end#
| isTrue# (s# >=# end#) = -1#
| isTrue# (c# `eqWord#` indexWord8Array# ba# s#) = s#
| isOffsetAligned# s# = alignedLoop# ba# (mkMask# c#)
CAST_OFFSET_BYTE_TO_WORD(s#)
CAST_OFFSET_BYTE_TO_WORD(end#)
end#
| otherwise = beforeAlignedLoop# ba# c# (s# +# 1#) end#
alignedLoop# :: ByteArray# -> Word# -> Int# -> Int# -> Int# -> Int#
alignedLoop# ba# mask# s# end# end_#
| isTrue# (s# >=# end#) = afterAlignedLoop# ba# (mask# `and#` 0xFF##)
CAST_OFFSET_WORD_TO_BYTE(s#)
end_#
| otherwise = case indexWordArray# ba# s# of
w# ->
case nullByteMagic# (mask# `xor#` w#) of
0## -> alignedLoop# ba# mask# (s# +# 1#) end# end_#
_ -> afterAlignedLoop# ba# (mask# `and#` 0xFF##)
CAST_OFFSET_WORD_TO_BYTE(s#)
end_#
afterAlignedLoop# :: ByteArray# -> Word# -> Int# -> Int# -> Int#
afterAlignedLoop# ba# c# s# end#
| isTrue# (s# >=# end#) = -1#
| isTrue# (c# `eqWord#` indexWord8Array# ba# s#) = s#
| otherwise = afterAlignedLoop# ba# c# (s# +# 1#) end#
| Search a array in reverse order .
--
This function is used in @elemIndexEnd@ , since there 's no c equivalent ( memrchr ) on OSX .
--
memchrReverse :: PrimArray Word8 -- array
-> Word8 -- target
-> Int -- start offset
-> Int -- search length
-> Int
# INLINE memchrReverse #
memchrReverse (PrimArray ba#) (W8# c#) (I# s#) (I# siz#) =
I# (memchr# ba# c# s# siz#)
-- | The unboxed version of 'memchrReverse'
--
memchrReverse# :: ByteArray# -> Word# -> Int# -> Int# -> Int#
# NOINLINE memchrReverse # #
memchrReverse# ba# c# s# siz# = beforeAlignedLoop# ba# c# s# (s# -# siz#)
where
beforeAlignedLoop# :: ByteArray# -> Word# -> Int# -> Int# -> Int#
beforeAlignedLoop# ba# c# s# end#
| isTrue# (s# <# end#) = -1#
| isTrue# (c# `eqWord#` indexWord8Array# ba# s#) = s#
| isOffsetAligned# s# = alignedLoop# ba# (mkMask# c#)
CAST_OFFSET_BYTE_TO_WORD(s#)
CAST_OFFSET_BYTE_TO_WORD(end#)
end#
| otherwise = beforeAlignedLoop# ba# c# (s# -# 1#) end#
alignedLoop# :: ByteArray# -> Word# -> Int# -> Int# -> Int# -> Int#
alignedLoop# ba# mask# s# end# end_#
| isTrue# (s# <# end#) = afterAlignedLoop# ba# (mask# `and#` 0xFF##)
CAST_OFFSET_WORD_TO_BYTE(s#)
end_#
| otherwise = case indexWordArray# ba# s# of
w# ->
case nullByteMagic# (mask# `xor#` w#) of
0## -> alignedLoop# ba# mask# (s# -# 1#) end# end_#
_ -> afterAlignedLoop# ba# (mask# `and#` 0xFF##)
CAST_OFFSET_WORD_TO_BYTE(s#)
end_#
afterAlignedLoop# :: ByteArray# -> Word# -> Int# -> Int# -> Int#
afterAlignedLoop# ba# c# s# end#
| isTrue# (s# <# end#) = -1#
| isTrue# (c# `eqWord#` indexWord8Array# ba# s#) = s#
| otherwise = afterAlignedLoop# ba# c# (s# -# 1#) end#
--------------------------------------------------------------------------------
| null | https://raw.githubusercontent.com/ZHaskell/stdio/7887b9413dc9feb957ddcbea96184f904cf37c12/std-data/Std/Data/PrimArray/BitTwiddle.hs | haskell | # LANGUAGE UnliftedFFITypes #
we need to know word size
-check-for-zero-byte.html
| Search a word8 in array.
Currently this function is ~4 times slow than c version, so we didn't use it.
array
target
start offset
search length
array
target
start offset
search length
| The unboxed version of 'memchrReverse'
------------------------------------------------------------------------------ | # LANGUAGE CPP #
# LANGUAGE MagicHash #
|
Module : Std . Data . PrimArray . BitTwiddle
Description : Primitive bits twiddling
Copyright : ( c ) , 2017 - 2018
License : BSD
Maintainer :
Stability : experimental
Portability : non - portable
This module implement some bit twiddling with ghc primitives .
We currently did n't use functions from this module though : the performance is not
catching up c version yet . But this module and relevant benchmarks are kept in hope
that once we have fully SIMD support in GHC , we might optimize these functions further
to compete with c.
Reference :
* /~seander/bithacks.html
* -check-for-zero-byte.html
Module : Std.Data.PrimArray.BitTwiddle
Description : Primitive bits twiddling
Copyright : (c) Dong Han, 2017-2018
License : BSD
Maintainer :
Stability : experimental
Portability : non-portable
This module implement some bit twiddling with ghc primitives.
We currently didn't use functions from this module though: the performance is not
catching up c version yet. But this module and relevant benchmarks are kept in hope
that once we have fully SIMD support in GHC, we might optimize these functions further
to compete with c.
Reference:
* /~seander/bithacks.html
* -check-for-zero-byte.html
-}
module Std.Data.PrimArray.BitTwiddle where
import GHC.Prim
import GHC.Types
import GHC.Word
import Data.Primitive.PrimArray
#include "MachDeps.h"
#if SIZEOF_HSWORD == 4
# define CAST_OFFSET_WORD_TO_BYTE(x) (x `uncheckedIShiftL#` 2#)
# define CAST_OFFSET_BYTE_TO_WORD(x) (x `uncheckedIShiftRA#` 2#)
#else
# define CAST_OFFSET_WORD_TO_BYTE(x) (x `uncheckedIShiftL#` 3#)
# define CAST_OFFSET_BYTE_TO_WORD(x) (x `uncheckedIShiftRA#` 3#)
#endif
isOffsetAligned# :: Int# -> Bool
# INLINE isOffsetAligned # #
isOffsetAligned# s# = isTrue# ((SIZEOF_HSWORD# -# 1#) `andI#` s# ==# 0#)
mkMask# :: Word# -> Word#
# INLINE mkMask # #
mkMask# w8# =
#if SIZEOF_HSWORD == 4
let w16# = w8# `or#` (w8# `uncheckedShiftL#` 8#)
in w16# `or#` (w16# `uncheckedShiftL#` 16#)
#else
let w16# = w8# `or#` (w8# `uncheckedShiftL#` 8#)
w32# = w16# `or#` (w16# `uncheckedShiftL#` 16#)
in w32# `or#` (w32# `uncheckedShiftL#` 32#)
#endif
nullByteMagic# :: Word# -> Word#
# INLINE nullByteMagic # #
nullByteMagic# w# =
#if SIZEOF_HSWORD == 4
(w# `minusWord#` 0x01010101##) `and#` (not# w#) `and#` 0x80808080##
#else
(w# `minusWord#` 0x0101010101010101##) `and#` (not# w#) `and#` 0x8080808080808080##
#endif
-> Int
# INLINE memchr #
memchr (PrimArray ba#) (W8# c#) (I# s#) (I# siz#) =
I# (memchr# ba# c# s# siz#)
| The unboxed version of ' memchr '
memchr# :: ByteArray# -> Word# -> Int# -> Int# -> Int#
# NOINLINE memchr # #
memchr# ba# c# s# siz# = beforeAlignedLoop# ba# c# s# (s# +# siz#)
where
beforeAlignedLoop# :: ByteArray# -> Word# -> Int# -> Int# -> Int#
beforeAlignedLoop# ba# c# s# end#
| isTrue# (s# >=# end#) = -1#
| isTrue# (c# `eqWord#` indexWord8Array# ba# s#) = s#
| isOffsetAligned# s# = alignedLoop# ba# (mkMask# c#)
CAST_OFFSET_BYTE_TO_WORD(s#)
CAST_OFFSET_BYTE_TO_WORD(end#)
end#
| otherwise = beforeAlignedLoop# ba# c# (s# +# 1#) end#
alignedLoop# :: ByteArray# -> Word# -> Int# -> Int# -> Int# -> Int#
alignedLoop# ba# mask# s# end# end_#
| isTrue# (s# >=# end#) = afterAlignedLoop# ba# (mask# `and#` 0xFF##)
CAST_OFFSET_WORD_TO_BYTE(s#)
end_#
| otherwise = case indexWordArray# ba# s# of
w# ->
case nullByteMagic# (mask# `xor#` w#) of
0## -> alignedLoop# ba# mask# (s# +# 1#) end# end_#
_ -> afterAlignedLoop# ba# (mask# `and#` 0xFF##)
CAST_OFFSET_WORD_TO_BYTE(s#)
end_#
afterAlignedLoop# :: ByteArray# -> Word# -> Int# -> Int# -> Int#
afterAlignedLoop# ba# c# s# end#
| isTrue# (s# >=# end#) = -1#
| isTrue# (c# `eqWord#` indexWord8Array# ba# s#) = s#
| otherwise = afterAlignedLoop# ba# c# (s# +# 1#) end#
| Search a array in reverse order .
This function is used in @elemIndexEnd@ , since there 's no c equivalent ( memrchr ) on OSX .
-> Int
# INLINE memchrReverse #
memchrReverse (PrimArray ba#) (W8# c#) (I# s#) (I# siz#) =
I# (memchr# ba# c# s# siz#)
memchrReverse# :: ByteArray# -> Word# -> Int# -> Int# -> Int#
# NOINLINE memchrReverse # #
memchrReverse# ba# c# s# siz# = beforeAlignedLoop# ba# c# s# (s# -# siz#)
where
beforeAlignedLoop# :: ByteArray# -> Word# -> Int# -> Int# -> Int#
beforeAlignedLoop# ba# c# s# end#
| isTrue# (s# <# end#) = -1#
| isTrue# (c# `eqWord#` indexWord8Array# ba# s#) = s#
| isOffsetAligned# s# = alignedLoop# ba# (mkMask# c#)
CAST_OFFSET_BYTE_TO_WORD(s#)
CAST_OFFSET_BYTE_TO_WORD(end#)
end#
| otherwise = beforeAlignedLoop# ba# c# (s# -# 1#) end#
alignedLoop# :: ByteArray# -> Word# -> Int# -> Int# -> Int# -> Int#
alignedLoop# ba# mask# s# end# end_#
| isTrue# (s# <# end#) = afterAlignedLoop# ba# (mask# `and#` 0xFF##)
CAST_OFFSET_WORD_TO_BYTE(s#)
end_#
| otherwise = case indexWordArray# ba# s# of
w# ->
case nullByteMagic# (mask# `xor#` w#) of
0## -> alignedLoop# ba# mask# (s# -# 1#) end# end_#
_ -> afterAlignedLoop# ba# (mask# `and#` 0xFF##)
CAST_OFFSET_WORD_TO_BYTE(s#)
end_#
afterAlignedLoop# :: ByteArray# -> Word# -> Int# -> Int# -> Int#
afterAlignedLoop# ba# c# s# end#
| isTrue# (s# <# end#) = -1#
| isTrue# (c# `eqWord#` indexWord8Array# ba# s#) = s#
| otherwise = afterAlignedLoop# ba# c# (s# -# 1#) end#
|
50b9d17bbbd74662e202bddfc74a1d392d6a929b9ce063496923914a653746fb | fulcrologic/semantic-ui-wrapper | ui_menu_menu.cljc | (ns com.fulcrologic.semantic-ui.collections.menu.ui-menu-menu
(:require
[com.fulcrologic.semantic-ui.factory-helpers :as h]
#?(:cljs ["semantic-ui-react$MenuMenu" :as MenuMenu])))
(def ui-menu-menu
"A menu can contain a sub menu.
Props:
- as (elementType): An element type to render as (string or function).
- children (node): Primary content.
- className (string): Additional classes.
- content (custom): Shorthand for primary content.
- position (enum): A sub menu can take left or right position. (left, right)"
#?(:cljs (h/factory-apply MenuMenu)))
| null | https://raw.githubusercontent.com/fulcrologic/semantic-ui-wrapper/7bd53f445bc4ca7e052c69596dc089282671df6c/src/main/com/fulcrologic/semantic_ui/collections/menu/ui_menu_menu.cljc | clojure | (ns com.fulcrologic.semantic-ui.collections.menu.ui-menu-menu
(:require
[com.fulcrologic.semantic-ui.factory-helpers :as h]
#?(:cljs ["semantic-ui-react$MenuMenu" :as MenuMenu])))
(def ui-menu-menu
"A menu can contain a sub menu.
Props:
- as (elementType): An element type to render as (string or function).
- children (node): Primary content.
- className (string): Additional classes.
- content (custom): Shorthand for primary content.
- position (enum): A sub menu can take left or right position. (left, right)"
#?(:cljs (h/factory-apply MenuMenu)))
| |
d513a917df07c611fa64b96dcb48f02a71eaea14496a2fee7233da58a6f43b75 | travelping/capwap | capwap_config_http.erl | Copyright ( C ) 2013 - 2023 , Travelping GmbH < >
%% This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation , either version 3 of the License , or
%% (at your option) any later version.
%% This program is distributed in the hope that it will be useful,
%% but WITHOUT ANY WARRANTY; without even the implied warranty of
%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
%% GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
%% along with this program. If not, see </>.
-module(capwap_config_http).
%%-behaviour(capwap_config_provider).
-export([wtp_init_config/2, wtp_config/1,
wtp_radio_config/3]).
-ifdef(TEST).
-export([transform_values/1]).
-endif.
-include("capwap_config.hrl").
-define(DEFAULT_HTTP, "").
wtp_init_config(CN, Opts) ->
URL = proplists:get_value(url, Opts, ?DEFAULT_HTTP),
JSON = request(<<"/", CN/binary>>, URL),
true = validate_config(JSON),
Config = maps:get(config, JSON, []),
Res = transform_values(Config),
{ok, {CN, capwap_config:'#frommap-wtp'(Res)}}.
wtp_config({_CN, Cfg}) ->
Cfg#wtp{radios = undefined}.
wtp_radio_config({_CN, #wtp{radios = Radios}}, RadioId, _RadioType) ->
#wtp_radio{} = lists:keyfind(RadioId, #wtp_radio.radio_id, Radios).
request(Path, Opts) ->
HttpServer = list_to_binary(Opts),
Http = <<HttpServer/binary, Path/binary>>,
case hackney:request(get, Http, []) of
{ok, 200, _Headers, ClientRef} ->
{ok, Body} = hackney:body(ClientRef),
jsx:decode(Body, [return_maps, {labels, existing_atom}]);
_ ->
exometer:update([capwap, ac, error_wtp_http_config_count], 1),
throw({error, get_http_config_wtp})
end.
validate_config(#{type := <<"wtp-config">>,
version := <<"1.0">>}) ->
true;
validate_config(_) ->
false.
akm_suite(<<"psk">>) -> 'PSK';
akm_suite(<<"ft-psk">>) -> 'FT-PSK';
akm_suite(<<"wpa">>) -> '802.1x';
akm_suite(<<"ft-wpa">>) -> 'FT-802.1x'.
encode_cipher_suite(Suite) ->
Atom = erlang:binary_to_existing_atom(Suite, utf8),
<<(capwap_packet:encode_cipher_suite(Atom)):32>>.
transform_values(Values) ->
maps:fold(
fun(K0, V0, M) ->
{K1, V1} = transform_value(K0, V0),
maps:put(K1, V1, M)
end, #{}, Values).
transform_value(radio_type, V) ->
{radio_type, [erlang:binary_to_existing_atom(RT, utf8) || RT <- V]};
transform_value(operation_mode, V) ->
{operation_mode, erlang:binary_to_existing_atom(V, utf8)};
transform_value(short_preamble, V) ->
{short_preamble, erlang:binary_to_existing_atom(V, utf8)};
transform_value(channel_assessment, V) ->
{channel_assessment, erlang:binary_to_existing_atom(V, utf8)};
transform_value(diversity, V) ->
{diversity, erlang:binary_to_existing_atom(V, utf8)};
transform_value(combiner, V) ->
{combiner, erlang:binary_to_existing_atom(V, utf8)};
transform_value(mac_mode, V) ->
{mac_mode, erlang:binary_to_existing_atom(V, utf8)};
transform_value(suppress_ssid, true) ->
{suppress_ssid, 1};
transform_value(suppress_ssid, false) ->
{suppress_ssid, 0};
transform_value(capabilities, <<"0x", V/binary>>) ->
{capabilities, binary_to_integer(V,16)};
transform_value(management_frame_protection, V)
when not is_boolean(V) ->
{management_frame_protection, erlang:binary_to_existing_atom(V, utf8)};
transform_value(group_cipher_suite, V) ->
{group_cipher_suite, encode_cipher_suite(V)};
transform_value(cipher_suites, V) ->
{cipher_suites, [encode_cipher_suite(S) || S <- V]};
transform_value(group_mgmt_cipher_suite, V) ->
{group_mgmt_cipher_suite, erlang:binary_to_existing_atom(V, utf8)};
transform_value(akm_suites, V) ->
{akm_suites, [akm_suite(S) || S <- V]};
transform_value(radio, Radios) ->
{radios, [capwap_config:'#frommap-wtp_radio'(
transform_values(Radio)) || Radio <- Radios ]};
transform_value(wlans, WLANs) ->
{wlans, [capwap_config:'#frommap-wtp_wlan_config'(
transform_values(WLAN)) || WLAN <- WLANs ]};
transform_value(rsn, RSN) ->
{rsn, capwap_config:'#frommap-wtp_wlan_rsn'(transform_values(RSN))};
transform_value(K, V) ->
{K, V}.
| null | https://raw.githubusercontent.com/travelping/capwap/c2e503c5ad7d6b4c0ff3df2a4d5deed73d5f7c51/src/capwap_config_http.erl | erlang | 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 Affero General Public License for more details.
along with this program. If not, see </>.
-behaviour(capwap_config_provider). | Copyright ( C ) 2013 - 2023 , Travelping GmbH < >
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU Affero General Public License
-module(capwap_config_http).
-export([wtp_init_config/2, wtp_config/1,
wtp_radio_config/3]).
-ifdef(TEST).
-export([transform_values/1]).
-endif.
-include("capwap_config.hrl").
-define(DEFAULT_HTTP, "").
wtp_init_config(CN, Opts) ->
URL = proplists:get_value(url, Opts, ?DEFAULT_HTTP),
JSON = request(<<"/", CN/binary>>, URL),
true = validate_config(JSON),
Config = maps:get(config, JSON, []),
Res = transform_values(Config),
{ok, {CN, capwap_config:'#frommap-wtp'(Res)}}.
wtp_config({_CN, Cfg}) ->
Cfg#wtp{radios = undefined}.
wtp_radio_config({_CN, #wtp{radios = Radios}}, RadioId, _RadioType) ->
#wtp_radio{} = lists:keyfind(RadioId, #wtp_radio.radio_id, Radios).
request(Path, Opts) ->
HttpServer = list_to_binary(Opts),
Http = <<HttpServer/binary, Path/binary>>,
case hackney:request(get, Http, []) of
{ok, 200, _Headers, ClientRef} ->
{ok, Body} = hackney:body(ClientRef),
jsx:decode(Body, [return_maps, {labels, existing_atom}]);
_ ->
exometer:update([capwap, ac, error_wtp_http_config_count], 1),
throw({error, get_http_config_wtp})
end.
validate_config(#{type := <<"wtp-config">>,
version := <<"1.0">>}) ->
true;
validate_config(_) ->
false.
akm_suite(<<"psk">>) -> 'PSK';
akm_suite(<<"ft-psk">>) -> 'FT-PSK';
akm_suite(<<"wpa">>) -> '802.1x';
akm_suite(<<"ft-wpa">>) -> 'FT-802.1x'.
encode_cipher_suite(Suite) ->
Atom = erlang:binary_to_existing_atom(Suite, utf8),
<<(capwap_packet:encode_cipher_suite(Atom)):32>>.
transform_values(Values) ->
maps:fold(
fun(K0, V0, M) ->
{K1, V1} = transform_value(K0, V0),
maps:put(K1, V1, M)
end, #{}, Values).
transform_value(radio_type, V) ->
{radio_type, [erlang:binary_to_existing_atom(RT, utf8) || RT <- V]};
transform_value(operation_mode, V) ->
{operation_mode, erlang:binary_to_existing_atom(V, utf8)};
transform_value(short_preamble, V) ->
{short_preamble, erlang:binary_to_existing_atom(V, utf8)};
transform_value(channel_assessment, V) ->
{channel_assessment, erlang:binary_to_existing_atom(V, utf8)};
transform_value(diversity, V) ->
{diversity, erlang:binary_to_existing_atom(V, utf8)};
transform_value(combiner, V) ->
{combiner, erlang:binary_to_existing_atom(V, utf8)};
transform_value(mac_mode, V) ->
{mac_mode, erlang:binary_to_existing_atom(V, utf8)};
transform_value(suppress_ssid, true) ->
{suppress_ssid, 1};
transform_value(suppress_ssid, false) ->
{suppress_ssid, 0};
transform_value(capabilities, <<"0x", V/binary>>) ->
{capabilities, binary_to_integer(V,16)};
transform_value(management_frame_protection, V)
when not is_boolean(V) ->
{management_frame_protection, erlang:binary_to_existing_atom(V, utf8)};
transform_value(group_cipher_suite, V) ->
{group_cipher_suite, encode_cipher_suite(V)};
transform_value(cipher_suites, V) ->
{cipher_suites, [encode_cipher_suite(S) || S <- V]};
transform_value(group_mgmt_cipher_suite, V) ->
{group_mgmt_cipher_suite, erlang:binary_to_existing_atom(V, utf8)};
transform_value(akm_suites, V) ->
{akm_suites, [akm_suite(S) || S <- V]};
transform_value(radio, Radios) ->
{radios, [capwap_config:'#frommap-wtp_radio'(
transform_values(Radio)) || Radio <- Radios ]};
transform_value(wlans, WLANs) ->
{wlans, [capwap_config:'#frommap-wtp_wlan_config'(
transform_values(WLAN)) || WLAN <- WLANs ]};
transform_value(rsn, RSN) ->
{rsn, capwap_config:'#frommap-wtp_wlan_rsn'(transform_values(RSN))};
transform_value(K, V) ->
{K, V}.
|
21b7579c32ca388f5802f90d0b5f9c0e6ee6bc1b9cceb9eb467f70f6d35539e9 | jscrane/jvml | test_ex2.clj | (ns ml.test-ex2
(:use (clojure test)
(ml util testutil)
[ml.ex2 :only (init-ex2 cost predict training-accuracy)]
[ml.ex2-reg :only (init-ex2-reg reg-cost reg-accuracy)]))
(def approx (approximately 1e-3))
(deftest ex2
(let [{:keys [X y norm theta]} (init-ex2)]
(is (approx 0.693 (cost X y [0 0 0])))
(is (approx 0.2035 (cost X y theta)))
(is (approx 0.776 (predict theta norm [45 85])))
(is (approx 0.89 (training-accuracy X y theta)))))
(deftest ex2-reg
(let [{:keys [X y]} (init-ex2-reg)]
(is (approx 0.693 (reg-cost X y (zeroes 28))))
(is (approx 0.83 (reg-accuracy X y 1)))
(is (approx 0.746 (reg-accuracy X y 10)))
(is (approx 0.61 (reg-accuracy X y 100))))) | null | https://raw.githubusercontent.com/jscrane/jvml/844eb267150564a3a0f882edbbd505ce94924c8f/test/ml/test_ex2.clj | clojure | (ns ml.test-ex2
(:use (clojure test)
(ml util testutil)
[ml.ex2 :only (init-ex2 cost predict training-accuracy)]
[ml.ex2-reg :only (init-ex2-reg reg-cost reg-accuracy)]))
(def approx (approximately 1e-3))
(deftest ex2
(let [{:keys [X y norm theta]} (init-ex2)]
(is (approx 0.693 (cost X y [0 0 0])))
(is (approx 0.2035 (cost X y theta)))
(is (approx 0.776 (predict theta norm [45 85])))
(is (approx 0.89 (training-accuracy X y theta)))))
(deftest ex2-reg
(let [{:keys [X y]} (init-ex2-reg)]
(is (approx 0.693 (reg-cost X y (zeroes 28))))
(is (approx 0.83 (reg-accuracy X y 1)))
(is (approx 0.746 (reg-accuracy X y 10)))
(is (approx 0.61 (reg-accuracy X y 100))))) | |
598def30bd03b12bbb668a52d683fc46c26df1ece4ba44b89efe513c818ba199 | haskell/win32 | Semaphores.hs | module Main where
import Control.Concurrent
( forkIO, threadDelay )
import Control.Monad
( void )
import Data.Foldable
( for_ )
import System.Win32.Event
( waitForSingleObject )
import System.Win32.File
( closeHandle )
import System.Win32.Semaphore
( Semaphore(..), createSemaphore, releaseSemaphore )
main :: IO ()
main = do
(test_sem, ex1) <- mk_test_sem
(_, ex2) <- mk_test_sem
let sem_name = "win32-test-semaphore"
(sem, ex3) <- createSemaphore Nothing 2 3 (Just sem_name)
putStrLn (show ex1 ++ " " ++ show ex2 ++ " " ++ show ex3)
-- False True False
putStrLn "=========="
for_ [1,2,3] (run_thread sem)
finish : 1 , 2
putStrLn "=========="
void $ releaseSemaphore sem 3
finish : 3
threadDelay 5000 -- 5 ms
for_ [4,5,6,7] (run_thread sem)
finish : 4 , 5
threadDelay 1000 -- 1 ms
putStrLn "=========="
void $ releaseSemaphore sem 1
finish : 6
threadDelay 100000 -- 100 ms
putStrLn "=========="
closeHandle (semaphoreHandle test_sem)
closeHandle (semaphoreHandle sem)
run_thread :: Semaphore -> Int -> IO ()
run_thread sem i = do
threadDelay 1000 -- 1 ms
putStrLn ("start " ++ show i)
void $ forkIO $ do
res <- waitForSingleObject (semaphoreHandle sem) 50 -- 50 ms
putStrLn ("finish " ++ show i ++ ": " ++ show res)
mk_test_sem :: IO (Semaphore, Bool)
mk_test_sem = createSemaphore Nothing 1 1 (Just "test-sem")
| null | https://raw.githubusercontent.com/haskell/win32/3fb78d425b3934ac393a6570833ff0b68ec5a89f/tests/Semaphores.hs | haskell | False True False
5 ms
1 ms
100 ms
1 ms
50 ms | module Main where
import Control.Concurrent
( forkIO, threadDelay )
import Control.Monad
( void )
import Data.Foldable
( for_ )
import System.Win32.Event
( waitForSingleObject )
import System.Win32.File
( closeHandle )
import System.Win32.Semaphore
( Semaphore(..), createSemaphore, releaseSemaphore )
main :: IO ()
main = do
(test_sem, ex1) <- mk_test_sem
(_, ex2) <- mk_test_sem
let sem_name = "win32-test-semaphore"
(sem, ex3) <- createSemaphore Nothing 2 3 (Just sem_name)
putStrLn (show ex1 ++ " " ++ show ex2 ++ " " ++ show ex3)
putStrLn "=========="
for_ [1,2,3] (run_thread sem)
finish : 1 , 2
putStrLn "=========="
void $ releaseSemaphore sem 3
finish : 3
for_ [4,5,6,7] (run_thread sem)
finish : 4 , 5
putStrLn "=========="
void $ releaseSemaphore sem 1
finish : 6
putStrLn "=========="
closeHandle (semaphoreHandle test_sem)
closeHandle (semaphoreHandle sem)
run_thread :: Semaphore -> Int -> IO ()
run_thread sem i = do
putStrLn ("start " ++ show i)
void $ forkIO $ do
putStrLn ("finish " ++ show i ++ ": " ++ show res)
mk_test_sem :: IO (Semaphore, Bool)
mk_test_sem = createSemaphore Nothing 1 1 (Just "test-sem")
|
a6ac7127093ae639dd7e56b91d6932b3bed5498193912634d2324edca8346dc4 | fragnix/fragnix | Data.Text.Internal.Builder.hs | # LANGUAGE Haskell98 #
# LINE 1 " Data / Text / Internal / Builder.hs " #
# LANGUAGE BangPatterns , CPP , Rank2Types #
# OPTIONS_HADDOCK not - home #
-----------------------------------------------------------------------------
-- |
-- Module : Data.Text.Internal.Builder
Copyright : ( c ) 2013
( c ) 2010
-- License : BSD-style (see LICENSE)
--
Maintainer : < >
-- Stability : experimental
Portability : portable to Hugs and GHC
--
-- /Warning/: this is an internal module, and does not have a stable
-- API or name. Functions in this module may not check or enforce
-- preconditions expected by public modules. Use at your own risk!
--
-- Efficient construction of lazy @Text@ values. The principal
operations on a @Builder@ are @singleton@ , @fromText@ , and
@fromLazyText@ , which construct new builders , and ' mappend ' , which
concatenates two builders .
--
-- To get maximum performance when building lazy @Text@ values using a
-- builder, associate @mappend@ calls to the right. For example,
-- prefer
--
-- > singleton 'a' `mappend` (singleton 'b' `mappend` singleton 'c')
--
-- to
--
-- > singleton 'a' `mappend` singleton 'b' `mappend` singleton 'c'
--
-- as the latter associates @mappend@ to the left.
--
-----------------------------------------------------------------------------
module Data.Text.Internal.Builder
( -- * Public API
-- ** The Builder type
Builder
, toLazyText
, toLazyTextWith
-- ** Constructing Builders
, singleton
, fromText
, fromLazyText
, fromString
-- ** Flushing the buffer state
, flush
-- * Internal functions
, append'
, ensureFree
, writeN
) where
import Control.Monad.ST (ST, runST)
import Data.Monoid (Monoid(..))
import Data.Semigroup (Semigroup(..))
import Data.Text.Internal (Text(..))
import Data.Text.Internal.Lazy (smallChunkSize)
import Data.Text.Unsafe (inlineInterleaveST)
import Data.Text.Internal.Unsafe.Char (unsafeWrite)
import Prelude hiding (map, putChar)
import qualified Data.String as String
import qualified Data.Text as S
import qualified Data.Text.Array as A
import qualified Data.Text.Lazy as L
------------------------------------------------------------------------
-- | A @Builder@ is an efficient way to build lazy @Text@ values.
There are several functions for constructing builders , but only one
-- to inspect them: to extract any data, you have to turn them into
-- lazy @Text@ values using @toLazyText@.
--
-- Internally, a builder constructs a lazy @Text@ by filling arrays
-- piece by piece. As each buffer is filled, it is \'popped\' off, to
-- become a new chunk of the resulting lazy @Text@. All this is
-- hidden from the user of the @Builder@.
newtype Builder = Builder {
-- Invariant (from Data.Text.Lazy):
-- The lists include no null Texts.
runBuilder :: forall s. (Buffer s -> ST s [S.Text])
-> Buffer s
-> ST s [S.Text]
}
instance Semigroup Builder where
(<>) = append
{-# INLINE (<>) #-}
instance Monoid Builder where
mempty = empty
# INLINE mempty #
mappend = (<>) -- future-proof definition
# INLINE mappend #
mconcat = foldr mappend Data.Monoid.mempty
# INLINE mconcat #
instance String.IsString Builder where
fromString = fromString
{-# INLINE fromString #-}
instance Show Builder where
show = show . toLazyText
instance Eq Builder where
a == b = toLazyText a == toLazyText b
instance Ord Builder where
a <= b = toLazyText a <= toLazyText b
------------------------------------------------------------------------
-- | /O(1)./ The empty @Builder@, satisfying
--
-- * @'toLazyText' 'empty' = 'L.empty'@
--
empty :: Builder
empty = Builder (\ k buf -> k buf)
{-# INLINE empty #-}
-- | /O(1)./ A @Builder@ taking a single character, satisfying
--
-- * @'toLazyText' ('singleton' c) = 'L.singleton' c@
--
singleton :: Char -> Builder
singleton c = writeAtMost 2 $ \ marr o -> unsafeWrite marr o c
# INLINE singleton #
------------------------------------------------------------------------
| /O(1)./ The concatenation of two builders , an associative
-- operation with identity 'empty', satisfying
--
-- * @'toLazyText' ('append' x y) = 'L.append' ('toLazyText' x) ('toLazyText' y)@
--
append :: Builder -> Builder -> Builder
append (Builder f) (Builder g) = Builder (f . g)
{-# INLINE [0] append #-}
-- TODO: Experiment to find the right threshold.
copyLimit :: Int
copyLimit = 128
This function attempts to merge small @Text@ values instead of
-- treating each value as its own chunk. We may not always want this.
-- | /O(1)./ A @Builder@ taking a 'S.Text', satisfying
--
-- * @'toLazyText' ('fromText' t) = 'L.fromChunks' [t]@
--
fromText :: S.Text -> Builder
fromText t@(Text arr off l)
| S.null t = empty
| l <= copyLimit = writeN l $ \marr o -> A.copyI marr o arr off (l+o)
| otherwise = flush `append` mapBuilder (t :)
# INLINE [ 1 ] fromText #
{-# RULES
"fromText/pack" forall s .
fromText (S.pack s) = fromString s
#-}
-- | /O(1)./ A Builder taking a @String@, satisfying
--
-- * @'toLazyText' ('fromString' s) = 'L.fromChunks' [S.pack s]@
--
fromString :: String -> Builder
fromString str = Builder $ \k (Buffer p0 o0 u0 l0) ->
let loop !marr !o !u !l [] = k (Buffer marr o u l)
loop marr o u l s@(c:cs)
| l <= 1 = do
arr <- A.unsafeFreeze marr
let !t = Text arr o u
marr' <- A.new chunkSize
ts <- inlineInterleaveST (loop marr' 0 0 chunkSize s)
return $ t : ts
| otherwise = do
n <- unsafeWrite marr (o+u) c
loop marr o (u+n) (l-n) cs
in loop p0 o0 u0 l0 str
where
chunkSize = smallChunkSize
{-# INLINE fromString #-}
-- | /O(1)./ A @Builder@ taking a lazy @Text@, satisfying
--
-- * @'toLazyText' ('fromLazyText' t) = t@
--
fromLazyText :: L.Text -> Builder
fromLazyText ts = flush `append` mapBuilder (L.toChunks ts ++)
{-# INLINE fromLazyText #-}
------------------------------------------------------------------------
-- Our internal buffer type
data Buffer s = Buffer {-# UNPACK #-} !(A.MArray s)
{-# UNPACK #-} !Int -- offset
{-# UNPACK #-} !Int -- used units
{-# UNPACK #-} !Int -- length left
------------------------------------------------------------------------
-- | /O(n)./ Extract a lazy @Text@ from a @Builder@ with a default
-- buffer size. The construction work takes place if and when the
-- relevant part of the lazy @Text@ is demanded.
toLazyText :: Builder -> L.Text
toLazyText = toLazyTextWith smallChunkSize
-- | /O(n)./ Extract a lazy @Text@ from a @Builder@, using the given
-- size for the initial buffer. The construction work takes place if
-- and when the relevant part of the lazy @Text@ is demanded.
--
-- If the initial buffer is too small to hold all data, subsequent
-- buffers will be the default buffer size.
toLazyTextWith :: Int -> Builder -> L.Text
toLazyTextWith chunkSize m = L.fromChunks (runST $
newBuffer chunkSize >>= runBuilder (m `append` flush) (const (return [])))
-- | /O(1)./ Pop the strict @Text@ we have constructed so far, if any,
-- yielding a new chunk in the result lazy @Text@.
flush :: Builder
flush = Builder $ \ k buf@(Buffer p o u l) ->
if u == 0
then k buf
else do arr <- A.unsafeFreeze p
let !b = Buffer p (o+u) 0 l
!t = Text arr o u
ts <- inlineInterleaveST (k b)
return $! t : ts
# INLINE [ 1 ] flush #
-- defer inlining so that flush/flush rule may fire.
------------------------------------------------------------------------
-- | Sequence an ST operation on the buffer
withBuffer :: (forall s. Buffer s -> ST s (Buffer s)) -> Builder
withBuffer f = Builder $ \k buf -> f buf >>= k
# INLINE withBuffer #
-- | Get the size of the buffer
withSize :: (Int -> Builder) -> Builder
withSize f = Builder $ \ k buf@(Buffer _ _ _ l) ->
runBuilder (f l) k buf
{-# INLINE withSize #-}
-- | Map the resulting list of texts.
mapBuilder :: ([S.Text] -> [S.Text]) -> Builder
mapBuilder f = Builder (fmap f .)
------------------------------------------------------------------------
-- | Ensure that there are at least @n@ many elements available.
ensureFree :: Int -> Builder
ensureFree !n = withSize $ \ l ->
if n <= l
then empty
else flush `append'` withBuffer (const (newBuffer (max n smallChunkSize)))
{-# INLINE [0] ensureFree #-}
writeAtMost :: Int -> (forall s. A.MArray s -> Int -> ST s Int) -> Builder
writeAtMost n f = ensureFree n `append'` withBuffer (writeBuffer f)
{-# INLINE [0] writeAtMost #-}
| Ensure that @n@ many elements are available , and then use @f@ to
-- write some elements into the memory.
writeN :: Int -> (forall s. A.MArray s -> Int -> ST s ()) -> Builder
writeN n f = writeAtMost n (\ p o -> f p o >> return n)
# INLINE writeN #
writeBuffer :: (A.MArray s -> Int -> ST s Int) -> Buffer s -> ST s (Buffer s)
writeBuffer f (Buffer p o u l) = do
n <- f p (o+u)
return $! Buffer p o (u+n) (l-n)
# INLINE writeBuffer #
newBuffer :: Int -> ST s (Buffer s)
newBuffer size = do
arr <- A.new size
return $! Buffer arr 0 0 size
# INLINE newBuffer #
------------------------------------------------------------------------
-- Some nice rules for Builder
This function makes GHC understand that ' writeN ' and ' ensureFree '
-- are *not* recursive in the precense of the rewrite rules below.
This is not needed with GHC 7 + .
append' :: Builder -> Builder -> Builder
append' (Builder f) (Builder g) = Builder (f . g)
{-# INLINE append' #-}
# RULES
" append / writeAtMost " forall a b ( f::forall s. A.MArray s - > Int - > ST s Int )
( g::forall s. A.MArray s - > Int - > ST s Int ) ws .
append ( writeAtMost a f ) ( append ( writeAtMost b g ) ws ) =
append ( writeAtMost ( a+b ) ( o - > f marr o > > = \ n - >
g marr ( o+n ) > > = \ m - >
let s = n+m in s ` seq ` return s ) ) ws
" writeAtMost / writeAtMost " forall a b ( f::forall s. A.MArray s - > Int - > ST s Int )
( g::forall s. A.MArray s - > Int - > ST s Int ) .
append ( writeAtMost a f ) ( writeAtMost b g ) =
writeAtMost ( a+b ) ( o - > f marr o > > = \ n - >
g marr ( o+n ) > > = \ m - >
let s = n+m in s ` seq ` return s )
" ensureFree / ensureFree " forall a b .
append ( ensureFree a ) ( ensureFree b ) = ensureFree ( max a b )
" flush / flush "
append flush flush = flush
#
"append/writeAtMost" forall a b (f::forall s. A.MArray s -> Int -> ST s Int)
(g::forall s. A.MArray s -> Int -> ST s Int) ws.
append (writeAtMost a f) (append (writeAtMost b g) ws) =
append (writeAtMost (a+b) (\marr o -> f marr o >>= \ n ->
g marr (o+n) >>= \ m ->
let s = n+m in s `seq` return s)) ws
"writeAtMost/writeAtMost" forall a b (f::forall s. A.MArray s -> Int -> ST s Int)
(g::forall s. A.MArray s -> Int -> ST s Int).
append (writeAtMost a f) (writeAtMost b g) =
writeAtMost (a+b) (\marr o -> f marr o >>= \ n ->
g marr (o+n) >>= \ m ->
let s = n+m in s `seq` return s)
"ensureFree/ensureFree" forall a b .
append (ensureFree a) (ensureFree b) = ensureFree (max a b)
"flush/flush"
append flush flush = flush
#-}
| null | https://raw.githubusercontent.com/fragnix/fragnix/b9969e9c6366e2917a782f3ac4e77cce0835448b/tests/packages/application/Data.Text.Internal.Builder.hs | haskell | ---------------------------------------------------------------------------
|
Module : Data.Text.Internal.Builder
License : BSD-style (see LICENSE)
Stability : experimental
/Warning/: this is an internal module, and does not have a stable
API or name. Functions in this module may not check or enforce
preconditions expected by public modules. Use at your own risk!
Efficient construction of lazy @Text@ values. The principal
To get maximum performance when building lazy @Text@ values using a
builder, associate @mappend@ calls to the right. For example,
prefer
> singleton 'a' `mappend` (singleton 'b' `mappend` singleton 'c')
to
> singleton 'a' `mappend` singleton 'b' `mappend` singleton 'c'
as the latter associates @mappend@ to the left.
---------------------------------------------------------------------------
* Public API
** The Builder type
** Constructing Builders
** Flushing the buffer state
* Internal functions
----------------------------------------------------------------------
| A @Builder@ is an efficient way to build lazy @Text@ values.
to inspect them: to extract any data, you have to turn them into
lazy @Text@ values using @toLazyText@.
Internally, a builder constructs a lazy @Text@ by filling arrays
piece by piece. As each buffer is filled, it is \'popped\' off, to
become a new chunk of the resulting lazy @Text@. All this is
hidden from the user of the @Builder@.
Invariant (from Data.Text.Lazy):
The lists include no null Texts.
# INLINE (<>) #
future-proof definition
# INLINE fromString #
----------------------------------------------------------------------
| /O(1)./ The empty @Builder@, satisfying
* @'toLazyText' 'empty' = 'L.empty'@
# INLINE empty #
| /O(1)./ A @Builder@ taking a single character, satisfying
* @'toLazyText' ('singleton' c) = 'L.singleton' c@
----------------------------------------------------------------------
operation with identity 'empty', satisfying
* @'toLazyText' ('append' x y) = 'L.append' ('toLazyText' x) ('toLazyText' y)@
# INLINE [0] append #
TODO: Experiment to find the right threshold.
treating each value as its own chunk. We may not always want this.
| /O(1)./ A @Builder@ taking a 'S.Text', satisfying
* @'toLazyText' ('fromText' t) = 'L.fromChunks' [t]@
# RULES
"fromText/pack" forall s .
fromText (S.pack s) = fromString s
#
| /O(1)./ A Builder taking a @String@, satisfying
* @'toLazyText' ('fromString' s) = 'L.fromChunks' [S.pack s]@
# INLINE fromString #
| /O(1)./ A @Builder@ taking a lazy @Text@, satisfying
* @'toLazyText' ('fromLazyText' t) = t@
# INLINE fromLazyText #
----------------------------------------------------------------------
Our internal buffer type
# UNPACK #
# UNPACK #
offset
# UNPACK #
used units
# UNPACK #
length left
----------------------------------------------------------------------
| /O(n)./ Extract a lazy @Text@ from a @Builder@ with a default
buffer size. The construction work takes place if and when the
relevant part of the lazy @Text@ is demanded.
| /O(n)./ Extract a lazy @Text@ from a @Builder@, using the given
size for the initial buffer. The construction work takes place if
and when the relevant part of the lazy @Text@ is demanded.
If the initial buffer is too small to hold all data, subsequent
buffers will be the default buffer size.
| /O(1)./ Pop the strict @Text@ we have constructed so far, if any,
yielding a new chunk in the result lazy @Text@.
defer inlining so that flush/flush rule may fire.
----------------------------------------------------------------------
| Sequence an ST operation on the buffer
| Get the size of the buffer
# INLINE withSize #
| Map the resulting list of texts.
----------------------------------------------------------------------
| Ensure that there are at least @n@ many elements available.
# INLINE [0] ensureFree #
# INLINE [0] writeAtMost #
write some elements into the memory.
----------------------------------------------------------------------
Some nice rules for Builder
are *not* recursive in the precense of the rewrite rules below.
# INLINE append' # | # LANGUAGE Haskell98 #
# LINE 1 " Data / Text / Internal / Builder.hs " #
# LANGUAGE BangPatterns , CPP , Rank2Types #
# OPTIONS_HADDOCK not - home #
Copyright : ( c ) 2013
( c ) 2010
Maintainer : < >
Portability : portable to Hugs and GHC
operations on a @Builder@ are @singleton@ , @fromText@ , and
@fromLazyText@ , which construct new builders , and ' mappend ' , which
concatenates two builders .
module Data.Text.Internal.Builder
Builder
, toLazyText
, toLazyTextWith
, singleton
, fromText
, fromLazyText
, fromString
, flush
, append'
, ensureFree
, writeN
) where
import Control.Monad.ST (ST, runST)
import Data.Monoid (Monoid(..))
import Data.Semigroup (Semigroup(..))
import Data.Text.Internal (Text(..))
import Data.Text.Internal.Lazy (smallChunkSize)
import Data.Text.Unsafe (inlineInterleaveST)
import Data.Text.Internal.Unsafe.Char (unsafeWrite)
import Prelude hiding (map, putChar)
import qualified Data.String as String
import qualified Data.Text as S
import qualified Data.Text.Array as A
import qualified Data.Text.Lazy as L
There are several functions for constructing builders , but only one
newtype Builder = Builder {
runBuilder :: forall s. (Buffer s -> ST s [S.Text])
-> Buffer s
-> ST s [S.Text]
}
instance Semigroup Builder where
(<>) = append
instance Monoid Builder where
mempty = empty
# INLINE mempty #
# INLINE mappend #
mconcat = foldr mappend Data.Monoid.mempty
# INLINE mconcat #
instance String.IsString Builder where
fromString = fromString
instance Show Builder where
show = show . toLazyText
instance Eq Builder where
a == b = toLazyText a == toLazyText b
instance Ord Builder where
a <= b = toLazyText a <= toLazyText b
empty :: Builder
empty = Builder (\ k buf -> k buf)
singleton :: Char -> Builder
singleton c = writeAtMost 2 $ \ marr o -> unsafeWrite marr o c
# INLINE singleton #
| /O(1)./ The concatenation of two builders , an associative
append :: Builder -> Builder -> Builder
append (Builder f) (Builder g) = Builder (f . g)
copyLimit :: Int
copyLimit = 128
This function attempts to merge small @Text@ values instead of
fromText :: S.Text -> Builder
fromText t@(Text arr off l)
| S.null t = empty
| l <= copyLimit = writeN l $ \marr o -> A.copyI marr o arr off (l+o)
| otherwise = flush `append` mapBuilder (t :)
# INLINE [ 1 ] fromText #
fromString :: String -> Builder
fromString str = Builder $ \k (Buffer p0 o0 u0 l0) ->
let loop !marr !o !u !l [] = k (Buffer marr o u l)
loop marr o u l s@(c:cs)
| l <= 1 = do
arr <- A.unsafeFreeze marr
let !t = Text arr o u
marr' <- A.new chunkSize
ts <- inlineInterleaveST (loop marr' 0 0 chunkSize s)
return $ t : ts
| otherwise = do
n <- unsafeWrite marr (o+u) c
loop marr o (u+n) (l-n) cs
in loop p0 o0 u0 l0 str
where
chunkSize = smallChunkSize
fromLazyText :: L.Text -> Builder
fromLazyText ts = flush `append` mapBuilder (L.toChunks ts ++)
toLazyText :: Builder -> L.Text
toLazyText = toLazyTextWith smallChunkSize
toLazyTextWith :: Int -> Builder -> L.Text
toLazyTextWith chunkSize m = L.fromChunks (runST $
newBuffer chunkSize >>= runBuilder (m `append` flush) (const (return [])))
flush :: Builder
flush = Builder $ \ k buf@(Buffer p o u l) ->
if u == 0
then k buf
else do arr <- A.unsafeFreeze p
let !b = Buffer p (o+u) 0 l
!t = Text arr o u
ts <- inlineInterleaveST (k b)
return $! t : ts
# INLINE [ 1 ] flush #
withBuffer :: (forall s. Buffer s -> ST s (Buffer s)) -> Builder
withBuffer f = Builder $ \k buf -> f buf >>= k
# INLINE withBuffer #
withSize :: (Int -> Builder) -> Builder
withSize f = Builder $ \ k buf@(Buffer _ _ _ l) ->
runBuilder (f l) k buf
mapBuilder :: ([S.Text] -> [S.Text]) -> Builder
mapBuilder f = Builder (fmap f .)
ensureFree :: Int -> Builder
ensureFree !n = withSize $ \ l ->
if n <= l
then empty
else flush `append'` withBuffer (const (newBuffer (max n smallChunkSize)))
writeAtMost :: Int -> (forall s. A.MArray s -> Int -> ST s Int) -> Builder
writeAtMost n f = ensureFree n `append'` withBuffer (writeBuffer f)
| Ensure that @n@ many elements are available , and then use @f@ to
writeN :: Int -> (forall s. A.MArray s -> Int -> ST s ()) -> Builder
writeN n f = writeAtMost n (\ p o -> f p o >> return n)
# INLINE writeN #
writeBuffer :: (A.MArray s -> Int -> ST s Int) -> Buffer s -> ST s (Buffer s)
writeBuffer f (Buffer p o u l) = do
n <- f p (o+u)
return $! Buffer p o (u+n) (l-n)
# INLINE writeBuffer #
newBuffer :: Int -> ST s (Buffer s)
newBuffer size = do
arr <- A.new size
return $! Buffer arr 0 0 size
# INLINE newBuffer #
This function makes GHC understand that ' writeN ' and ' ensureFree '
This is not needed with GHC 7 + .
append' :: Builder -> Builder -> Builder
append' (Builder f) (Builder g) = Builder (f . g)
# RULES
" append / writeAtMost " forall a b ( f::forall s. A.MArray s - > Int - > ST s Int )
( g::forall s. A.MArray s - > Int - > ST s Int ) ws .
append ( writeAtMost a f ) ( append ( writeAtMost b g ) ws ) =
append ( writeAtMost ( a+b ) ( o - > f marr o > > = \ n - >
g marr ( o+n ) > > = \ m - >
let s = n+m in s ` seq ` return s ) ) ws
" writeAtMost / writeAtMost " forall a b ( f::forall s. A.MArray s - > Int - > ST s Int )
( g::forall s. A.MArray s - > Int - > ST s Int ) .
append ( writeAtMost a f ) ( writeAtMost b g ) =
writeAtMost ( a+b ) ( o - > f marr o > > = \ n - >
g marr ( o+n ) > > = \ m - >
let s = n+m in s ` seq ` return s )
" ensureFree / ensureFree " forall a b .
append ( ensureFree a ) ( ensureFree b ) = ensureFree ( max a b )
" flush / flush "
append flush flush = flush
#
"append/writeAtMost" forall a b (f::forall s. A.MArray s -> Int -> ST s Int)
(g::forall s. A.MArray s -> Int -> ST s Int) ws.
append (writeAtMost a f) (append (writeAtMost b g) ws) =
append (writeAtMost (a+b) (\marr o -> f marr o >>= \ n ->
g marr (o+n) >>= \ m ->
let s = n+m in s `seq` return s)) ws
"writeAtMost/writeAtMost" forall a b (f::forall s. A.MArray s -> Int -> ST s Int)
(g::forall s. A.MArray s -> Int -> ST s Int).
append (writeAtMost a f) (writeAtMost b g) =
writeAtMost (a+b) (\marr o -> f marr o >>= \ n ->
g marr (o+n) >>= \ m ->
let s = n+m in s `seq` return s)
"ensureFree/ensureFree" forall a b .
append (ensureFree a) (ensureFree b) = ensureFree (max a b)
"flush/flush"
append flush flush = flush
#-}
|
d745217acdaedecef5a127209164776d49354bee78b79b1c06ddab79a5620902 | borkdude/advent-of-cljc | jreighley.cljc | (ns aoc.y2018.d07.jreighley
(:require
[aoc.utils :as u :refer [deftest]]
[aoc.y2018.d07.data :refer [input answer-1 answer-2]]
[clojure.string :refer [split-lines]]
[clojure.test :refer [is testing]]))
(def sched
(delay
(let [raw (split-lines input)
precedent-keys (sort-by first (map #(vector (subs % 5 6) (subs % 36 37 ))raw))]
precedent-keys)))
(def all-nodes (sort (reduce into #{} @sched)))
(def remaining-nodes #(remove (set %) all-nodes))
(def jobtime (delay (zipmap all-nodes (range 61 (+ 60 27)))))
(defn find-parents [job unsat]
(->> (filter #(= (last %) job) unsat)
(map #(first %))))
(defn reduced-instructions [acc]
(remove #((set acc) (first %)) @sched))
(defn undependant [acc]
(filter #(empty? (find-parents % (reduced-instructions acc))) (remaining-nodes acc)))
(defn do-jobs [acc]
(let [new-acc (conj acc (first (undependant acc)))]
(if (= (count all-nodes) (count acc))
(apply str acc)
(recur new-acc))))
(defn solve-1 []
(do-jobs []))
PART 2
(defn sched-times [done ip tics]
(let [free-workers (- 5 (count ip))
wip (set (map first ip))
av-work (remove wip (undependant done))
new-work (->> (take free-workers av-work))
work-timer (vec (for [job new-work]
[job (+ tics (@jobtime job))]))
interum-ip (reduce conj ip work-timer)
next-tic (when (not-empty interum-ip) (apply min (map last interum-ip)))
next-done (reduce conj done (map first (filter #(= next-tic (last %)) interum-ip)))
next-ip (vec (remove #(= next-tic (last %)) interum-ip))]
(if (= (count done) 26)
tics
(recur next-done next-ip next-tic))))
(defn solve-2 []
(sched-times [] [] 0))
(deftest part-1
(is (= answer-1 (solve-1))))
(deftest part-2
(is (= answer-2 (solve-2))))
| null | https://raw.githubusercontent.com/borkdude/advent-of-cljc/17c8abb876b95ab01eee418f1da2e402e845c596/src/aoc/y2018/d07/jreighley.cljc | clojure | (ns aoc.y2018.d07.jreighley
(:require
[aoc.utils :as u :refer [deftest]]
[aoc.y2018.d07.data :refer [input answer-1 answer-2]]
[clojure.string :refer [split-lines]]
[clojure.test :refer [is testing]]))
(def sched
(delay
(let [raw (split-lines input)
precedent-keys (sort-by first (map #(vector (subs % 5 6) (subs % 36 37 ))raw))]
precedent-keys)))
(def all-nodes (sort (reduce into #{} @sched)))
(def remaining-nodes #(remove (set %) all-nodes))
(def jobtime (delay (zipmap all-nodes (range 61 (+ 60 27)))))
(defn find-parents [job unsat]
(->> (filter #(= (last %) job) unsat)
(map #(first %))))
(defn reduced-instructions [acc]
(remove #((set acc) (first %)) @sched))
(defn undependant [acc]
(filter #(empty? (find-parents % (reduced-instructions acc))) (remaining-nodes acc)))
(defn do-jobs [acc]
(let [new-acc (conj acc (first (undependant acc)))]
(if (= (count all-nodes) (count acc))
(apply str acc)
(recur new-acc))))
(defn solve-1 []
(do-jobs []))
PART 2
(defn sched-times [done ip tics]
(let [free-workers (- 5 (count ip))
wip (set (map first ip))
av-work (remove wip (undependant done))
new-work (->> (take free-workers av-work))
work-timer (vec (for [job new-work]
[job (+ tics (@jobtime job))]))
interum-ip (reduce conj ip work-timer)
next-tic (when (not-empty interum-ip) (apply min (map last interum-ip)))
next-done (reduce conj done (map first (filter #(= next-tic (last %)) interum-ip)))
next-ip (vec (remove #(= next-tic (last %)) interum-ip))]
(if (= (count done) 26)
tics
(recur next-done next-ip next-tic))))
(defn solve-2 []
(sched-times [] [] 0))
(deftest part-1
(is (= answer-1 (solve-1))))
(deftest part-2
(is (= answer-2 (solve-2))))
| |
2466eec8e7b8620beaea7cff5a54b9cb80a92078f4e4ef58fded5dfae8363bf2 | hverr/lxdfile | Main.hs | # LANGUAGE FlexibleContexts #
# LANGUAGE GeneralizedNewtypeDeriving #
module Main where
import Control.Monad.Except (ExceptT, MonadError, runExceptT, throwError)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Data.Monoid ((<>))
import Data.Version (showVersion)
import Options.Applicative
import System.Exit (exitFailure)
import Language.LXDFile (Image, baseImage)
import Language.LXDFile.InitScript.Types (InitScriptError)
import Language.LXDFile.Version (version)
import System.LXD.LXDFile.Launch (Profile, InitScriptContext(..))
import qualified Language.LXDFile as LXDFile
import qualified Language.LXDFile.InitScript as InitScript
import qualified System.LXD.LXDFile as LXDFile
^ Init script , context
data Command = BuildCommand FilePath String FilePath (Maybe Image) -- ^ LXDFile, image tag, base directory, and base image
| LaunchCommand String String Profile [InitScriptArg] -- ^ Image, container, context, profile, list of init scripts
| InjectCommand String [InitScriptArg] -- ^ Container, init scripts
| VersionCommand
newtype CmdT m a = CmdT { runCmdT :: ExceptT String m a }
deriving (Functor, Applicative, Monad, MonadIO, MonadError String)
buildCmd :: Mod CommandFields Command
buildCmd =
command "build" $ info (helper <*> cmd') $ progDesc "build an LXD image using an LXDFile"
where
cmd' = BuildCommand <$> strOption (short 'f' <> metavar "LXDFILE" <> value "lxdfile" <> help "location of the lxdfile")
<*> strArgument (metavar "NAME" <> help "name of the newly built image")
<*> strArgument (metavar "DIR" <> value "." <> help "base directory")
<*> option (Just <$> str) (long "from" <> metavar "IMAGE" <> value Nothing <> help "override the base image")
launchCmd :: Mod CommandFields Command
launchCmd =
command "launch" $ info (helper <*> cmd') $ progDesc "launch an LXD image with init scripts"
where
cmd' = LaunchCommand <$> strArgument (metavar "IMAGE" <> help "name of an LXD iamge")
<*> strArgument (metavar "CONTAINER" <> help "name of the created LXD container")
<*> option (Just <$> str) (short 'p' <> long "profile" <> value Nothing <> help "LXD profile for the launched container")
<*> many initScriptArg
injectCmd :: Mod CommandFields Command
injectCmd =
command "inject" $ info (helper <*> cmd') $ progDesc "inject init scripts in running containers"
where
cmd' = InjectCommand <$> strArgument (metavar "CONTAINER" <> help "name of the LXD container")
<*> many initScriptArg
initScriptArg :: Parser InitScriptArg
initScriptArg = parse <$> strOption (short 'i' <> metavar "SCRIPT[:CTX]" <> help "init script with optional context")
where
parse x = case break (== ':') x of
(a, []) -> InitScriptArg a "."
(a, [_]) -> InitScriptArg a "."
(a, _:b) -> InitScriptArg a b
versionCmd :: Mod CommandFields Command
versionCmd =
command "version" $ info (helper <*> cmd') $ progDesc "show the program version"
where
cmd' = pure VersionCommand
subcommand :: Parser Command
subcommand = subparser (buildCmd <> launchCmd <> injectCmd <> versionCmd)
main :: IO ()
main =
execParser opts >>= cmd . run
where
opts = info (helper <*> subcommand) $ progDesc "Automatically build and manage LXD images and containers."
cmd :: CmdT IO () -> IO ()
cmd action' = do
x <- runExceptT $ runCmdT action'
case x of Right () -> return ()
Left e -> do
putStrLn $ "error: " ++ e
exitFailure
run :: (MonadIO m, MonadError String m) => Command -> m ()
run (BuildCommand fp name dir base) = do
lxdfile <- liftIO (LXDFile.parseFile fp) >>= orErr "parse error"
let lxdfile' = case base of Nothing -> lxdfile
Just b -> lxdfile { baseImage = b }
LXDFile.build lxdfile' name dir
where
orErr pref = either (showErr pref) return
showErr pref e = throwError $ pref ++ ": " ++ show e
run (LaunchCommand image container profile isas) = do
scripts <- liftIO (sequence <$> mapM parseInitScriptContext isas) >>= orErr "parse error"
LXDFile.launch image container profile scripts
where
orErr pref = either (showErr pref) return
showErr pref e = throwError $ pref ++ ": " ++ show e
run (InjectCommand name isas) = do
scripts <- liftIO (sequence <$> mapM parseInitScriptContext isas) >>= orErr "parse error"
LXDFile.inject name scripts
where
orErr pref = either (showErr pref) return
showErr pref e = throwError $ pref ++ ": " ++ show e
run VersionCommand = liftIO . putStrLn $ showVersion version
parseInitScriptContext :: InitScriptArg -> IO (Either InitScriptError InitScriptContext)
parseInitScriptContext (InitScriptArg fp ctx) = do
v <- InitScript.parseFile fp
return $ InitScriptContext <$> v <*> pure ctx
| null | https://raw.githubusercontent.com/hverr/lxdfile/16c371b3ab3aff2ebc4bb1fc7f6a7c45f0b91b01/app/Main.hs | haskell | ^ LXDFile, image tag, base directory, and base image
^ Image, container, context, profile, list of init scripts
^ Container, init scripts | # LANGUAGE FlexibleContexts #
# LANGUAGE GeneralizedNewtypeDeriving #
module Main where
import Control.Monad.Except (ExceptT, MonadError, runExceptT, throwError)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Data.Monoid ((<>))
import Data.Version (showVersion)
import Options.Applicative
import System.Exit (exitFailure)
import Language.LXDFile (Image, baseImage)
import Language.LXDFile.InitScript.Types (InitScriptError)
import Language.LXDFile.Version (version)
import System.LXD.LXDFile.Launch (Profile, InitScriptContext(..))
import qualified Language.LXDFile as LXDFile
import qualified Language.LXDFile.InitScript as InitScript
import qualified System.LXD.LXDFile as LXDFile
^ Init script , context
| VersionCommand
newtype CmdT m a = CmdT { runCmdT :: ExceptT String m a }
deriving (Functor, Applicative, Monad, MonadIO, MonadError String)
buildCmd :: Mod CommandFields Command
buildCmd =
command "build" $ info (helper <*> cmd') $ progDesc "build an LXD image using an LXDFile"
where
cmd' = BuildCommand <$> strOption (short 'f' <> metavar "LXDFILE" <> value "lxdfile" <> help "location of the lxdfile")
<*> strArgument (metavar "NAME" <> help "name of the newly built image")
<*> strArgument (metavar "DIR" <> value "." <> help "base directory")
<*> option (Just <$> str) (long "from" <> metavar "IMAGE" <> value Nothing <> help "override the base image")
launchCmd :: Mod CommandFields Command
launchCmd =
command "launch" $ info (helper <*> cmd') $ progDesc "launch an LXD image with init scripts"
where
cmd' = LaunchCommand <$> strArgument (metavar "IMAGE" <> help "name of an LXD iamge")
<*> strArgument (metavar "CONTAINER" <> help "name of the created LXD container")
<*> option (Just <$> str) (short 'p' <> long "profile" <> value Nothing <> help "LXD profile for the launched container")
<*> many initScriptArg
injectCmd :: Mod CommandFields Command
injectCmd =
command "inject" $ info (helper <*> cmd') $ progDesc "inject init scripts in running containers"
where
cmd' = InjectCommand <$> strArgument (metavar "CONTAINER" <> help "name of the LXD container")
<*> many initScriptArg
initScriptArg :: Parser InitScriptArg
initScriptArg = parse <$> strOption (short 'i' <> metavar "SCRIPT[:CTX]" <> help "init script with optional context")
where
parse x = case break (== ':') x of
(a, []) -> InitScriptArg a "."
(a, [_]) -> InitScriptArg a "."
(a, _:b) -> InitScriptArg a b
versionCmd :: Mod CommandFields Command
versionCmd =
command "version" $ info (helper <*> cmd') $ progDesc "show the program version"
where
cmd' = pure VersionCommand
subcommand :: Parser Command
subcommand = subparser (buildCmd <> launchCmd <> injectCmd <> versionCmd)
main :: IO ()
main =
execParser opts >>= cmd . run
where
opts = info (helper <*> subcommand) $ progDesc "Automatically build and manage LXD images and containers."
cmd :: CmdT IO () -> IO ()
cmd action' = do
x <- runExceptT $ runCmdT action'
case x of Right () -> return ()
Left e -> do
putStrLn $ "error: " ++ e
exitFailure
run :: (MonadIO m, MonadError String m) => Command -> m ()
run (BuildCommand fp name dir base) = do
lxdfile <- liftIO (LXDFile.parseFile fp) >>= orErr "parse error"
let lxdfile' = case base of Nothing -> lxdfile
Just b -> lxdfile { baseImage = b }
LXDFile.build lxdfile' name dir
where
orErr pref = either (showErr pref) return
showErr pref e = throwError $ pref ++ ": " ++ show e
run (LaunchCommand image container profile isas) = do
scripts <- liftIO (sequence <$> mapM parseInitScriptContext isas) >>= orErr "parse error"
LXDFile.launch image container profile scripts
where
orErr pref = either (showErr pref) return
showErr pref e = throwError $ pref ++ ": " ++ show e
run (InjectCommand name isas) = do
scripts <- liftIO (sequence <$> mapM parseInitScriptContext isas) >>= orErr "parse error"
LXDFile.inject name scripts
where
orErr pref = either (showErr pref) return
showErr pref e = throwError $ pref ++ ": " ++ show e
run VersionCommand = liftIO . putStrLn $ showVersion version
parseInitScriptContext :: InitScriptArg -> IO (Either InitScriptError InitScriptContext)
parseInitScriptContext (InitScriptArg fp ctx) = do
v <- InitScript.parseFile fp
return $ InitScriptContext <$> v <*> pure ctx
|
67234a5517da7839067b6d60480303f47a1e4066f91bc6a7cbc6ba4456d17f33 | thoughtbot/carnival | User.hs | module Handler.User where
import Import
import Model.User ()
import Helper.Request
getUserR :: Handler Value
getUserR = do
allowCrossOrigin
user <- requireAuth
return $ object ["user" .= user]
| null | https://raw.githubusercontent.com/thoughtbot/carnival/1cd4bd02ea6884b86020029257ab69ec3892a168/Handler/User.hs | haskell | module Handler.User where
import Import
import Model.User ()
import Helper.Request
getUserR :: Handler Value
getUserR = do
allowCrossOrigin
user <- requireAuth
return $ object ["user" .= user]
| |
2487bde8dd23f14c444c20fec27336ecc71852a1797db4a441060855507804c3 | alexandergunnarson/quantum | io.cljc | (ns quantum.test.core.io) | null | https://raw.githubusercontent.com/alexandergunnarson/quantum/0c655af439734709566110949f9f2f482e468509/test/quantum/test/core/io.cljc | clojure | (ns quantum.test.core.io) | |
4f2c2473f43ce6684208fd5abc2bf6bd6d6a5464e5ec8b2501893e77c6ce5195 | TrustInSoft/tis-interpreter | ltl_output.mli | Modified by TrustInSoft
(**************************************************************************)
(* *)
This file is part of Aorai plug - in of Frama - C.
(* *)
Copyright ( C ) 2007 - 2015
CEA ( Commissariat à l'énergie atomique et aux énergies
(* alternatives) *)
( Institut National de Recherche en Informatique et en
(* Automatique) *)
INSA ( Institut National des Sciences Appliquees )
(* *)
(* 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 ) .
(* *)
(**************************************************************************)
$ I d : ltl_output.mli , v 1.2 2008 - 10 - 02 13:33:29 uid588 Exp $
val output : Ltlast.formula -> string -> unit
(*
Local Variables:
compile-command: "make -C ../../.."
End:
*)
| null | https://raw.githubusercontent.com/TrustInSoft/tis-interpreter/33132ce4a825494ea48bf2dd6fd03a56b62cc5c3/src/plugins/aorai/ltl_output.mli | ocaml | ************************************************************************
alternatives)
Automatique)
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:
| Modified by TrustInSoft
This file is part of Aorai plug - in of Frama - C.
Copyright ( C ) 2007 - 2015
CEA ( Commissariat à l'énergie atomique et aux énergies
( Institut National de Recherche en Informatique et en
INSA ( Institut National des Sciences Appliquees )
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 ) .
$ I d : ltl_output.mli , v 1.2 2008 - 10 - 02 13:33:29 uid588 Exp $
val output : Ltlast.formula -> string -> unit
|
8fe568e8dd49b9fdbbeac9f693c351f37866c1dd926d3526d0c2b6ff030d1c10 | tisnik/clojure-examples | core.clj | ;
( C ) Copyright 2016 , 2020 , 2021
;
; All rights reserved. This program and the accompanying materials
; are made available under the terms of the Eclipse Public License v1.0
; which accompanies this distribution, and is available at
-v10.html
;
; Contributors:
;
(ns consume-messages-3.core
(:require [jackdaw.client :as jc]
[jackdaw.client.log :as jl]
[clojure.pprint :as pp]))
(def consumer-config
{"bootstrap.servers" "localhost:9092"
"key.deserializer" "org.apache.kafka.common.serialization.StringDeserializer"
"value.deserializer" "org.apache.kafka.common.serialization.StringDeserializer"
"auto.offset.reset" "earliest"
"group.id" "group-A"})
(defn -main
[& args]
(with-open [consumer (-> (jc/consumer consumer-config)
(jc/subscribe [{:topic-name "test3"}]))]
(doseq [{:keys [key value partition timestamp offset]} (jl/log consumer 10)]
(println "key: " key)
(println "value: " value)
(println "partition: " partition)
(println "timestamp: " timestamp)
(println "offset: " offset))))
| null | https://raw.githubusercontent.com/tisnik/clojure-examples/a5f9d6119b62520b05da64b7929d07b832b957ab/kafka-consume-messages-3/src/consume_messages_3/core.clj | clojure |
All rights reserved. This program and the accompanying materials
are made available under the terms of the Eclipse Public License v1.0
which accompanies this distribution, and is available at
Contributors:
| ( C ) Copyright 2016 , 2020 , 2021
-v10.html
(ns consume-messages-3.core
(:require [jackdaw.client :as jc]
[jackdaw.client.log :as jl]
[clojure.pprint :as pp]))
(def consumer-config
{"bootstrap.servers" "localhost:9092"
"key.deserializer" "org.apache.kafka.common.serialization.StringDeserializer"
"value.deserializer" "org.apache.kafka.common.serialization.StringDeserializer"
"auto.offset.reset" "earliest"
"group.id" "group-A"})
(defn -main
[& args]
(with-open [consumer (-> (jc/consumer consumer-config)
(jc/subscribe [{:topic-name "test3"}]))]
(doseq [{:keys [key value partition timestamp offset]} (jl/log consumer 10)]
(println "key: " key)
(println "value: " value)
(println "partition: " partition)
(println "timestamp: " timestamp)
(println "offset: " offset))))
|
de15fd545fb0ab07a48f82ce2d4ac6ef435f71c1a699e5bd4659f006f4406b43 | capnproto/capnp-ocaml | defaults.ml | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* capnp - ocaml
*
* Copyright ( c ) 2013 - 2014 ,
* All rights reserved .
*
* Redistribution and use in source and binary forms , with or without
* modification , are permitted provided that the following conditions are met :
*
* 1 . Redistributions of source code must retain the above copyright notice ,
* this list of conditions and the following disclaimer .
*
* 2 . Redistributions in binary form must reproduce the above copyright
* notice , this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution .
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS "
* AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR
* CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS
* INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , IN
* CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING NEGLIGENCE OR OTHERWISE )
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE , EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE .
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* capnp-ocaml
*
* Copyright (c) 2013-2014, Paul Pelzl
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
******************************************************************************)
Management of default values for structs and lists . These values are
passed as a pointers to data stored in the PluginSchema message
generated by capnp compile . We will need to make a deep copy to transfer these
objects into a BytesStorage - based message , so we can easily serialize
the string contents right into the generated code .
It turns out to be relatively easy to handle default values for Builder
structs and lists , because the standard Builder behavior is to eliminate
nulls as early as possible : default values are immediately deep copied
into the Builder message so that the implementation can hold references
to valid data .
Surprisingly , the more difficult case is the Reader implementation .
The read - only semantics imply that we ca n't use the same approach here :
if there 's a null pointer , a dereference must return default data
which is physically stored in a different message . But because we have
functorized the code over the message type , we ca n't arbitrarily choose
to return default data stored in a * string * message ; we must return
default data stored in a message type which matches the functor parameter .
So when we instantiate the generated functor , we immediately construct
a new message of an appropriate type and deep - copy the default values
from string storage into this new message of the correct type .
passed as a pointers to data stored in the PluginSchema message
generated by capnp compile. We will need to make a deep copy to transfer these
objects into a BytesStorage-based message, so we can easily serialize
the string contents right into the generated code.
It turns out to be relatively easy to handle default values for Builder
structs and lists, because the standard Builder behavior is to eliminate
nulls as early as possible: default values are immediately deep copied
into the Builder message so that the implementation can hold references
to valid data.
Surprisingly, the more difficult case is the Reader implementation.
The read-only semantics imply that we can't use the same approach here:
if there's a null pointer, a dereference must return default data
which is physically stored in a different message. But because we have
functorized the code over the message type, we can't arbitrarily choose
to return default data stored in a *string* message; we must return
default data stored in a message type which matches the functor parameter.
So when we instantiate the generated functor, we immediately construct
a new message of an appropriate type and deep-copy the default values
from string storage into this new message of the correct type.
*)
module Uint64 = Stdint.Uint64
Workaround for missing . Bytes in Core 112.35.00
module CamlBytes = Bytes
module String = Base.String
module List = Base.List
module Int = Base.Int
module Copier = Capnp.Runtime.BuilderOps.Make(GenCommon.M)(GenCommon.M)
module M = GenCommon.M
module ListStorageType = Capnp.Runtime.ListStorageType
let sizeof_uint64 = 8
type abstract
type t = {
(* Message storage. *)
message : Capnp.Message.rw M.Message.t;
(* Array of structs which have been stored in the message, along with
their unique identifiers. *)
structs : (string * (Capnp.Message.rw, abstract) M.StructStorage.t) Res.Array.t;
(* Array of lists which have been stored in the message, along with
their unique identifiers. *)
lists : (string * Capnp.Message.rw M.ListStorage.t) Res.Array.t;
(* Array of pointers which have been stored in the message, along
with their unique identifiers. *)
pointers : (string * Capnp.Message.rw M.Slice.t) Res.Array.t;
}
type ident_t = string
let create () = {
message = M.Message.create 64;
structs = Res.Array.empty ();
lists = Res.Array.empty ();
pointers = Res.Array.empty ();
}
let make_ident node_id field_name =
"default_value_" ^ (Uint64.to_string node_id) ^ "_" ^ field_name
let builder_string_of_ident x = "_builder_" ^ x
let reader_string_of_ident x = "_reader_" ^ x
let add_struct defaults ident struct_storage =
let open M.StructStorage in
let data_words = struct_storage.data.M.Slice.len / sizeof_uint64 in
let pointer_words = struct_storage.pointers.M.Slice.len / sizeof_uint64 in
let struct_copy = Copier.deep_copy_struct ~src:struct_storage
~dest_message:defaults.message ~data_words ~pointer_words
in
Res.Array.add_one defaults.structs (ident, struct_copy)
let add_list defaults ident list_storage =
let list_copy = Copier.deep_copy_list ~src:list_storage
~dest_message:defaults.message ()
in
Res.Array.add_one defaults.lists (ident, list_copy)
let add_pointer defaults ident pointer_bytes =
let dest = M.Slice.alloc defaults.message sizeof_uint64 in
let () = Copier.deep_copy_pointer ~src:pointer_bytes ~dest in
Res.Array.add_one defaults.pointers (ident, dest)
(* Emit a semicolon-delimited string literal, wrapping at approximately the specified
word wrap boundary. We use the end-of-line-backslash to emit a string literal
which spans multiple lines. Escaped literals for binary data can contain lots
of backslashes, so we may stretch a line slightly to avoid breaking in the
middle of a literal backslash. *)
let emit_literal_seg (segment : string) (wrap : int) : string list =
let literal = Capnp.Runtime.Util.make_hex_literal segment in
let lines = Res.Array.empty () in
let rec loop line_start line_end =
let () = assert (line_end <= String.length literal) in
if line_end = String.length literal then
let last_line = String.sub literal ~pos:line_start ~len:(line_end - line_start) in
let () = Res.Array.add_one lines (last_line ^ "\";") in
Res.Array.to_list lines
else if literal.[line_end - 1] <> '\\' then
let line = String.sub literal ~pos:line_start ~len:(line_end - line_start) in
let () = Res.Array.add_one lines (line ^ "\\") in
loop line_end (min (line_end + wrap) (String.length literal))
else
loop line_start (line_end + 1)
in
"Bytes.unsafe_of_string \"\\" :: (loop 0 (min wrap (String.length literal)))
(* Generate appropriate code for instantiating a message which contains
all the struct and list default values. *)
let emit_instantiate_builder_message message : string list =
let message_segment_literals =
let segment_descrs = M.Message.to_storage message in
64 characters works out to 16 bytes per line .
let wrap_chars = 64 in
List.fold_left (List.rev segment_descrs) ~init:[] ~f:(fun acc descr ->
let seg = CamlBytes.sub descr.M.Message.segment 0 descr.M.Message.bytes_consumed in
(emit_literal_seg (CamlBytes.unsafe_to_string seg) wrap_chars) @ acc)
in [
"module DefaultsMessage_ = Capnp.BytesMessage";
"";
"let _builder_defaults_message =";
" let message_segments = ["; ] @
(GenCommon.apply_indent ~indent:" " message_segment_literals) @ [
" ] in";
" DefaultsMessage_.Message.readonly";
" (DefaultsMessage_.Message.of_storage message_segments)";
"";
]
(* Generate code which instantiates struct descriptors for struct defaults
stored in the message. *)
let emit_instantiate_builder_structs struct_array : string list =
Res.Array.fold_right (fun (ident, struct_storage) acc ->
let open M.StructStorage in [
"let " ^ (builder_string_of_ident ident) ^ " =";
" let data_segment_id = " ^
(Int.to_string struct_storage.data.M.Slice.segment_id) ^ " in";
" let pointers_segment_id = " ^
(Int.to_string struct_storage.pointers.M.Slice.segment_id) ^ " in";
" DefaultsMessage_.StructStorage.v";
" ~data:{";
" DefaultsMessage_.Slice.msg = _builder_defaults_message;";
" DefaultsMessage_.Slice.segment = DefaultsMessage_.Message.get_segment \
_builder_defaults_message data_segment_id;";
" DefaultsMessage_.Slice.segment_id = data_segment_id;";
" DefaultsMessage_.Slice.start = " ^
(Int.to_string struct_storage.data.M.Slice.start) ^ ";";
" DefaultsMessage_.Slice.len = " ^
(Int.to_string struct_storage.data.M.Slice.len) ^ ";";
" }";
" ~pointers:{";
" DefaultsMessage_.Slice.msg = _builder_defaults_message;";
" DefaultsMessage_.Slice.segment = DefaultsMessage_.Message.get_segment \
_builder_defaults_message pointers_segment_id;";
" DefaultsMessage_.Slice.segment_id = pointers_segment_id;";
" DefaultsMessage_.Slice.start = " ^
(Int.to_string struct_storage.pointers.M.Slice.start) ^ ";";
" DefaultsMessage_.Slice.len = " ^
(Int.to_string struct_storage.pointers.M.Slice.len) ^ ";";
" }";
"";
] @ acc)
struct_array
[]
(* Generate code which instantiates list descriptors for list defaults
stored in the message. *)
let emit_instantiate_builder_lists list_array : string list =
Res.Array.fold_right (fun (ident, list_storage) acc ->
let open M.ListStorage in [
"let " ^ (builder_string_of_ident ident) ^ " =";
" let segment_id = " ^
(Int.to_string list_storage.storage.M.Slice.segment_id) ^ " in {";
" DefaultsMessage_.ListStorage.storage = {";
" DefaultsMessage_.Slice.msg = _builder_defaults_message;";
" DefaultsMessage_.Slice.segment = DefaultsMessage_.Message.get_segment \
_builder_defaults_message segment_id;";
" DefaultsMessage_.Slice.segment_id = segment_id;" ^
" DefaultsMessage_.Slice.start = " ^
(Int.to_string list_storage.storage.M.Slice.start) ^ ";";
" DefaultsMessage_.Slice.len = " ^
(Int.to_string list_storage.storage.M.Slice.len) ^ "; };";
" DefaultsMessage_.ListStorage.storage_type = Capnp.Runtime." ^
(ListStorageType.to_string list_storage.storage_type) ^ ";";
" DefaultsMessage_.ListStorage.num_elements = " ^
(Int.to_string list_storage.num_elements) ^ ";";
"}";
"";
] @ acc)
list_array
[]
(* Generate code which instantiates slices for pointer defaults
stored in the message. *)
let emit_instantiate_builder_pointers pointer_array : string list =
Res.Array.fold_right (fun (ident, pointer_bytes) acc -> [
"let " ^ (builder_string_of_ident ident) ^ " =";
" let segment_id = " ^
(Int.to_string pointer_bytes.M.Slice.segment_id) ^ " in {";
" DefaultsMessage_.Slice.msg = _builder_defaults_message;";
" DefaultsMessage_.Slice.segment = DefaultsMessage_.Message.get_segment \
_builder_defaults_message segment_id;";
" DefaultsMessage_.Slice.segment_id = segment_id;";
" DefaultsMessage_.Slice.start = " ^
(Int.to_string pointer_bytes.M.Slice.start) ^ ";";
" DefaultsMessage_.Slice.len = " ^
(Int.to_string pointer_bytes.M.Slice.len) ^ ";";
"}";
"";
] @ acc)
pointer_array
[]
let gen_builder_defaults defaults =
(emit_instantiate_builder_message defaults.message) @
(emit_instantiate_builder_structs defaults.structs) @
(emit_instantiate_builder_lists defaults.lists) @
(emit_instantiate_builder_pointers defaults.pointers)
(* Generate code for instantiating a defaults storage message
using the same native storage type as the functor parameter. *)
let emit_instantiate_reader_message () = [
"module DefaultsCopier_ =";
" Capnp.Runtime.BuilderOps.Make(Capnp.BytesMessage)(MessageWrapper)";
"";
"let _reader_defaults_message =";
" MessageWrapper.Message.create";
" (DefaultsMessage_.Message.total_size _builder_defaults_message)";
"";
]
let emit_instantiate_reader_structs struct_array =
Res.Array.fold_left (fun acc (ident, _struct_storage) -> [
"let " ^ (reader_string_of_ident ident) ^ " =";
" let data_words =";
" let def = " ^ (builder_string_of_ident ident) ^ " in";
" let data_slice = def.DefaultsMessage_.StructStorage.data in";
" data_slice.DefaultsMessage_.Slice.len / 8";
" in";
" let pointer_words =";
" let def = " ^ (builder_string_of_ident ident) ^ " in";
" let pointers_slice = def.DefaultsMessage_.StructStorage.pointers in";
" pointers_slice.DefaultsMessage_.Slice.len / 8";
" in";
" DefaultsCopier_.RWC.StructStorage.readonly";
" (DefaultsCopier_.deep_copy_struct ~src:" ^ (builder_string_of_ident ident);
" ~dest_message:_reader_defaults_message ~data_words ~pointer_words)";
"";
] @ acc)
[]
struct_array
let emit_instantiate_reader_lists list_array =
Res.Array.fold_left (fun acc (ident, _list_storage) -> [
"let " ^ (reader_string_of_ident ident) ^ " =";
" DefaultsCopier_.RWC.ListStorage.readonly";
" (DefaultsCopier_.deep_copy_list ~src:" ^ (builder_string_of_ident ident);
" ~dest_message:_reader_defaults_message ())";
"";
] @ acc)
[]
list_array
let gen_reader_defaults defaults =
(emit_instantiate_reader_message ()) @
(emit_instantiate_reader_structs defaults.structs) @
(emit_instantiate_reader_lists defaults.lists) @
(emit_instantiate_builder_pointers defaults.pointers)
| null | https://raw.githubusercontent.com/capnproto/capnp-ocaml/dda3d811aa7734110d7af051465011f1f823ffb9/src/compiler/defaults.ml | ocaml | Message storage.
Array of structs which have been stored in the message, along with
their unique identifiers.
Array of lists which have been stored in the message, along with
their unique identifiers.
Array of pointers which have been stored in the message, along
with their unique identifiers.
Emit a semicolon-delimited string literal, wrapping at approximately the specified
word wrap boundary. We use the end-of-line-backslash to emit a string literal
which spans multiple lines. Escaped literals for binary data can contain lots
of backslashes, so we may stretch a line slightly to avoid breaking in the
middle of a literal backslash.
Generate appropriate code for instantiating a message which contains
all the struct and list default values.
Generate code which instantiates struct descriptors for struct defaults
stored in the message.
Generate code which instantiates list descriptors for list defaults
stored in the message.
Generate code which instantiates slices for pointer defaults
stored in the message.
Generate code for instantiating a defaults storage message
using the same native storage type as the functor parameter. | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* capnp - ocaml
*
* Copyright ( c ) 2013 - 2014 ,
* All rights reserved .
*
* Redistribution and use in source and binary forms , with or without
* modification , are permitted provided that the following conditions are met :
*
* 1 . Redistributions of source code must retain the above copyright notice ,
* this list of conditions and the following disclaimer .
*
* 2 . Redistributions in binary form must reproduce the above copyright
* notice , this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution .
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS "
* AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR
* CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS
* INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , IN
* CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING NEGLIGENCE OR OTHERWISE )
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE , EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE .
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* capnp-ocaml
*
* Copyright (c) 2013-2014, Paul Pelzl
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
******************************************************************************)
Management of default values for structs and lists . These values are
passed as a pointers to data stored in the PluginSchema message
generated by capnp compile . We will need to make a deep copy to transfer these
objects into a BytesStorage - based message , so we can easily serialize
the string contents right into the generated code .
It turns out to be relatively easy to handle default values for Builder
structs and lists , because the standard Builder behavior is to eliminate
nulls as early as possible : default values are immediately deep copied
into the Builder message so that the implementation can hold references
to valid data .
Surprisingly , the more difficult case is the Reader implementation .
The read - only semantics imply that we ca n't use the same approach here :
if there 's a null pointer , a dereference must return default data
which is physically stored in a different message . But because we have
functorized the code over the message type , we ca n't arbitrarily choose
to return default data stored in a * string * message ; we must return
default data stored in a message type which matches the functor parameter .
So when we instantiate the generated functor , we immediately construct
a new message of an appropriate type and deep - copy the default values
from string storage into this new message of the correct type .
passed as a pointers to data stored in the PluginSchema message
generated by capnp compile. We will need to make a deep copy to transfer these
objects into a BytesStorage-based message, so we can easily serialize
the string contents right into the generated code.
It turns out to be relatively easy to handle default values for Builder
structs and lists, because the standard Builder behavior is to eliminate
nulls as early as possible: default values are immediately deep copied
into the Builder message so that the implementation can hold references
to valid data.
Surprisingly, the more difficult case is the Reader implementation.
The read-only semantics imply that we can't use the same approach here:
if there's a null pointer, a dereference must return default data
which is physically stored in a different message. But because we have
functorized the code over the message type, we can't arbitrarily choose
to return default data stored in a *string* message; we must return
default data stored in a message type which matches the functor parameter.
So when we instantiate the generated functor, we immediately construct
a new message of an appropriate type and deep-copy the default values
from string storage into this new message of the correct type.
*)
module Uint64 = Stdint.Uint64
Workaround for missing . Bytes in Core 112.35.00
module CamlBytes = Bytes
module String = Base.String
module List = Base.List
module Int = Base.Int
module Copier = Capnp.Runtime.BuilderOps.Make(GenCommon.M)(GenCommon.M)
module M = GenCommon.M
module ListStorageType = Capnp.Runtime.ListStorageType
let sizeof_uint64 = 8
type abstract
type t = {
message : Capnp.Message.rw M.Message.t;
structs : (string * (Capnp.Message.rw, abstract) M.StructStorage.t) Res.Array.t;
lists : (string * Capnp.Message.rw M.ListStorage.t) Res.Array.t;
pointers : (string * Capnp.Message.rw M.Slice.t) Res.Array.t;
}
type ident_t = string
let create () = {
message = M.Message.create 64;
structs = Res.Array.empty ();
lists = Res.Array.empty ();
pointers = Res.Array.empty ();
}
let make_ident node_id field_name =
"default_value_" ^ (Uint64.to_string node_id) ^ "_" ^ field_name
let builder_string_of_ident x = "_builder_" ^ x
let reader_string_of_ident x = "_reader_" ^ x
let add_struct defaults ident struct_storage =
let open M.StructStorage in
let data_words = struct_storage.data.M.Slice.len / sizeof_uint64 in
let pointer_words = struct_storage.pointers.M.Slice.len / sizeof_uint64 in
let struct_copy = Copier.deep_copy_struct ~src:struct_storage
~dest_message:defaults.message ~data_words ~pointer_words
in
Res.Array.add_one defaults.structs (ident, struct_copy)
let add_list defaults ident list_storage =
let list_copy = Copier.deep_copy_list ~src:list_storage
~dest_message:defaults.message ()
in
Res.Array.add_one defaults.lists (ident, list_copy)
let add_pointer defaults ident pointer_bytes =
let dest = M.Slice.alloc defaults.message sizeof_uint64 in
let () = Copier.deep_copy_pointer ~src:pointer_bytes ~dest in
Res.Array.add_one defaults.pointers (ident, dest)
let emit_literal_seg (segment : string) (wrap : int) : string list =
let literal = Capnp.Runtime.Util.make_hex_literal segment in
let lines = Res.Array.empty () in
let rec loop line_start line_end =
let () = assert (line_end <= String.length literal) in
if line_end = String.length literal then
let last_line = String.sub literal ~pos:line_start ~len:(line_end - line_start) in
let () = Res.Array.add_one lines (last_line ^ "\";") in
Res.Array.to_list lines
else if literal.[line_end - 1] <> '\\' then
let line = String.sub literal ~pos:line_start ~len:(line_end - line_start) in
let () = Res.Array.add_one lines (line ^ "\\") in
loop line_end (min (line_end + wrap) (String.length literal))
else
loop line_start (line_end + 1)
in
"Bytes.unsafe_of_string \"\\" :: (loop 0 (min wrap (String.length literal)))
let emit_instantiate_builder_message message : string list =
let message_segment_literals =
let segment_descrs = M.Message.to_storage message in
64 characters works out to 16 bytes per line .
let wrap_chars = 64 in
List.fold_left (List.rev segment_descrs) ~init:[] ~f:(fun acc descr ->
let seg = CamlBytes.sub descr.M.Message.segment 0 descr.M.Message.bytes_consumed in
(emit_literal_seg (CamlBytes.unsafe_to_string seg) wrap_chars) @ acc)
in [
"module DefaultsMessage_ = Capnp.BytesMessage";
"";
"let _builder_defaults_message =";
" let message_segments = ["; ] @
(GenCommon.apply_indent ~indent:" " message_segment_literals) @ [
" ] in";
" DefaultsMessage_.Message.readonly";
" (DefaultsMessage_.Message.of_storage message_segments)";
"";
]
let emit_instantiate_builder_structs struct_array : string list =
Res.Array.fold_right (fun (ident, struct_storage) acc ->
let open M.StructStorage in [
"let " ^ (builder_string_of_ident ident) ^ " =";
" let data_segment_id = " ^
(Int.to_string struct_storage.data.M.Slice.segment_id) ^ " in";
" let pointers_segment_id = " ^
(Int.to_string struct_storage.pointers.M.Slice.segment_id) ^ " in";
" DefaultsMessage_.StructStorage.v";
" ~data:{";
" DefaultsMessage_.Slice.msg = _builder_defaults_message;";
" DefaultsMessage_.Slice.segment = DefaultsMessage_.Message.get_segment \
_builder_defaults_message data_segment_id;";
" DefaultsMessage_.Slice.segment_id = data_segment_id;";
" DefaultsMessage_.Slice.start = " ^
(Int.to_string struct_storage.data.M.Slice.start) ^ ";";
" DefaultsMessage_.Slice.len = " ^
(Int.to_string struct_storage.data.M.Slice.len) ^ ";";
" }";
" ~pointers:{";
" DefaultsMessage_.Slice.msg = _builder_defaults_message;";
" DefaultsMessage_.Slice.segment = DefaultsMessage_.Message.get_segment \
_builder_defaults_message pointers_segment_id;";
" DefaultsMessage_.Slice.segment_id = pointers_segment_id;";
" DefaultsMessage_.Slice.start = " ^
(Int.to_string struct_storage.pointers.M.Slice.start) ^ ";";
" DefaultsMessage_.Slice.len = " ^
(Int.to_string struct_storage.pointers.M.Slice.len) ^ ";";
" }";
"";
] @ acc)
struct_array
[]
let emit_instantiate_builder_lists list_array : string list =
Res.Array.fold_right (fun (ident, list_storage) acc ->
let open M.ListStorage in [
"let " ^ (builder_string_of_ident ident) ^ " =";
" let segment_id = " ^
(Int.to_string list_storage.storage.M.Slice.segment_id) ^ " in {";
" DefaultsMessage_.ListStorage.storage = {";
" DefaultsMessage_.Slice.msg = _builder_defaults_message;";
" DefaultsMessage_.Slice.segment = DefaultsMessage_.Message.get_segment \
_builder_defaults_message segment_id;";
" DefaultsMessage_.Slice.segment_id = segment_id;" ^
" DefaultsMessage_.Slice.start = " ^
(Int.to_string list_storage.storage.M.Slice.start) ^ ";";
" DefaultsMessage_.Slice.len = " ^
(Int.to_string list_storage.storage.M.Slice.len) ^ "; };";
" DefaultsMessage_.ListStorage.storage_type = Capnp.Runtime." ^
(ListStorageType.to_string list_storage.storage_type) ^ ";";
" DefaultsMessage_.ListStorage.num_elements = " ^
(Int.to_string list_storage.num_elements) ^ ";";
"}";
"";
] @ acc)
list_array
[]
let emit_instantiate_builder_pointers pointer_array : string list =
Res.Array.fold_right (fun (ident, pointer_bytes) acc -> [
"let " ^ (builder_string_of_ident ident) ^ " =";
" let segment_id = " ^
(Int.to_string pointer_bytes.M.Slice.segment_id) ^ " in {";
" DefaultsMessage_.Slice.msg = _builder_defaults_message;";
" DefaultsMessage_.Slice.segment = DefaultsMessage_.Message.get_segment \
_builder_defaults_message segment_id;";
" DefaultsMessage_.Slice.segment_id = segment_id;";
" DefaultsMessage_.Slice.start = " ^
(Int.to_string pointer_bytes.M.Slice.start) ^ ";";
" DefaultsMessage_.Slice.len = " ^
(Int.to_string pointer_bytes.M.Slice.len) ^ ";";
"}";
"";
] @ acc)
pointer_array
[]
let gen_builder_defaults defaults =
(emit_instantiate_builder_message defaults.message) @
(emit_instantiate_builder_structs defaults.structs) @
(emit_instantiate_builder_lists defaults.lists) @
(emit_instantiate_builder_pointers defaults.pointers)
let emit_instantiate_reader_message () = [
"module DefaultsCopier_ =";
" Capnp.Runtime.BuilderOps.Make(Capnp.BytesMessage)(MessageWrapper)";
"";
"let _reader_defaults_message =";
" MessageWrapper.Message.create";
" (DefaultsMessage_.Message.total_size _builder_defaults_message)";
"";
]
let emit_instantiate_reader_structs struct_array =
Res.Array.fold_left (fun acc (ident, _struct_storage) -> [
"let " ^ (reader_string_of_ident ident) ^ " =";
" let data_words =";
" let def = " ^ (builder_string_of_ident ident) ^ " in";
" let data_slice = def.DefaultsMessage_.StructStorage.data in";
" data_slice.DefaultsMessage_.Slice.len / 8";
" in";
" let pointer_words =";
" let def = " ^ (builder_string_of_ident ident) ^ " in";
" let pointers_slice = def.DefaultsMessage_.StructStorage.pointers in";
" pointers_slice.DefaultsMessage_.Slice.len / 8";
" in";
" DefaultsCopier_.RWC.StructStorage.readonly";
" (DefaultsCopier_.deep_copy_struct ~src:" ^ (builder_string_of_ident ident);
" ~dest_message:_reader_defaults_message ~data_words ~pointer_words)";
"";
] @ acc)
[]
struct_array
let emit_instantiate_reader_lists list_array =
Res.Array.fold_left (fun acc (ident, _list_storage) -> [
"let " ^ (reader_string_of_ident ident) ^ " =";
" DefaultsCopier_.RWC.ListStorage.readonly";
" (DefaultsCopier_.deep_copy_list ~src:" ^ (builder_string_of_ident ident);
" ~dest_message:_reader_defaults_message ())";
"";
] @ acc)
[]
list_array
let gen_reader_defaults defaults =
(emit_instantiate_reader_message ()) @
(emit_instantiate_reader_structs defaults.structs) @
(emit_instantiate_reader_lists defaults.lists) @
(emit_instantiate_builder_pointers defaults.pointers)
|
5d021a59083e6d9354b82f3b641aeaba0a471fd84e797e4b629306fa82c900ef | ghc/nofib | S_matrix.hs |
Diffusion matrix
XZ , 24/10/91
Diffusion matrix
XZ, 24/10/91
-}
Modified to adopt S_array
The way in which the matrix is constructed has been
changed .
XZ , 19/2/92
Modified to adopt S_array
The way in which the matrix is constructed has been
changed.
XZ, 19/2/92
-}
module S_matrix ( s_mat ) where
import Defs
import S_Array -- not needed w/ proper module handling
import Norm -- ditto
-----------------------------------------------------------
-- Diffusion matrix. --
-- Used in assembling rh1. --
-- Parameters: --
-- gdij : jth entry of ith element factor component --
-----------------------------------------------------------
s_mat
:: My_Array Int (((Frac_type,Frac_type,Frac_type),
(Frac_type,Frac_type,Frac_type)) -> [Frac_type])
s_mat =
s_listArray (1,v_nodel)
[
\u -> cons u [f11,f12,f13,f0,f15,f16],
\u -> cons u [f12,f22,f23,f24,f0,f16],
\u -> cons u [f13,f23,f33,f24,f15,f0],
\u -> cons u [f0,f24,f24,f44,f45,f46],
\u -> cons u [f15,f0,f15,f45,f55,f56],
\u -> cons u [f16,f16,f0,f46,f56,f66]
]
where
s1 = \(x,_,_) -> x
s2 = \(_,y,_) -> y
s3 = \(_,_,z) -> z
ff1 = \x y u v -> x*y+u*v
ff2 = \x y u v -> (ff2' x y) + (ff2' u v)
where ff2' = \x y -> x*(x+y)+y*y
ff3 = \x y z u v w -> (ff3' x y z) + (ff3' u v w)
where ff3' = \x y z -> x*y+(x+z)*(y+z)
cons = \u -> map (\f->f u)
f0 = \x -> 0
f11 (x,y) = 3 * ( ff1 c1 c1 c2 c2 )
where
c1 = s1 x
c2 = s1 y
f12 = \(x,y) -> - ( ff1 (s1 x) (s2 x) (s1 y) (s2 y) )
f13 = \(x,y) -> - ( ff1 (s1 x) (s3 x) (s1 y) (s3 y) )
f15 = \x -> (-4) * (f13 x)
f16 = \x -> (-4) * (f12 x)
f22 (x,y) = 3 * ( ff1 c1 c1 c2 c2 )
where
c1 = s2 x
c2 = s2 y
f23 = \(x,y) -> - ( ff1 (s2 x) (s3 x) (s2 y) (s3 y) )
f24 = \x -> (-4) * (f23 x)
f33 (x,y) = 3 * ( ff1 c1 c1 c2 c2 )
where
c1 = s3 x
c2 = s3 y
f44 = \(x,y) -> 8 * ( ff2 (s2 x) (s3 x) (s2 y) (s3 y) )
f45 = \(x,y)->4*(ff3 (s1 x) (s2 x) (s3 x) (s1 y) (s2 y) (s3 y))
f46 = \(x,y)->4*(ff3 (s1 x) (s3 x) (s2 x) (s1 y) (s3 y) (s2 y))
f55 = \(x,y) -> 8 * ( ff2 (s1 x) (s3 x) (s1 y) (s3 y) )
f56 = \(x,y)->4*(ff3 (s2 x) (s3 x) (s1 x) (s2 y) (s3 y) (s1 y))
f66 = \(x,y) -> 8 * ( ff2 (s1 x) (s2 x) (s1 y) (s2 y) )
| null | https://raw.githubusercontent.com/ghc/nofib/f34b90b5a6ce46284693119a06d1133908b11856/real/fluid/S_matrix.hs | haskell | not needed w/ proper module handling
ditto
---------------------------------------------------------
Diffusion matrix. --
Used in assembling rh1. --
Parameters: --
gdij : jth entry of ith element factor component --
--------------------------------------------------------- |
Diffusion matrix
XZ , 24/10/91
Diffusion matrix
XZ, 24/10/91
-}
Modified to adopt S_array
The way in which the matrix is constructed has been
changed .
XZ , 19/2/92
Modified to adopt S_array
The way in which the matrix is constructed has been
changed.
XZ, 19/2/92
-}
module S_matrix ( s_mat ) where
import Defs
s_mat
:: My_Array Int (((Frac_type,Frac_type,Frac_type),
(Frac_type,Frac_type,Frac_type)) -> [Frac_type])
s_mat =
s_listArray (1,v_nodel)
[
\u -> cons u [f11,f12,f13,f0,f15,f16],
\u -> cons u [f12,f22,f23,f24,f0,f16],
\u -> cons u [f13,f23,f33,f24,f15,f0],
\u -> cons u [f0,f24,f24,f44,f45,f46],
\u -> cons u [f15,f0,f15,f45,f55,f56],
\u -> cons u [f16,f16,f0,f46,f56,f66]
]
where
s1 = \(x,_,_) -> x
s2 = \(_,y,_) -> y
s3 = \(_,_,z) -> z
ff1 = \x y u v -> x*y+u*v
ff2 = \x y u v -> (ff2' x y) + (ff2' u v)
where ff2' = \x y -> x*(x+y)+y*y
ff3 = \x y z u v w -> (ff3' x y z) + (ff3' u v w)
where ff3' = \x y z -> x*y+(x+z)*(y+z)
cons = \u -> map (\f->f u)
f0 = \x -> 0
f11 (x,y) = 3 * ( ff1 c1 c1 c2 c2 )
where
c1 = s1 x
c2 = s1 y
f12 = \(x,y) -> - ( ff1 (s1 x) (s2 x) (s1 y) (s2 y) )
f13 = \(x,y) -> - ( ff1 (s1 x) (s3 x) (s1 y) (s3 y) )
f15 = \x -> (-4) * (f13 x)
f16 = \x -> (-4) * (f12 x)
f22 (x,y) = 3 * ( ff1 c1 c1 c2 c2 )
where
c1 = s2 x
c2 = s2 y
f23 = \(x,y) -> - ( ff1 (s2 x) (s3 x) (s2 y) (s3 y) )
f24 = \x -> (-4) * (f23 x)
f33 (x,y) = 3 * ( ff1 c1 c1 c2 c2 )
where
c1 = s3 x
c2 = s3 y
f44 = \(x,y) -> 8 * ( ff2 (s2 x) (s3 x) (s2 y) (s3 y) )
f45 = \(x,y)->4*(ff3 (s1 x) (s2 x) (s3 x) (s1 y) (s2 y) (s3 y))
f46 = \(x,y)->4*(ff3 (s1 x) (s3 x) (s2 x) (s1 y) (s3 y) (s2 y))
f55 = \(x,y) -> 8 * ( ff2 (s1 x) (s3 x) (s1 y) (s3 y) )
f56 = \(x,y)->4*(ff3 (s2 x) (s3 x) (s1 x) (s2 y) (s3 y) (s1 y))
f66 = \(x,y) -> 8 * ( ff2 (s1 x) (s2 x) (s1 y) (s2 y) )
|
5e9360f1431a4fbcd1ce95acf22636cea23945ebcaebec12e8a0f5e9e326d1a1 | SamB/coq | record.mli | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
(*i $Id$ i*)
(*i*)
open Names
open Term
open Sign
open Vernacexpr
open Topconstr
(*i*)
(* [declare_projections ref name coers params fields] declare projections of
record [ref] (if allowed) using the given [name] as argument, and put them
as coercions accordingly to [coers]; it returns the absolute names of projections *)
val declare_projections :
inductive -> ?kind:Decl_kinds.definition_object_kind -> ?name:identifier -> bool list -> rel_context -> bool list * constant option list
val definition_structure :
lident with_coercion * local_binder list *
(local_decl_expr with_coercion) list * identifier * sorts -> kernel_name
| null | https://raw.githubusercontent.com/SamB/coq/8f84aba9ae83a4dc43ea6e804227ae8cae8086b1/toplevel/record.mli | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
i $Id$ i
i
i
[declare_projections ref name coers params fields] declare projections of
record [ref] (if allowed) using the given [name] as argument, and put them
as coercions accordingly to [coers]; it returns the absolute names of projections | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
open Names
open Term
open Sign
open Vernacexpr
open Topconstr
val declare_projections :
inductive -> ?kind:Decl_kinds.definition_object_kind -> ?name:identifier -> bool list -> rel_context -> bool list * constant option list
val definition_structure :
lident with_coercion * local_binder list *
(local_decl_expr with_coercion) list * identifier * sorts -> kernel_name
|
30e228dd9a404abeb96dcbb5eb8cdeb83b54fa343684e3052667e36ac58d3407 | haas/harmtrace | GuptaNishimura.hs | # OPTIONS_GHC -Wall #
# LANGUAGE MagicHash #
{-# LANGUAGE BangPatterns #-}
module HarmTrace.Matching.GuptaNishimura ( getLCES , getLCESsize
, getLCESdepth, getLCESsim)
where
--------------------------------------------------------------------------------
Finding the Largest Common ( LCES )
Based on : , and Nishimura , N. ( 1998 ) Finding largest subtrees and
smallest supertrees , , 21(2 ) , p. 183 - -210
author :
--------------------------------------------------------------------------------
import Data.Ord
import Data.Maybe
import Prelude hiding (length, last)
import Data.Vector hiding ((!), last)
import qualified Data.List as L
import HarmTrace.HAnTree.Tree
import HarmTrace.HAnTree.HAn
import HarmTrace.Matching.Sim
--------------------------------------------------------------------------------
-- Top Level LCES function
--------------------------------------------------------------------------------
getLCESsim :: Tree HAn -> Tree HAn -> Float
getLCESsim ta tb = let match = fromIntegral . snd $ getLCES ta tb
selfSimA = sim ta ta * cumDur ta
selfSimB = sim tb tb * cumDur tb
in (match * match) / fromIntegral (selfSimA * selfSimB)
getLCESsize :: Tree HAn -> Tree HAn -> Float
getLCESsize ta tb = let match = fromIntegral . sizeF . fst $ getLCES ta tb
in (match * match) / fromIntegral (size ta * size tb)
-- Check ismir09 implementation
getLCESdepth :: Tree HAn -> Tree HAn -> Float
getLCESdepth ta tb = let match = avgDepthF . fst $ getLCES ta tb
in (match * match) / (avgDepth ta * avgDepth tb)
-- Top level function that returns the largest common embedable subtree
of two trees
getLCES :: Tree HAn -> Tree HAn -> ([Tree HAn], Int)
getLCES ta tb = (matchToTree ta (L.map fst (L.reverse m)),w) where
(LCES m w) = last . last $ lces ta tb
nonMatchPenal :: Int
nonMatchPenal = 2
--------------------------------------------------------------------------------
-- LCES calculation
--------------------------------------------------------------------------------
-- calculates the largest labeled common embeddable subtree
lces :: (Sim t, GetDur t) => Tree t -> Tree t -> Vector (Vector LCES)
lces ta tb = n where
a = fromList (pot ta)
b = fromList (pot tb)
maxi :: Int -> [Int] -> LCES
{-# INLINE maxi #-}
maxi _ [] = emptyLCES
maxi i cb = (n!i) ! (L.maximumBy (comparing (\j -> getWeight $ ((n!i)!j))) cb)
maxj :: [Int] -> Int -> LCES
{-# INLINE maxj #-}
maxj [] _ = emptyLCES
maxj ca j = (n ! (L.maximumBy (comparing (\i -> getWeight $ ((n!i)!j))) ca))!j
recur 0 0 = if sim (getLabel (a ! 0)) (getLabel (b ! 0)) > 0
then LCES [(0,0)] (durSim (getLabel (a ! 0)) (getLabel (b ! 0)))
else emptyLCES
recur i j = findBestMatch (sim labi labj)
(min (getDur labi) (getDur labj)) i j mc mi mj where
mi = maxi i (getChildPns (b ! j))
mj = maxj (getChildPns (a ! i)) j
mc = wbMatch (getChild (a ! i)) (getChild $ b ! j) n
!labi = getLabel (a!i)
!labj = getLabel (b!j)
n = generate (length a) (generate (length b) . recur)
-- returns the best matching candidate, given the previous candidates, the
-- bipartite matching. The function depends on wheter the currend nodes
match and whether , in that case , one of the current nodes is not allready
-- matched
findBestMatch :: Int -> Int -> Int -> Int -> LCES -> LCES -> LCES -> LCES
{-# INLINE findBestMatch #-}
findBestMatch simv dur i j a b c
| simv <= 0 = (LCES mf (max (wf - (nonMatchPenal * dur)) 0 ))
| otherwise = if isFree first i j then (LCES ((i,j):mf) (wf+(dur*simv)))
else if wf /= ws then first
else if isFree second i j then (LCES ((i,j):ms) (ws+(dur*simv)))
else if wf /= wt then first
else if isFree second i j then (LCES ((i,j):mt) (wt+(dur*simv)))
else first where
(first@(LCES mf wf) :second@(LCES ms ws) :(LCES mt wt) :[]) = mySort [a,b,c]
--------------------------------------------------------------------------------
Weighted Plannar Matching of a Bipartite Graph
--------------------------------------------------------------------------------
-- returns the actual planar weighted bipartite matchings. n should contain
-- the weights of the edge between a[i] and b[j]
wbMatch :: [Tree t] -> [Tree t] -> Vector (Vector LCES) -> LCES
# INLINE wbMatch #
wbMatch _ [] _ = emptyLCES
wbMatch [] _ _ = emptyLCES
wbMatch a b n = last $ last m where
-- returns a previously matched subtree
subTree :: Int -> Int -> LCES
# INLINE subTree #
subTree i j = (n ! (fromJust . getPn $ a!!i)) ! (fromJust . getPn $ b!!j)
-- this is the actual core recursive definintion of the algorithm
match, fill :: Int -> Int -> LCES
match i j = L.maximumBy (comparing getWeight) [maxPrv, minPrv, diagM] where
s = subTree i j
!hasMatch = getWeight s > 0
maxPrv = if not hasMatch then (m ! (i-1)) ! j
else if isFree ((m!(i-1)) ! j) i j then merge s ((m!(i-1)) ! j)
else ((m ! (i-1)) ! j)
minPrv = if not hasMatch then (m ! i) ! (j-1)
else if isFree ((m!i) ! (j-1)) i j then merge s ((m!i) ! (j-1))
else ((m ! i) ! (j-1))
diagM = merge s ((m ! (i-1)) ! (j-1))
fill 0 0 = subTree 0 0
fill 0 j = if getWeight (subTree 0 j) > getWeight ((m ! 0) ! (j-1))
then subTree 0 j else (m ! 0) ! (j-1)
fill i 0 = if getWeight (subTree i 0) > getWeight ((m ! (i-1)) ! 0)
then subTree i 0 else ((m ! (i-1)) ! 0)
fill i j = match i j
m = generate (L.length a) (generate (L.length b) . fill)
--------------------------------------------------------------------------------
Some helper functions
--------------------------------------------------------------------------------
data LCES = LCES ![(Int, Int)] !Int
getWeight :: LCES -> Int
# INLINE getWeight #
getWeight (LCES _ w) = w
-- getMatch :: LCES -> [(Int, Int)]
-- getMatch (LCES m _) = m
durSim :: (Sim a, GetDur a) => a -> a -> Int
durSim a b = (sim a b) * (min (getDur a) (getDur b))
emptyLCES :: LCES
# INLINE emptyLCES #
emptyLCES = LCES [] 0
(!) :: Vector a -> Int -> a
{-# INLINE (!) #-}
(!) = unsafeIndex
last :: Vector a -> a
# INLINE last #
last = unsafeLast
cumDur :: (GetDur a) => Tree a -> Int
cumDur a = (getDur $ getLabel a) + (L.sum $ L.map cumDur (getChild a))
-- checks if the previously calculated optimal solution does not
-- contain the indices i and j in a and b, resepectivly
isFree :: LCES -> Int -> Int -> Bool
# INLINE isFree #
isFree (LCES [] _) _ _ = True
isFree (LCES ((previ, prevj):_) _) i j = ( i > previ && j > prevj)
mergest two lists with matches
merge :: LCES -> LCES -> LCES
{-# INLINE merge #-}
merge (LCES a wa) (LCES b wb) = LCES (a L.++ b) (wa + wb)
-- this sorting routine makes quite a large difference in runtime performance!
mySort :: [LCES] -> [LCES]
{-# INLINE mySort #-}
mySort [a,b,c] = case (x >= y, y >= z, x >= z) of
(True , True , True ) -> [a,b,c]
(True , False, True ) -> [a,c,b]
(True , False, False) -> [c,a,b]
(False, True , True ) -> [b,a,c]
(False, True , False) -> [b,c,a]
(False, False, False) -> [c,b,a]
_ -> error "mySort: impossible"
where !x = getWeight a
!y = getWeight b
!z = getWeight c
mySort _ = error "mySort: unexpected argument"
| null | https://raw.githubusercontent.com/haas/harmtrace/e250855a3bb6e5b28fe538c728f707cf82ca9fd3/src/HarmTrace/Matching/GuptaNishimura.hs | haskell | # LANGUAGE BangPatterns #
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Top Level LCES function
------------------------------------------------------------------------------
Check ismir09 implementation
Top level function that returns the largest common embedable subtree
------------------------------------------------------------------------------
LCES calculation
------------------------------------------------------------------------------
calculates the largest labeled common embeddable subtree
# INLINE maxi #
# INLINE maxj #
returns the best matching candidate, given the previous candidates, the
bipartite matching. The function depends on wheter the currend nodes
matched
# INLINE findBestMatch #
------------------------------------------------------------------------------
------------------------------------------------------------------------------
returns the actual planar weighted bipartite matchings. n should contain
the weights of the edge between a[i] and b[j]
returns a previously matched subtree
this is the actual core recursive definintion of the algorithm
------------------------------------------------------------------------------
------------------------------------------------------------------------------
getMatch :: LCES -> [(Int, Int)]
getMatch (LCES m _) = m
# INLINE (!) #
checks if the previously calculated optimal solution does not
contain the indices i and j in a and b, resepectivly
# INLINE merge #
this sorting routine makes quite a large difference in runtime performance!
# INLINE mySort # | # OPTIONS_GHC -Wall #
# LANGUAGE MagicHash #
module HarmTrace.Matching.GuptaNishimura ( getLCES , getLCESsize
, getLCESdepth, getLCESsim)
where
Finding the Largest Common ( LCES )
Based on : , and Nishimura , N. ( 1998 ) Finding largest subtrees and
smallest supertrees , , 21(2 ) , p. 183 - -210
author :
import Data.Ord
import Data.Maybe
import Prelude hiding (length, last)
import Data.Vector hiding ((!), last)
import qualified Data.List as L
import HarmTrace.HAnTree.Tree
import HarmTrace.HAnTree.HAn
import HarmTrace.Matching.Sim
getLCESsim :: Tree HAn -> Tree HAn -> Float
getLCESsim ta tb = let match = fromIntegral . snd $ getLCES ta tb
selfSimA = sim ta ta * cumDur ta
selfSimB = sim tb tb * cumDur tb
in (match * match) / fromIntegral (selfSimA * selfSimB)
getLCESsize :: Tree HAn -> Tree HAn -> Float
getLCESsize ta tb = let match = fromIntegral . sizeF . fst $ getLCES ta tb
in (match * match) / fromIntegral (size ta * size tb)
getLCESdepth :: Tree HAn -> Tree HAn -> Float
getLCESdepth ta tb = let match = avgDepthF . fst $ getLCES ta tb
in (match * match) / (avgDepth ta * avgDepth tb)
of two trees
getLCES :: Tree HAn -> Tree HAn -> ([Tree HAn], Int)
getLCES ta tb = (matchToTree ta (L.map fst (L.reverse m)),w) where
(LCES m w) = last . last $ lces ta tb
nonMatchPenal :: Int
nonMatchPenal = 2
lces :: (Sim t, GetDur t) => Tree t -> Tree t -> Vector (Vector LCES)
lces ta tb = n where
a = fromList (pot ta)
b = fromList (pot tb)
maxi :: Int -> [Int] -> LCES
maxi _ [] = emptyLCES
maxi i cb = (n!i) ! (L.maximumBy (comparing (\j -> getWeight $ ((n!i)!j))) cb)
maxj :: [Int] -> Int -> LCES
maxj [] _ = emptyLCES
maxj ca j = (n ! (L.maximumBy (comparing (\i -> getWeight $ ((n!i)!j))) ca))!j
recur 0 0 = if sim (getLabel (a ! 0)) (getLabel (b ! 0)) > 0
then LCES [(0,0)] (durSim (getLabel (a ! 0)) (getLabel (b ! 0)))
else emptyLCES
recur i j = findBestMatch (sim labi labj)
(min (getDur labi) (getDur labj)) i j mc mi mj where
mi = maxi i (getChildPns (b ! j))
mj = maxj (getChildPns (a ! i)) j
mc = wbMatch (getChild (a ! i)) (getChild $ b ! j) n
!labi = getLabel (a!i)
!labj = getLabel (b!j)
n = generate (length a) (generate (length b) . recur)
match and whether , in that case , one of the current nodes is not allready
findBestMatch :: Int -> Int -> Int -> Int -> LCES -> LCES -> LCES -> LCES
findBestMatch simv dur i j a b c
| simv <= 0 = (LCES mf (max (wf - (nonMatchPenal * dur)) 0 ))
| otherwise = if isFree first i j then (LCES ((i,j):mf) (wf+(dur*simv)))
else if wf /= ws then first
else if isFree second i j then (LCES ((i,j):ms) (ws+(dur*simv)))
else if wf /= wt then first
else if isFree second i j then (LCES ((i,j):mt) (wt+(dur*simv)))
else first where
(first@(LCES mf wf) :second@(LCES ms ws) :(LCES mt wt) :[]) = mySort [a,b,c]
Weighted Plannar Matching of a Bipartite Graph
wbMatch :: [Tree t] -> [Tree t] -> Vector (Vector LCES) -> LCES
# INLINE wbMatch #
wbMatch _ [] _ = emptyLCES
wbMatch [] _ _ = emptyLCES
wbMatch a b n = last $ last m where
subTree :: Int -> Int -> LCES
# INLINE subTree #
subTree i j = (n ! (fromJust . getPn $ a!!i)) ! (fromJust . getPn $ b!!j)
match, fill :: Int -> Int -> LCES
match i j = L.maximumBy (comparing getWeight) [maxPrv, minPrv, diagM] where
s = subTree i j
!hasMatch = getWeight s > 0
maxPrv = if not hasMatch then (m ! (i-1)) ! j
else if isFree ((m!(i-1)) ! j) i j then merge s ((m!(i-1)) ! j)
else ((m ! (i-1)) ! j)
minPrv = if not hasMatch then (m ! i) ! (j-1)
else if isFree ((m!i) ! (j-1)) i j then merge s ((m!i) ! (j-1))
else ((m ! i) ! (j-1))
diagM = merge s ((m ! (i-1)) ! (j-1))
fill 0 0 = subTree 0 0
fill 0 j = if getWeight (subTree 0 j) > getWeight ((m ! 0) ! (j-1))
then subTree 0 j else (m ! 0) ! (j-1)
fill i 0 = if getWeight (subTree i 0) > getWeight ((m ! (i-1)) ! 0)
then subTree i 0 else ((m ! (i-1)) ! 0)
fill i j = match i j
m = generate (L.length a) (generate (L.length b) . fill)
Some helper functions
data LCES = LCES ![(Int, Int)] !Int
getWeight :: LCES -> Int
# INLINE getWeight #
getWeight (LCES _ w) = w
durSim :: (Sim a, GetDur a) => a -> a -> Int
durSim a b = (sim a b) * (min (getDur a) (getDur b))
emptyLCES :: LCES
# INLINE emptyLCES #
emptyLCES = LCES [] 0
(!) :: Vector a -> Int -> a
(!) = unsafeIndex
last :: Vector a -> a
# INLINE last #
last = unsafeLast
cumDur :: (GetDur a) => Tree a -> Int
cumDur a = (getDur $ getLabel a) + (L.sum $ L.map cumDur (getChild a))
isFree :: LCES -> Int -> Int -> Bool
# INLINE isFree #
isFree (LCES [] _) _ _ = True
isFree (LCES ((previ, prevj):_) _) i j = ( i > previ && j > prevj)
mergest two lists with matches
merge :: LCES -> LCES -> LCES
merge (LCES a wa) (LCES b wb) = LCES (a L.++ b) (wa + wb)
mySort :: [LCES] -> [LCES]
mySort [a,b,c] = case (x >= y, y >= z, x >= z) of
(True , True , True ) -> [a,b,c]
(True , False, True ) -> [a,c,b]
(True , False, False) -> [c,a,b]
(False, True , True ) -> [b,a,c]
(False, True , False) -> [b,c,a]
(False, False, False) -> [c,b,a]
_ -> error "mySort: impossible"
where !x = getWeight a
!y = getWeight b
!z = getWeight c
mySort _ = error "mySort: unexpected argument"
|
dfb96eaa93e72f9f676deb6ae6e04f53c4259cacffb3afea0acee1d6b982aa48 | racket/racket7 | head.rkt | #lang racket/base
(require racket/date racket/string)
(provide empty-header
validate-header
extract-field
remove-field
insert-field
replace-field
extract-all-fields
append-headers
standard-message-header
data-lines->data
extract-addresses
assemble-address-field)
NB : I 've done a copied - code adaptation of a number of these definitions
;; into "bytes-compatible" versions. Finishing the rest will require some
;; kind of interface decision---that is, when you don't supply a header,
;; should the resulting operation be string-centric or bytes-centric?
;; Easiest just to stop here.
-- JBC 2006 - 07 - 31
(define CRLF (string #\return #\newline))
(define CRLF/bytes #"\r\n")
(define empty-header CRLF)
(define empty-header/bytes CRLF/bytes)
(define re:field-start (regexp "^[^ \t\n\r\v:\001-\032\"]*:"))
(define re:field-start/bytes #rx#"^[^ \t\n\r\v:\001-\032\"]*:")
(define re:continue (regexp "^[ \t\v]"))
(define re:continue/bytes #rx#"^[ \t\v]")
(define (validate-header s)
(if (bytes? s)
legal char check not needed per rfc 2822 , IIUC .
(let ([len (bytes-length s)])
(let loop ([offset 0])
(cond
[(and (= (+ offset 2) len)
(bytes=? CRLF/bytes (subbytes s offset len)))
(void)] ; validated
[(= offset len) (error 'validate-header "missing ending CRLF")]
[(or (regexp-match re:field-start/bytes s offset)
(regexp-match re:continue/bytes s offset))
(let ([m (regexp-match-positions #rx#"\r\n" s offset)])
(if m
(loop (cdar m))
(error 'validate-header "missing ending CRLF")))]
[else (error 'validate-header "ill-formed header at ~s"
(subbytes s offset (bytes-length s)))])))
;; otherwise it should be a string:
(begin
(let ([m (regexp-match #rx"[^\000-\377]" s)])
(when m
(error 'validate-header "non-Latin-1 character in string: ~v" (car m))))
(let ([len (string-length s)])
(let loop ([offset 0])
(cond
[(and (= (+ offset 2) len)
(string=? CRLF (substring s offset len)))
(void)] ; validated
[(= offset len) (error 'validate-header "missing ending CRLF")]
[(or (regexp-match re:field-start s offset)
(regexp-match re:continue s offset))
(let ([m (regexp-match-positions #rx"\r\n" s offset)])
(if m
(loop (cdar m))
(error 'validate-header "missing ending CRLF")))]
[else (error 'validate-header "ill-formed header at ~s"
(substring s offset (string-length s)))]))))))
(define (make-field-start-regexp field)
(regexp (format "(^|[\r][\n])(~a: *)" (regexp-quote field #f))))
(define (make-field-start-regexp/bytes field)
(byte-regexp (bytes-append #"(^|[\r][\n])("(regexp-quote field #f) #": *)")))
(define (extract-field field header)
(if (bytes? header)
(cond
[(bytes? field)
(let ([m (regexp-match-positions (make-field-start-regexp/bytes field)
header)])
(and m
(let ([s (subbytes header
(cdaddr m)
(bytes-length header))])
(let ([m (regexp-match-positions #rx#"[\r][\n][^: \r\n\"]*:" s)])
(if m
(subbytes s 0 (caar m))
;; Rest of header is this field, but strip trailing CRLFCRLF:
(regexp-replace #rx#"\r\n\r\n$" s ""))))))]
[else (raise-argument-error 'extract-field "bytes field for bytes header" 0 field header)])
otherwise header & field should be strings :
(cond
[(string? field)
(let ([m (regexp-match-positions (make-field-start-regexp field)
header)])
(and m
(let ([s (substring header
(cdaddr m)
(string-length header))])
(let ([m (regexp-match-positions #rx"[\r][\n][^: \r\n\"]*:" s)])
(if m
(substring s 0 (caar m))
;; Rest of header is this field, but strip trailing CRLFCRLF:
(regexp-replace #rx"\r\n\r\n$" s ""))))))]
[else (raise-argument-error 'extract-field "string field for string header" 0 field header)])))
(define (replace-field field data header)
(if (bytes? header)
(let ([m (regexp-match-positions (make-field-start-regexp/bytes field)
header)])
(if m
(let* ([pre (subbytes header 0 (caaddr m))]
[s (subbytes header (cdaddr m))]
[m (regexp-match-positions #rx#"[\r][\n][^: \r\n\"]*:" s)]
[rest (if m (subbytes s (+ 2 (caar m))) empty-header/bytes)])
(bytes-append pre (if data (insert-field field data rest) rest)))
(if data (insert-field field data header) header)))
otherwise header & field & data should be strings :
(let ([m (regexp-match-positions (make-field-start-regexp field) header)])
(if m
(let* ([pre (substring header 0 (caaddr m))]
[s (substring header (cdaddr m))]
[m (regexp-match-positions #rx"[\r][\n][^: \r\n\"]*:" s)]
[rest (if m (substring s (+ 2 (caar m))) empty-header)])
(string-append pre (if data (insert-field field data rest) rest)))
(if data (insert-field field data header) header)))))
(define (remove-field field header)
(replace-field field #f header))
(define (insert-field field data header)
(if (bytes? header)
(let ([field (bytes-append field #": "data #"\r\n")])
(bytes-append field header))
;; otherwise field, data, & header should be strings:
(let ([field (format "~a: ~a\r\n" field data)])
(string-append field header))))
(define (append-headers a b)
(if (bytes? a)
(let ([alen (bytes-length a)])
(if (> alen 1)
(bytes-append (subbytes a 0 (- alen 2)) b)
(error 'append-headers "first argument is not a header: ~a" a)))
;; otherwise, a & b should be strings:
(let ([alen (string-length a)])
(if (> alen 1)
(string-append (substring a 0 (- alen 2)) b)
(error 'append-headers "first argument is not a header: ~a" a)))))
(define (extract-all-fields header)
(if (bytes? header)
(let ([re #rx#"(^|[\r][\n])(([^\r\n:\"]*): *)"])
(let loop ([start 0])
(let ([m (regexp-match-positions re header start)])
(if m
(let ([start (cdaddr m)]
[field-name (subbytes header (caaddr (cdr m))
(cdaddr (cdr m)))])
(let ([m2 (regexp-match-positions
#rx#"\r\n[^: \r\n\"]*:"
header
start)])
(if m2
(cons (cons field-name
(subbytes header start (caar m2)))
(loop (caar m2)))
;; Rest of header is this field, but strip trailing CRLFCRLF:
(list
(cons field-name
(regexp-replace #rx#"\r\n\r\n$"
(subbytes header start (bytes-length header))
""))))))
;; malformed header:
null))))
;; otherwise, header should be a string:
(let ([re #rx"(^|[\r][\n])(([^\r\n:\"]*): *)"])
(let loop ([start 0])
(let ([m (regexp-match-positions re header start)])
(if m
(let ([start (cdaddr m)]
[field-name (substring header (caaddr (cdr m)) (cdaddr (cdr m)))])
(let ([m2 (regexp-match-positions
#rx"\r\n[^: \r\n\"]*:" header start)])
(if m2
(cons (cons field-name
(substring header start (caar m2)))
(loop (caar m2)))
;; Rest of header is this field, but strip trailing CRLFCRLF:
(list
(cons field-name
(regexp-replace #rx"\r\n\r\n$"
(substring header start (string-length header))
""))))))
;; malformed header:
null))))))
;; It's slightly less obvious how to generalize the functions that don't
;; accept a header as input; for lack of an obvious solution (and free time),
I 'm stopping the string->bytes translation here . -- JBC , 2006 - 07 - 31
(define (standard-message-header from tos ccs bccs subject)
(let ([h (insert-field
"Subject" subject
(insert-field
"Date" (parameterize ([date-display-format 'rfc2822])
(date->string (seconds->date (current-seconds)) #t))
CRLF))])
;; NOTE: bccs don't go into the header; that's why they're "blind"
(let ([h (if (null? ccs)
h
(insert-field "CC" (assemble-address-field ccs) h))])
(let ([h (if (null? tos)
h
(insert-field "To" (assemble-address-field tos) h))])
(insert-field "From" from h)))))
(define (splice l sep)
(if (null? l)
""
(format "~a~a"
(car l)
(apply string-append
(map (lambda (n) (format "~a~a" sep n))
(cdr l))))))
(define (data-lines->data datas)
(splice datas "\r\n\t"))
;; Extracting Addresses ;;
(define blank "[ \t\n\r\v]")
(define nonblank "[^ \t\n\r\v]")
(define re:all-blank (regexp (format "^~a*$" blank)))
(define re:quoted (regexp "\"[^\"]*\""))
(define re:parened (regexp "[(][^)]*[)]"))
(define re:comma (regexp ","))
(define re:comma-separated (regexp "([^,]*),(.*)"))
(define (extract-addresses s form)
(unless (memq form '(name address full all))
(raise-type-error 'extract-addresses
"form: 'name, 'address, 'full, or 'all"
form))
(if (or (not s) (regexp-match re:all-blank s))
null
(let loop ([prefix ""][s s])
Which comes first - a quote or a comma ?
(let* ([mq1 (regexp-match-positions re:quoted s)]
[mq2 (regexp-match-positions re:parened s)]
[mq (if (and mq1 mq2)
(if (< (caar mq1) (caar mq2)) mq1 mq2)
(or mq1 mq2))]
[mc (regexp-match-positions re:comma s)])
(if (and mq mc (< (caar mq) (caar mc) (cdar mq)))
;; Quote contains a comma
(loop (string-append
prefix
(substring s 0 (cdar mq)))
(substring s (cdar mq) (string-length s)))
;; Normal comma parsing:
(let ([m (regexp-match re:comma-separated s)])
(if m
(let ([n (extract-one-name (string-append prefix (cadr m)) form)]
[rest (extract-addresses (caddr m) form)])
(cons n rest))
(let ([n (extract-one-name (string-append prefix s) form)])
(list n)))))))))
(define (select-result form name addr full)
(case form
[(name) name]
[(address) addr]
[(full) full]
[(all) (list name addr full)]))
(define (one-result form s)
(select-result form s s s))
(define re:quoted-name (regexp (format "^~a*(\"[^\"]*\")(.*)" blank)))
(define re:parened-name (regexp (format "(.*)[(]([^)]*)[)]~a*$" blank)))
(define re:simple-name (regexp (format "^~a*(~a.*)(<.*>)~a*$" blank nonblank blank)))
(define re:normal-name (regexp (format "~a*<([^>]*)>~a*" blank blank)))
(define re:double-less (regexp "<.*<"))
(define re:double-greater (regexp ">.*>"))
(define re:bad-chars (regexp "[,\"()<>]"))
(define re:tail-blanks (regexp (format "~a+$" blank)))
(define re:head-blanks (regexp (format "^~a+" blank)))
(define (extract-one-name orig form)
(let loop ([s orig][form form])
(cond
;; ?!?!? Where does the "addr (name)" standard come from ?!?!?
[(regexp-match re:parened-name s)
=> (lambda (m)
(let ([name (caddr m)]
[all (loop (cadr m) 'all)])
(select-result
form
(if (string=? (car all) (cadr all)) name (car all))
(cadr all)
(format "~a (~a)" (caddr all) name))))]
[(regexp-match re:quoted-name s)
=> (lambda (m)
(let ([name (cadr m)]
[addr (extract-angle-addr (caddr m) s)])
(select-result form name addr
(format "~a <~a>" name addr))))]
[(regexp-match re:simple-name s)
=> (lambda (m)
(let ([name (regexp-replace (format "~a*$" blank) (cadr m) "")]
[addr (extract-angle-addr (caddr m) s)])
(select-result form name addr
(format "~a <~a>" name addr))))]
[(or (regexp-match "<" s) (regexp-match ">" s))
(one-result form (extract-angle-addr s orig))]
[else (one-result form (extract-simple-addr s orig))])))
(define (extract-angle-addr s orig)
(if (or (regexp-match re:double-less s) (regexp-match re:double-greater s))
(error 'extract-address "too many angle brackets: ~a" s)
(let ([m (regexp-match re:normal-name s)])
(if m
(extract-simple-addr (cadr m) orig)
(error 'extract-address "cannot parse address: ~a" orig)))))
(define (extract-simple-addr s orig)
(cond [(regexp-match re:bad-chars s)
(error 'extract-address "cannot parse address: ~a" orig)]
[else
;; final whitespace strip
(regexp-replace re:tail-blanks
(regexp-replace re:head-blanks s "")
"")]))
(define (assemble-address-field addresses)
(if (null? addresses)
""
(let loop ([addresses (cdr addresses)]
[s (car addresses)]
[len (string-length (car addresses))])
(if (null? addresses)
s
(let* ([addr (car addresses)]
[alen (string-length addr)])
(if (<= 72 (+ len alen))
(loop (cdr addresses)
(format "~a,~a~a~a~a"
s #\return #\linefeed
#\tab addr)
alen)
(loop (cdr addresses)
(format "~a, ~a" s addr)
(+ len alen 2))))))))
| null | https://raw.githubusercontent.com/racket/racket7/5dbb62c6bbec198b4a790f1dc08fef0c45c2e32b/racket/collects/net/head.rkt | racket | into "bytes-compatible" versions. Finishing the rest will require some
kind of interface decision---that is, when you don't supply a header,
should the resulting operation be string-centric or bytes-centric?
Easiest just to stop here.
validated
otherwise it should be a string:
validated
Rest of header is this field, but strip trailing CRLFCRLF:
Rest of header is this field, but strip trailing CRLFCRLF:
otherwise field, data, & header should be strings:
otherwise, a & b should be strings:
Rest of header is this field, but strip trailing CRLFCRLF:
malformed header:
otherwise, header should be a string:
Rest of header is this field, but strip trailing CRLFCRLF:
malformed header:
It's slightly less obvious how to generalize the functions that don't
accept a header as input; for lack of an obvious solution (and free time),
NOTE: bccs don't go into the header; that's why they're "blind"
Extracting Addresses ;;
Quote contains a comma
Normal comma parsing:
?!?!? Where does the "addr (name)" standard come from ?!?!?
final whitespace strip | #lang racket/base
(require racket/date racket/string)
(provide empty-header
validate-header
extract-field
remove-field
insert-field
replace-field
extract-all-fields
append-headers
standard-message-header
data-lines->data
extract-addresses
assemble-address-field)
NB : I 've done a copied - code adaptation of a number of these definitions
-- JBC 2006 - 07 - 31
(define CRLF (string #\return #\newline))
(define CRLF/bytes #"\r\n")
(define empty-header CRLF)
(define empty-header/bytes CRLF/bytes)
(define re:field-start (regexp "^[^ \t\n\r\v:\001-\032\"]*:"))
(define re:field-start/bytes #rx#"^[^ \t\n\r\v:\001-\032\"]*:")
(define re:continue (regexp "^[ \t\v]"))
(define re:continue/bytes #rx#"^[ \t\v]")
(define (validate-header s)
(if (bytes? s)
legal char check not needed per rfc 2822 , IIUC .
(let ([len (bytes-length s)])
(let loop ([offset 0])
(cond
[(and (= (+ offset 2) len)
(bytes=? CRLF/bytes (subbytes s offset len)))
[(= offset len) (error 'validate-header "missing ending CRLF")]
[(or (regexp-match re:field-start/bytes s offset)
(regexp-match re:continue/bytes s offset))
(let ([m (regexp-match-positions #rx#"\r\n" s offset)])
(if m
(loop (cdar m))
(error 'validate-header "missing ending CRLF")))]
[else (error 'validate-header "ill-formed header at ~s"
(subbytes s offset (bytes-length s)))])))
(begin
(let ([m (regexp-match #rx"[^\000-\377]" s)])
(when m
(error 'validate-header "non-Latin-1 character in string: ~v" (car m))))
(let ([len (string-length s)])
(let loop ([offset 0])
(cond
[(and (= (+ offset 2) len)
(string=? CRLF (substring s offset len)))
[(= offset len) (error 'validate-header "missing ending CRLF")]
[(or (regexp-match re:field-start s offset)
(regexp-match re:continue s offset))
(let ([m (regexp-match-positions #rx"\r\n" s offset)])
(if m
(loop (cdar m))
(error 'validate-header "missing ending CRLF")))]
[else (error 'validate-header "ill-formed header at ~s"
(substring s offset (string-length s)))]))))))
(define (make-field-start-regexp field)
(regexp (format "(^|[\r][\n])(~a: *)" (regexp-quote field #f))))
(define (make-field-start-regexp/bytes field)
(byte-regexp (bytes-append #"(^|[\r][\n])("(regexp-quote field #f) #": *)")))
(define (extract-field field header)
(if (bytes? header)
(cond
[(bytes? field)
(let ([m (regexp-match-positions (make-field-start-regexp/bytes field)
header)])
(and m
(let ([s (subbytes header
(cdaddr m)
(bytes-length header))])
(let ([m (regexp-match-positions #rx#"[\r][\n][^: \r\n\"]*:" s)])
(if m
(subbytes s 0 (caar m))
(regexp-replace #rx#"\r\n\r\n$" s ""))))))]
[else (raise-argument-error 'extract-field "bytes field for bytes header" 0 field header)])
otherwise header & field should be strings :
(cond
[(string? field)
(let ([m (regexp-match-positions (make-field-start-regexp field)
header)])
(and m
(let ([s (substring header
(cdaddr m)
(string-length header))])
(let ([m (regexp-match-positions #rx"[\r][\n][^: \r\n\"]*:" s)])
(if m
(substring s 0 (caar m))
(regexp-replace #rx"\r\n\r\n$" s ""))))))]
[else (raise-argument-error 'extract-field "string field for string header" 0 field header)])))
(define (replace-field field data header)
(if (bytes? header)
(let ([m (regexp-match-positions (make-field-start-regexp/bytes field)
header)])
(if m
(let* ([pre (subbytes header 0 (caaddr m))]
[s (subbytes header (cdaddr m))]
[m (regexp-match-positions #rx#"[\r][\n][^: \r\n\"]*:" s)]
[rest (if m (subbytes s (+ 2 (caar m))) empty-header/bytes)])
(bytes-append pre (if data (insert-field field data rest) rest)))
(if data (insert-field field data header) header)))
otherwise header & field & data should be strings :
(let ([m (regexp-match-positions (make-field-start-regexp field) header)])
(if m
(let* ([pre (substring header 0 (caaddr m))]
[s (substring header (cdaddr m))]
[m (regexp-match-positions #rx"[\r][\n][^: \r\n\"]*:" s)]
[rest (if m (substring s (+ 2 (caar m))) empty-header)])
(string-append pre (if data (insert-field field data rest) rest)))
(if data (insert-field field data header) header)))))
(define (remove-field field header)
(replace-field field #f header))
(define (insert-field field data header)
(if (bytes? header)
(let ([field (bytes-append field #": "data #"\r\n")])
(bytes-append field header))
(let ([field (format "~a: ~a\r\n" field data)])
(string-append field header))))
(define (append-headers a b)
(if (bytes? a)
(let ([alen (bytes-length a)])
(if (> alen 1)
(bytes-append (subbytes a 0 (- alen 2)) b)
(error 'append-headers "first argument is not a header: ~a" a)))
(let ([alen (string-length a)])
(if (> alen 1)
(string-append (substring a 0 (- alen 2)) b)
(error 'append-headers "first argument is not a header: ~a" a)))))
(define (extract-all-fields header)
(if (bytes? header)
(let ([re #rx#"(^|[\r][\n])(([^\r\n:\"]*): *)"])
(let loop ([start 0])
(let ([m (regexp-match-positions re header start)])
(if m
(let ([start (cdaddr m)]
[field-name (subbytes header (caaddr (cdr m))
(cdaddr (cdr m)))])
(let ([m2 (regexp-match-positions
#rx#"\r\n[^: \r\n\"]*:"
header
start)])
(if m2
(cons (cons field-name
(subbytes header start (caar m2)))
(loop (caar m2)))
(list
(cons field-name
(regexp-replace #rx#"\r\n\r\n$"
(subbytes header start (bytes-length header))
""))))))
null))))
(let ([re #rx"(^|[\r][\n])(([^\r\n:\"]*): *)"])
(let loop ([start 0])
(let ([m (regexp-match-positions re header start)])
(if m
(let ([start (cdaddr m)]
[field-name (substring header (caaddr (cdr m)) (cdaddr (cdr m)))])
(let ([m2 (regexp-match-positions
#rx"\r\n[^: \r\n\"]*:" header start)])
(if m2
(cons (cons field-name
(substring header start (caar m2)))
(loop (caar m2)))
(list
(cons field-name
(regexp-replace #rx"\r\n\r\n$"
(substring header start (string-length header))
""))))))
null))))))
I 'm stopping the string->bytes translation here . -- JBC , 2006 - 07 - 31
(define (standard-message-header from tos ccs bccs subject)
(let ([h (insert-field
"Subject" subject
(insert-field
"Date" (parameterize ([date-display-format 'rfc2822])
(date->string (seconds->date (current-seconds)) #t))
CRLF))])
(let ([h (if (null? ccs)
h
(insert-field "CC" (assemble-address-field ccs) h))])
(let ([h (if (null? tos)
h
(insert-field "To" (assemble-address-field tos) h))])
(insert-field "From" from h)))))
(define (splice l sep)
(if (null? l)
""
(format "~a~a"
(car l)
(apply string-append
(map (lambda (n) (format "~a~a" sep n))
(cdr l))))))
(define (data-lines->data datas)
(splice datas "\r\n\t"))
(define blank "[ \t\n\r\v]")
(define nonblank "[^ \t\n\r\v]")
(define re:all-blank (regexp (format "^~a*$" blank)))
(define re:quoted (regexp "\"[^\"]*\""))
(define re:parened (regexp "[(][^)]*[)]"))
(define re:comma (regexp ","))
(define re:comma-separated (regexp "([^,]*),(.*)"))
(define (extract-addresses s form)
(unless (memq form '(name address full all))
(raise-type-error 'extract-addresses
"form: 'name, 'address, 'full, or 'all"
form))
(if (or (not s) (regexp-match re:all-blank s))
null
(let loop ([prefix ""][s s])
Which comes first - a quote or a comma ?
(let* ([mq1 (regexp-match-positions re:quoted s)]
[mq2 (regexp-match-positions re:parened s)]
[mq (if (and mq1 mq2)
(if (< (caar mq1) (caar mq2)) mq1 mq2)
(or mq1 mq2))]
[mc (regexp-match-positions re:comma s)])
(if (and mq mc (< (caar mq) (caar mc) (cdar mq)))
(loop (string-append
prefix
(substring s 0 (cdar mq)))
(substring s (cdar mq) (string-length s)))
(let ([m (regexp-match re:comma-separated s)])
(if m
(let ([n (extract-one-name (string-append prefix (cadr m)) form)]
[rest (extract-addresses (caddr m) form)])
(cons n rest))
(let ([n (extract-one-name (string-append prefix s) form)])
(list n)))))))))
(define (select-result form name addr full)
(case form
[(name) name]
[(address) addr]
[(full) full]
[(all) (list name addr full)]))
(define (one-result form s)
(select-result form s s s))
(define re:quoted-name (regexp (format "^~a*(\"[^\"]*\")(.*)" blank)))
(define re:parened-name (regexp (format "(.*)[(]([^)]*)[)]~a*$" blank)))
(define re:simple-name (regexp (format "^~a*(~a.*)(<.*>)~a*$" blank nonblank blank)))
(define re:normal-name (regexp (format "~a*<([^>]*)>~a*" blank blank)))
(define re:double-less (regexp "<.*<"))
(define re:double-greater (regexp ">.*>"))
(define re:bad-chars (regexp "[,\"()<>]"))
(define re:tail-blanks (regexp (format "~a+$" blank)))
(define re:head-blanks (regexp (format "^~a+" blank)))
(define (extract-one-name orig form)
(let loop ([s orig][form form])
(cond
[(regexp-match re:parened-name s)
=> (lambda (m)
(let ([name (caddr m)]
[all (loop (cadr m) 'all)])
(select-result
form
(if (string=? (car all) (cadr all)) name (car all))
(cadr all)
(format "~a (~a)" (caddr all) name))))]
[(regexp-match re:quoted-name s)
=> (lambda (m)
(let ([name (cadr m)]
[addr (extract-angle-addr (caddr m) s)])
(select-result form name addr
(format "~a <~a>" name addr))))]
[(regexp-match re:simple-name s)
=> (lambda (m)
(let ([name (regexp-replace (format "~a*$" blank) (cadr m) "")]
[addr (extract-angle-addr (caddr m) s)])
(select-result form name addr
(format "~a <~a>" name addr))))]
[(or (regexp-match "<" s) (regexp-match ">" s))
(one-result form (extract-angle-addr s orig))]
[else (one-result form (extract-simple-addr s orig))])))
(define (extract-angle-addr s orig)
(if (or (regexp-match re:double-less s) (regexp-match re:double-greater s))
(error 'extract-address "too many angle brackets: ~a" s)
(let ([m (regexp-match re:normal-name s)])
(if m
(extract-simple-addr (cadr m) orig)
(error 'extract-address "cannot parse address: ~a" orig)))))
(define (extract-simple-addr s orig)
(cond [(regexp-match re:bad-chars s)
(error 'extract-address "cannot parse address: ~a" orig)]
[else
(regexp-replace re:tail-blanks
(regexp-replace re:head-blanks s "")
"")]))
(define (assemble-address-field addresses)
(if (null? addresses)
""
(let loop ([addresses (cdr addresses)]
[s (car addresses)]
[len (string-length (car addresses))])
(if (null? addresses)
s
(let* ([addr (car addresses)]
[alen (string-length addr)])
(if (<= 72 (+ len alen))
(loop (cdr addresses)
(format "~a,~a~a~a~a"
s #\return #\linefeed
#\tab addr)
alen)
(loop (cdr addresses)
(format "~a, ~a" s addr)
(+ len alen 2))))))))
|
66cc7d7819a88e4c517216fb05047598dbbcfecded22ccd3b94d4c24dc4a3571 | jrm-code-project/LISP-Machine | bootstrap.lisp | -*- Mode : LISP ; Package : SITE - DATA - EDIT ; ; : CL -*-
Copyright ( c ) Lisp Machine Inc. , 1986 .
;;; NOW. SPECIAL BOOTSTRAP CONSIDERATIONS ARE DEALT WITH.
3 - May-86 12:34:23 -GJC
(DEFUN BOOTSTRAP-SITE-INFORMATION (&OPTIONAL DISK)
(LET ((INFO (BOOTSTRAP-READ-INFORMATION (ECASE DISK
(NIL NIL)
(:SAVE T)))))
(LET ((DATA (BOOTSTRAP-READ-SITE-DATA (GETF INFO 'SITE-DIR))))
(LET ((TRANS (BOOTSTRAP-CHECK-SYS-TRANSLATIONS (GETF INFO 'SITE-DIR)
(SEND (BOOTSTRAP-LOOKUP-HOST (GETF INFO 'NAME)
(GETF DATA 'SI:HOST-ALIST))
:NAME))))
(BOOTSTRAP-SITE-INFORMATION-DOIT DATA INFO TRANS)))))
(DEFVAR *BOOTSTRAP-SITE-VARS* '(SI:HOST-ALIST SI:SITE-NAME SI:SITE-OPTION-ALIST SI:MACHINE-LOCATION-ALIST))
(DEFVAR *BOOTSTRAP-OLD* NIL)
(DEFUN BOOTSTRAP-SITE-INFORMATION-DOIT (DATA INFO TRANS)
(DOLIST (VAR *BOOTSTRAP-SITE-VARS*)
(SETF (GETF *BOOTSTRAP-OLD* VAR) (SYMBOL-VALUE VAR)))
(SETF (GETF *BOOTSTRAP-OLD* 'PACK-NAME) (FORMAT NIL "~{~A~^ ~}" (MULTIPLE-VALUE-LIST (SI:GET-PACK-NAME))))
(DOLIST (VAR *BOOTSTRAP-SITE-VARS*)
(SET VAR (GETF DATA VAR)))
(SI:SET-PACK-NAME (GETF INFO 'NAME))
(BOOTSTRAP-SITE-INITIALIZATIONS)
(EVAL TRANS)
(COND ((GETF INFO 'LOD)
(SETQ *BOOTSTRAP-OLD* NIL)
(SI:DISK-SAVE (GETF INFO 'LOD)))))
(DEFUN BOOTSTRAP-SITE-INITIALIZATIONS ()
(FORMAT T "~&Running bootstrap site initializations...")
AN INIT , BUT IN WRONG ORDER IN INIT LIST .
(LET ((SI:HOST-TABLE-FILE-ALIST NIL))
;; must bind above to keep reset-non-site-hosts from reading site files again.
(INITIALIZATIONS 'SI:SITE-INITIALIZATION-LIST T))
(CHAOS:RESET T)
(FORMAT T " done.~%"))
(DEFUN BOOTSTRAP-SITE-REVERT ()
(DOLIST (VAR *BOOTSTRAP-SITE-VARS*)
(SET VAR (GETF *BOOTSTRAP-OLD* VAR)))
(SI:SET-PACK-NAME (GETF *BOOTSTRAP-OLD* 'PACK-NAME))
(BOOTSTRAP-SITE-INITIALIZATIONS))
(DEFUN BOOTSTRAP-READ-INFORMATION (DISK-SAVEP)
(LET (NAME SITE-DIR LOD)
(DO ()
((SETQ NAME (PROMPT-AND-READ :STRING-OR-NIL
"~& Short name of this machine: "))))
(DO ()
((WHEN (AND (SETQ SITE-DIR (CATCH-ERROR (PROMPT-AND-READ :PATHNAME-OR-NIL "~& Site file directory : ")))
(SETQ SITE-DIR (SEND SITE-DIR :NEW-PATHNAME :HOST "LM"
:NAME "SITE" :TYPE "LISP" :VERSION :NEWEST)))
(LET ((TEMP (OPEN SITE-DIR :ERROR NIL :direction nil)))
(COND ((ERRORP TEMP)
(FORMAT T "Incorrect Site File directory: ~S~%" site-dir)
(send temp :report standard-output)
nil)
('else
(setq site-dir (send temp :truename))))))))
(when disk-savep
(LET ((L (SUBSET #'(LAMBDA (X)
(STRING-EQUAL "LOD" (CAR X) :END2 3))
(SI:PARTITION-LIST)))
(CB (SI:CURRENT-BAND)))
(DO ((x))
((PROGN (FORMAT T "~&Available LOD Partitions:~%")
(DOLIST (P L)
(FORMAT T "~4A ~14A ~25S ~5D blocks.~%"
(NTH 0 P)
(COND ((STRING-EQUAL CB (NTH 0 P))
"(current band)")
((STRING-EQUAL (NTH 3 P) "")
"(unused band)")
('ELSE
"(a lisp band)"))
(NTH 3 P)
(NTH 2 P)))
(SETQ LOD (PROMPT-AND-READ :STRING-OR-NIL "~& LOD band to save to :"))
(setq x lod)
(WHEN (STRING-EQUAL "LOD" x :END2 3)
(SETQ x (SUBSTRING x 3)))
(COND ((FIXP (CATCH-ERROR (PARSE-INTEGER x)))
(SETQ x (PARSE-INTEGER x))
(LET ((FL (FORMAT NIL "LOD~D" x)))
(DO ((P L (CDR P)))
((NULL P)
(FORMAT T "Not an available load partition: ~S" LOD)
NIL)
(IF (string-equal (caar p) fl)
(return (setq lod x))))))))))))
(list 'NAME name 'SITE-DIR site-dir 'LOD lod)))
(DEFUN BOOTSTRAP-READ-SITE-DATA (DIR)
(LET ((FS (LIST (SEND DIR :NEW-PATHNAME :NAME "SITE" :TYPE "QFASL" :VERSION :NEWEST)
(SEND DIR :NEW-PATHNAME :NAME "HSTTBL" :TYPE "QFASL" :VERSION :NEWEST)
(SEND DIR :NEW-PATHNAME :NAME "LMLOCS" :TYPE "QFASL" :VERSION :NEWEST))))
(remprop 'si:machine-location-alist :source-file)
(PROGV *BOOTSTRAP-SITE-VARS*
(MAKE-LIST (LENGTH *BOOTSTRAP-SITE-VARS*))
(DOLIST (F FS)
(LOAD F :SET-DEFAULT-PATHNAME NIL))
(DOLIST (ELEM SI:HOST-ALIST)
(SI:GET-ALIST-ELEM-HOST ELEM))
(MAPCAN #'(LAMBDA (VAR)
(LIST VAR (SYMBOL-VALUE VAR)))
*BOOTSTRAP-SITE-VARS*))))
(DEFUN BOOTSTRAP-LOOKUP-HOST (NAME ALIST)
(OR (DOLIST (A ALIST)
(WHEN (MEM #'STRING-EQUAL NAME (SI:HOST-NAME-LIST A))
(RETURN (SI:HOST-INSTANCE A))))
(FERROR NIL "Host ~S not found in bootstrap data" NAME)))
(DEFVAR *RELEASE-ROOT-NAME* "RELEASE-3")
(DEFVAR *RELEASE-ROOT-DEPTH* 5)
(DEFUN BOOTSTRAP-CHECK-SYS-TRANSLATIONS (DIR SYS-HOST-NAME)
(LET* ((NP (SEND DIR :NEW-PATHNAME :NAME NIL :TYPE NIL :VERSION NIL))
(SP (SEND DIR :NEW-PATHNAME :NAME "SYS" :TYPE "TRANSLATIONS" :VERSION :NEWEST))
(FORM `(FS:SET-LOGICAL-PATHNAME-HOST "SYS"
:PHYSICAL-HOST ,SYS-HOST-NAME
:TRANSLATIONS '(("CHAOS;" ,(SEND NP :STRING-FOR-HOST))
("SITE;" ,(SEND NP :STRING-FOR-HOST))
,@(DO ((L NIL
(CONS (LIST (FORMAT NIL "~{~A;~}"
(MAKE-LIST DEPTH :INITIAL-ELEMENT '*))
(SEND (SEND NP :NEW-PATHNAME
:DIRECTORY (CONS *RELEASE-ROOT-NAME*
(MAKE-LIST DEPTH
:INITIAL-ELEMENT :WILD)))
:STRING-FOR-HOST))
L))
(DEPTH *RELEASE-ROOT-DEPTH* (1- DEPTH)))
((ZEROP DEPTH)
L))))))
(FLET ((WRITE-FORM ()
(WITH-OPEN-FILE (S SP :DIRECTION :OUTPUT)
(FORMAT S ";; SYS.TRANSLATIONS WRITTEN BY BOOTSTRAP SITE GENERATOR~%")
(PPRINT FORM S)
(TERPRI S))))
(COND ((NOT (PROBE-FILE SP))
(WRITE-FORM))
((WITH-OPEN-FILE (S SP)
(NOT (EQUALP FORM (LET ((*PACKAGE* (FIND-PACKAGE "USER"))
(*READTABLE* (SI:FIND-READTABLE-NAMED "ZL")))
(READ S)))))
(WRITE-FORM)))
FORM)))
| null | https://raw.githubusercontent.com/jrm-code-project/LISP-Machine/0a448d27f40761fafabe5775ffc550637be537b2/lambda/network/edit/bootstrap.lisp | lisp | Package : SITE - DATA - EDIT ; ; : CL -*-
NOW. SPECIAL BOOTSTRAP CONSIDERATIONS ARE DEALT WITH.
must bind above to keep reset-non-site-hosts from reading site files again. | Copyright ( c ) Lisp Machine Inc. , 1986 .
3 - May-86 12:34:23 -GJC
(DEFUN BOOTSTRAP-SITE-INFORMATION (&OPTIONAL DISK)
(LET ((INFO (BOOTSTRAP-READ-INFORMATION (ECASE DISK
(NIL NIL)
(:SAVE T)))))
(LET ((DATA (BOOTSTRAP-READ-SITE-DATA (GETF INFO 'SITE-DIR))))
(LET ((TRANS (BOOTSTRAP-CHECK-SYS-TRANSLATIONS (GETF INFO 'SITE-DIR)
(SEND (BOOTSTRAP-LOOKUP-HOST (GETF INFO 'NAME)
(GETF DATA 'SI:HOST-ALIST))
:NAME))))
(BOOTSTRAP-SITE-INFORMATION-DOIT DATA INFO TRANS)))))
(DEFVAR *BOOTSTRAP-SITE-VARS* '(SI:HOST-ALIST SI:SITE-NAME SI:SITE-OPTION-ALIST SI:MACHINE-LOCATION-ALIST))
(DEFVAR *BOOTSTRAP-OLD* NIL)
(DEFUN BOOTSTRAP-SITE-INFORMATION-DOIT (DATA INFO TRANS)
(DOLIST (VAR *BOOTSTRAP-SITE-VARS*)
(SETF (GETF *BOOTSTRAP-OLD* VAR) (SYMBOL-VALUE VAR)))
(SETF (GETF *BOOTSTRAP-OLD* 'PACK-NAME) (FORMAT NIL "~{~A~^ ~}" (MULTIPLE-VALUE-LIST (SI:GET-PACK-NAME))))
(DOLIST (VAR *BOOTSTRAP-SITE-VARS*)
(SET VAR (GETF DATA VAR)))
(SI:SET-PACK-NAME (GETF INFO 'NAME))
(BOOTSTRAP-SITE-INITIALIZATIONS)
(EVAL TRANS)
(COND ((GETF INFO 'LOD)
(SETQ *BOOTSTRAP-OLD* NIL)
(SI:DISK-SAVE (GETF INFO 'LOD)))))
(DEFUN BOOTSTRAP-SITE-INITIALIZATIONS ()
(FORMAT T "~&Running bootstrap site initializations...")
AN INIT , BUT IN WRONG ORDER IN INIT LIST .
(LET ((SI:HOST-TABLE-FILE-ALIST NIL))
(INITIALIZATIONS 'SI:SITE-INITIALIZATION-LIST T))
(CHAOS:RESET T)
(FORMAT T " done.~%"))
(DEFUN BOOTSTRAP-SITE-REVERT ()
(DOLIST (VAR *BOOTSTRAP-SITE-VARS*)
(SET VAR (GETF *BOOTSTRAP-OLD* VAR)))
(SI:SET-PACK-NAME (GETF *BOOTSTRAP-OLD* 'PACK-NAME))
(BOOTSTRAP-SITE-INITIALIZATIONS))
(DEFUN BOOTSTRAP-READ-INFORMATION (DISK-SAVEP)
(LET (NAME SITE-DIR LOD)
(DO ()
((SETQ NAME (PROMPT-AND-READ :STRING-OR-NIL
"~& Short name of this machine: "))))
(DO ()
((WHEN (AND (SETQ SITE-DIR (CATCH-ERROR (PROMPT-AND-READ :PATHNAME-OR-NIL "~& Site file directory : ")))
(SETQ SITE-DIR (SEND SITE-DIR :NEW-PATHNAME :HOST "LM"
:NAME "SITE" :TYPE "LISP" :VERSION :NEWEST)))
(LET ((TEMP (OPEN SITE-DIR :ERROR NIL :direction nil)))
(COND ((ERRORP TEMP)
(FORMAT T "Incorrect Site File directory: ~S~%" site-dir)
(send temp :report standard-output)
nil)
('else
(setq site-dir (send temp :truename))))))))
(when disk-savep
(LET ((L (SUBSET #'(LAMBDA (X)
(STRING-EQUAL "LOD" (CAR X) :END2 3))
(SI:PARTITION-LIST)))
(CB (SI:CURRENT-BAND)))
(DO ((x))
((PROGN (FORMAT T "~&Available LOD Partitions:~%")
(DOLIST (P L)
(FORMAT T "~4A ~14A ~25S ~5D blocks.~%"
(NTH 0 P)
(COND ((STRING-EQUAL CB (NTH 0 P))
"(current band)")
((STRING-EQUAL (NTH 3 P) "")
"(unused band)")
('ELSE
"(a lisp band)"))
(NTH 3 P)
(NTH 2 P)))
(SETQ LOD (PROMPT-AND-READ :STRING-OR-NIL "~& LOD band to save to :"))
(setq x lod)
(WHEN (STRING-EQUAL "LOD" x :END2 3)
(SETQ x (SUBSTRING x 3)))
(COND ((FIXP (CATCH-ERROR (PARSE-INTEGER x)))
(SETQ x (PARSE-INTEGER x))
(LET ((FL (FORMAT NIL "LOD~D" x)))
(DO ((P L (CDR P)))
((NULL P)
(FORMAT T "Not an available load partition: ~S" LOD)
NIL)
(IF (string-equal (caar p) fl)
(return (setq lod x))))))))))))
(list 'NAME name 'SITE-DIR site-dir 'LOD lod)))
(DEFUN BOOTSTRAP-READ-SITE-DATA (DIR)
(LET ((FS (LIST (SEND DIR :NEW-PATHNAME :NAME "SITE" :TYPE "QFASL" :VERSION :NEWEST)
(SEND DIR :NEW-PATHNAME :NAME "HSTTBL" :TYPE "QFASL" :VERSION :NEWEST)
(SEND DIR :NEW-PATHNAME :NAME "LMLOCS" :TYPE "QFASL" :VERSION :NEWEST))))
(remprop 'si:machine-location-alist :source-file)
(PROGV *BOOTSTRAP-SITE-VARS*
(MAKE-LIST (LENGTH *BOOTSTRAP-SITE-VARS*))
(DOLIST (F FS)
(LOAD F :SET-DEFAULT-PATHNAME NIL))
(DOLIST (ELEM SI:HOST-ALIST)
(SI:GET-ALIST-ELEM-HOST ELEM))
(MAPCAN #'(LAMBDA (VAR)
(LIST VAR (SYMBOL-VALUE VAR)))
*BOOTSTRAP-SITE-VARS*))))
(DEFUN BOOTSTRAP-LOOKUP-HOST (NAME ALIST)
(OR (DOLIST (A ALIST)
(WHEN (MEM #'STRING-EQUAL NAME (SI:HOST-NAME-LIST A))
(RETURN (SI:HOST-INSTANCE A))))
(FERROR NIL "Host ~S not found in bootstrap data" NAME)))
(DEFVAR *RELEASE-ROOT-NAME* "RELEASE-3")
(DEFVAR *RELEASE-ROOT-DEPTH* 5)
(DEFUN BOOTSTRAP-CHECK-SYS-TRANSLATIONS (DIR SYS-HOST-NAME)
(LET* ((NP (SEND DIR :NEW-PATHNAME :NAME NIL :TYPE NIL :VERSION NIL))
(SP (SEND DIR :NEW-PATHNAME :NAME "SYS" :TYPE "TRANSLATIONS" :VERSION :NEWEST))
(FORM `(FS:SET-LOGICAL-PATHNAME-HOST "SYS"
:PHYSICAL-HOST ,SYS-HOST-NAME
:TRANSLATIONS '(("CHAOS;" ,(SEND NP :STRING-FOR-HOST))
("SITE;" ,(SEND NP :STRING-FOR-HOST))
,@(DO ((L NIL
(CONS (LIST (FORMAT NIL "~{~A;~}"
(MAKE-LIST DEPTH :INITIAL-ELEMENT '*))
(SEND (SEND NP :NEW-PATHNAME
:DIRECTORY (CONS *RELEASE-ROOT-NAME*
(MAKE-LIST DEPTH
:INITIAL-ELEMENT :WILD)))
:STRING-FOR-HOST))
L))
(DEPTH *RELEASE-ROOT-DEPTH* (1- DEPTH)))
((ZEROP DEPTH)
L))))))
(FLET ((WRITE-FORM ()
(WITH-OPEN-FILE (S SP :DIRECTION :OUTPUT)
(FORMAT S ";; SYS.TRANSLATIONS WRITTEN BY BOOTSTRAP SITE GENERATOR~%")
(PPRINT FORM S)
(TERPRI S))))
(COND ((NOT (PROBE-FILE SP))
(WRITE-FORM))
((WITH-OPEN-FILE (S SP)
(NOT (EQUALP FORM (LET ((*PACKAGE* (FIND-PACKAGE "USER"))
(*READTABLE* (SI:FIND-READTABLE-NAMED "ZL")))
(READ S)))))
(WRITE-FORM)))
FORM)))
|
6a9c6016ea19596245b0c08b5b0b9b65a1257ab17af1618fac0793b200afd2f7 | Virtual-Insurance-Products/cldb | metaclass.lisp |
(in-package :cldb)
(defclass cldb-class (standard-class)
((table-name :initform nil :initarg :table-name)))
can only subclass - superclass
(defmethod ccl:validate-superclass ((class cldb-class) (superclass standard-class))
( eq superclass ( find - class ' - entity ) )
t)
... or another class ( which is perfectly fine )
(defmethod ccl:validate-superclass ((class cldb-class) (superclass cldb-class))
t)
(defclass cldb-slot-definition (ccl:standard-slot-definition)
((presentation-type :initarg :presentation-type
:reader slot-definition-presentation-type
:initform t)
(ccl::allocation :initform :database)))
(defclass cldb-direct-slot-definition (ccl:standard-direct-slot-definition cldb-slot-definition)
())
(defclass cldb-effective-slot-definition (ccl:standard-effective-slot-definition cldb-slot-definition)
((value-getter :initform nil :accessor slot-definition-value-getter)))
;; by default the ID slot is a normal one and the rest come from the database
(defmethod ccl:direct-slot-definition-class ((class cldb-class) &rest initargs)
( declare ( ignore ) )
(if (member (second (member :allocation initargs))
'(:instance :class))
(call-next-method)
(find-class 'cldb-direct-slot-definition)))
(defmethod ccl:effective-slot-definition-class ((class cldb-class) &rest initargs)
(if (or (member (second (member :allocation initargs))
'(:instance :class))
(member (symbol-name (second (member :name initargs)))
'("ID" "BASE-VECTOR" "CHANGED-BLOCKS")
:test #'equal))
(call-next-method)
(find-class 'cldb-effective-slot-definition)))
;; !!! I think I should do this differently
I can just get all the ptypes , which will default to nil , and then remove duplicates and see what I 'm left with
;; (see the definition in relations/postgres-class - I'm not sure that is right
(defmethod compute-presentation-type ((def cldb-effective-slot-definition) direct-slots)
(let ((ptypes (remove-duplicates (mapcar #'slot-definition-presentation-type direct-slots)
:test #'equal)))
;; !!! CHECK THIS
(setf (slot-value def 'presentation-type)
(if (cdr ptypes)
`(and ,@ptypes)
(first ptypes)))))
(defmethod compute-presentation-type ((def t) direct-slots)
(declare (ignore direct-slots)))
(defmethod ccl:compute-effective-slot-definition ((class cldb-class) name direct-slots)
(declare (ignore name))
(let ((def (call-next-method)))
(compute-presentation-type def direct-slots)
def))
now , we need to map over all the superclasses to make ID slots for each of them
;; This, I think, is how I will get the inheritance thing to work again
(defmethod ccl:compute-slots ((class cldb-class))
(let ((slots (call-next-method)))
(append
;; walk up the class hierarchy
(let ((list nil))
(labels ((walk (class)
(push (make-instance 'ccl:standard-effective-slot-definition
:class class
:initargs (list (intern (symbol-name (class-name class)) :keyword))
:type 'integer
:allocation :instance
:name (class-name class)
)
list)
(loop for super in (ccl::class-direct-superclasses class)
when (typep super 'cldb-class)
do (walk super))
))
(walk class))
list)
;; make some additional slots...
(list
(make-instance 'ccl:standard-effective-slot-definition
:class class
:initargs '(:base-vector)
:type t
:allocation :instance
:name 'base-vector)
(make-instance 'ccl:standard-effective-slot-definition
:class class
:initargs '(:changed-blocks)
:type t
:allocation :instance
:name 'changed-blocks))
slots)))
;; I think the slot definition should have associated with it a column from the database
;; that will avoid looking up the column definition in the database each time
;; we will store the INDEX of the column, not the column itself
;; This is because the database will keep getting swapped over each time they are updated, but the column indexes will never change once established
(defmethod slot-column-name ((s symbol))
(symbol-to-db-name s))
(defmethod slot-column-name ((slot-definition cldb-slot-definition))
(symbol-to-db-name (ccl:slot-definition-name slot-definition)))
(defmethod class-table-name ((c cldb-class))
(symbol-to-db-name (or (first (slot-value c 'table-name))
(class-name c))))
;; this is broken
#+nil(defmethod db-name ((c cldb-class))
(symbol-to-db-name (class-table-name c)))
;; these should be cached really
;; Will this be called on compilation? I don't want it to be. It needs to be late bound
(defun slot-column (b c slot)
(let ((slot-class (ccl::slot-definition-class slot)))
(find-column b c
(class-table-name slot-class)
(slot-column-name slot))))
;; Useful for running tests and perfectly safe
(defmethod clear-slot-column-cache ((class cldb-class))
(dolist (slot (ccl:class-slots class))
(when (typep slot 'cldb-effective-slot-definition)
(setf (slot-definition-value-getter slot) nil))))
;; I should override the setter here to just do nothing OR can you declare slots read only?
;; I wonder if I can cache things here
(defmethod ccl:slot-value-using-class ((class cldb-class) instance (slot-definition cldb-effective-slot-definition))
(funcall (or (slot-value slot-definition 'value-getter)
(setf (slot-definition-value-getter slot-definition)
(let* ((b (slot-value instance 'base-vector))
(c (slot-value instance 'changed-blocks))
(col (slot-column b c slot-definition))
(id->value (column-slot b c col column.id->value))
(slot-type (ccl:slot-definition-type slot-definition))
(slot-type-class (when (symbolp slot-type)
(find-class slot-type)))
(slot-type-initarg (when slot-type-class
(intern (symbol-name slot-type) :keyword))))
(if (and slot-type-class
(typep slot-type-class 'cldb-class))
(lambda (b c id)
(heap-instance b c slot-type-class
slot-type-initarg
! ! ! I 'm assuming the i d wo n't exceed ( 1- ( ash 1 56 ) )
;; (which would cause us problems anyway)
(parray-ref b c id->value id)))
(lambda (b c id)
(pobject->lisp-object b c
(parray-ref b c id->value id)))))))
(slot-value instance 'base-vector)
(slot-value instance 'changed-blocks)
(slot-value instance (class-name (ccl::slot-definition-class slot-definition)))))
;; how do I determine whether the slot is bound? Is it always if we have a valid row?
;; This comes down to the question of null handling. Maybe I need something special for null, though it will depend on data types from the database
;; do I get those? All I need to know is whether it's a binary or not.
(defmethod ccl:slot-boundp-using-class ((class cldb-class) instance (slot-definition cldb-effective-slot-definition))
(declare (ignore instance))
;; !!! FIXME - if the database returns :NULL as the slot value then the answer is no
t)
;; of course, I am not initially going to do ways of mutating things here
;; indeed, if you want to mutate things it's probably going to be necessary to create a postgres-class instance instead
;; it might be nice to just do change-instance.
;; If I were going to give direct write access here I would need to do these things...
;; !!! We need to see if the value is an instance of this metaclass - I should start handling that...
(defun find-instances (b c class slot value)
(when (symbolp class)
(setf class (find-class class)))
(let ((r nil))
(map-ids-for-value b c
(slot-column b c slot)
value
(lambda (id)
(push (heap-instance b c class :id id) r)))
r))
;; in fact, we shouldn't use make-instance to get references. We need find-instance...
;; (this is more restricted than postgres-class so far)
#+nil(defun find-instance (b c class slot value)
(let ((a (find-instances class slot value)))
(if (= (length a) 1)
(error "Found ~A instances of ~A with ~A = ~A - not just 1"
class slot value))))
TODO
;; - handle creation of subclasses (like underwriter-product subclasseses etc) like the postgres-class does
;; --- this is one of the major points of this exercise - to get that stuff to run fast)
;; incidentally, instantiating these new classes will be very much quicker than postgres-class ones
;; if this were to be used for querying it needs to be as fast as possible
;; it might be better NOT to use it for querying
#+nil(defmethod map-tuples (f (x cldb-class))
(map-row-ids (lambda (id)
(funcall f (make-instance x :id id)))
(find-table *database* (class-table-name x))))
;; so, to get an instance by ID we just need to do this...
( which is annoying because we wo n't see
(defun heap-instance (b c class id-slot-name id)
;; !!! To initialize subclasses will require more work than this
;; we have to check for any subclasses and then walk over them looking for any references to this particular superclass
;; we may have to make a computed class in the end. If not then we just need to make sure to set all the id slots
;; !!! This won't yet handle computed classes or multiple inheritence
MI should n't be hard to add
! ! !
(when (symbolp class)
(setf class (find-class class)))
(labels ((create (class identifiers id)
(or (loop for sub in (ccl:class-direct-subclasses class)
for match = (collect-1 b c
(index-lookup b c
(class-table-name sub)
(class-table-name class))
id)
when match
return (create sub (cons (intern (symbol-name (class-name sub))
:keyword)
(cons match
identifiers))
match))
(apply #'make-instance
(append (list class
:base-vector b
:changed-blocks c)
identifiers)))))
(let ((identifiers (list id-slot-name id)))
(create class
identifiers id))))
(defun simple-heap-instance (b c class id-slot-name id)
(make-instance class
:base-vector b
:changed-blocks c
id-slot-name id))
(defun get-instance (class &optional id)
(with-database (b c)
(heap-instance b c class
(intern (symbol-name class) :keyword)
id)))
(defun id/instance-id (object class)
(if (integerp object)
object
(slot-value object class)))
;; Here is a version which can be composed in with id-mapper etc
(defun map-heap-instance (class)
(let ((id-slot-name (intern (symbol-name class) :keyword)))
(lambda (b c id)
(lambda (f)
(funcall f (heap-instance b c class id-slot-name id))))))
| null | https://raw.githubusercontent.com/Virtual-Insurance-Products/cldb/43e0f10b6ce2e834f73a8b0c8477ca5b01df38f2/metaclass.lisp | lisp | by default the ID slot is a normal one and the rest come from the database
!!! I think I should do this differently
(see the definition in relations/postgres-class - I'm not sure that is right
!!! CHECK THIS
This, I think, is how I will get the inheritance thing to work again
walk up the class hierarchy
make some additional slots...
I think the slot definition should have associated with it a column from the database
that will avoid looking up the column definition in the database each time
we will store the INDEX of the column, not the column itself
This is because the database will keep getting swapped over each time they are updated, but the column indexes will never change once established
this is broken
these should be cached really
Will this be called on compilation? I don't want it to be. It needs to be late bound
Useful for running tests and perfectly safe
I should override the setter here to just do nothing OR can you declare slots read only?
I wonder if I can cache things here
(which would cause us problems anyway)
how do I determine whether the slot is bound? Is it always if we have a valid row?
This comes down to the question of null handling. Maybe I need something special for null, though it will depend on data types from the database
do I get those? All I need to know is whether it's a binary or not.
!!! FIXME - if the database returns :NULL as the slot value then the answer is no
of course, I am not initially going to do ways of mutating things here
indeed, if you want to mutate things it's probably going to be necessary to create a postgres-class instance instead
it might be nice to just do change-instance.
If I were going to give direct write access here I would need to do these things...
!!! We need to see if the value is an instance of this metaclass - I should start handling that...
in fact, we shouldn't use make-instance to get references. We need find-instance...
(this is more restricted than postgres-class so far)
- handle creation of subclasses (like underwriter-product subclasseses etc) like the postgres-class does
--- this is one of the major points of this exercise - to get that stuff to run fast)
incidentally, instantiating these new classes will be very much quicker than postgres-class ones
if this were to be used for querying it needs to be as fast as possible
it might be better NOT to use it for querying
so, to get an instance by ID we just need to do this...
!!! To initialize subclasses will require more work than this
we have to check for any subclasses and then walk over them looking for any references to this particular superclass
we may have to make a computed class in the end. If not then we just need to make sure to set all the id slots
!!! This won't yet handle computed classes or multiple inheritence
Here is a version which can be composed in with id-mapper etc |
(in-package :cldb)
(defclass cldb-class (standard-class)
((table-name :initform nil :initarg :table-name)))
can only subclass - superclass
(defmethod ccl:validate-superclass ((class cldb-class) (superclass standard-class))
( eq superclass ( find - class ' - entity ) )
t)
... or another class ( which is perfectly fine )
(defmethod ccl:validate-superclass ((class cldb-class) (superclass cldb-class))
t)
(defclass cldb-slot-definition (ccl:standard-slot-definition)
((presentation-type :initarg :presentation-type
:reader slot-definition-presentation-type
:initform t)
(ccl::allocation :initform :database)))
(defclass cldb-direct-slot-definition (ccl:standard-direct-slot-definition cldb-slot-definition)
())
(defclass cldb-effective-slot-definition (ccl:standard-effective-slot-definition cldb-slot-definition)
((value-getter :initform nil :accessor slot-definition-value-getter)))
(defmethod ccl:direct-slot-definition-class ((class cldb-class) &rest initargs)
( declare ( ignore ) )
(if (member (second (member :allocation initargs))
'(:instance :class))
(call-next-method)
(find-class 'cldb-direct-slot-definition)))
(defmethod ccl:effective-slot-definition-class ((class cldb-class) &rest initargs)
(if (or (member (second (member :allocation initargs))
'(:instance :class))
(member (symbol-name (second (member :name initargs)))
'("ID" "BASE-VECTOR" "CHANGED-BLOCKS")
:test #'equal))
(call-next-method)
(find-class 'cldb-effective-slot-definition)))
I can just get all the ptypes , which will default to nil , and then remove duplicates and see what I 'm left with
(defmethod compute-presentation-type ((def cldb-effective-slot-definition) direct-slots)
(let ((ptypes (remove-duplicates (mapcar #'slot-definition-presentation-type direct-slots)
:test #'equal)))
(setf (slot-value def 'presentation-type)
(if (cdr ptypes)
`(and ,@ptypes)
(first ptypes)))))
(defmethod compute-presentation-type ((def t) direct-slots)
(declare (ignore direct-slots)))
(defmethod ccl:compute-effective-slot-definition ((class cldb-class) name direct-slots)
(declare (ignore name))
(let ((def (call-next-method)))
(compute-presentation-type def direct-slots)
def))
now , we need to map over all the superclasses to make ID slots for each of them
(defmethod ccl:compute-slots ((class cldb-class))
(let ((slots (call-next-method)))
(append
(let ((list nil))
(labels ((walk (class)
(push (make-instance 'ccl:standard-effective-slot-definition
:class class
:initargs (list (intern (symbol-name (class-name class)) :keyword))
:type 'integer
:allocation :instance
:name (class-name class)
)
list)
(loop for super in (ccl::class-direct-superclasses class)
when (typep super 'cldb-class)
do (walk super))
))
(walk class))
list)
(list
(make-instance 'ccl:standard-effective-slot-definition
:class class
:initargs '(:base-vector)
:type t
:allocation :instance
:name 'base-vector)
(make-instance 'ccl:standard-effective-slot-definition
:class class
:initargs '(:changed-blocks)
:type t
:allocation :instance
:name 'changed-blocks))
slots)))
(defmethod slot-column-name ((s symbol))
(symbol-to-db-name s))
(defmethod slot-column-name ((slot-definition cldb-slot-definition))
(symbol-to-db-name (ccl:slot-definition-name slot-definition)))
(defmethod class-table-name ((c cldb-class))
(symbol-to-db-name (or (first (slot-value c 'table-name))
(class-name c))))
#+nil(defmethod db-name ((c cldb-class))
(symbol-to-db-name (class-table-name c)))
(defun slot-column (b c slot)
(let ((slot-class (ccl::slot-definition-class slot)))
(find-column b c
(class-table-name slot-class)
(slot-column-name slot))))
(defmethod clear-slot-column-cache ((class cldb-class))
(dolist (slot (ccl:class-slots class))
(when (typep slot 'cldb-effective-slot-definition)
(setf (slot-definition-value-getter slot) nil))))
(defmethod ccl:slot-value-using-class ((class cldb-class) instance (slot-definition cldb-effective-slot-definition))
(funcall (or (slot-value slot-definition 'value-getter)
(setf (slot-definition-value-getter slot-definition)
(let* ((b (slot-value instance 'base-vector))
(c (slot-value instance 'changed-blocks))
(col (slot-column b c slot-definition))
(id->value (column-slot b c col column.id->value))
(slot-type (ccl:slot-definition-type slot-definition))
(slot-type-class (when (symbolp slot-type)
(find-class slot-type)))
(slot-type-initarg (when slot-type-class
(intern (symbol-name slot-type) :keyword))))
(if (and slot-type-class
(typep slot-type-class 'cldb-class))
(lambda (b c id)
(heap-instance b c slot-type-class
slot-type-initarg
! ! ! I 'm assuming the i d wo n't exceed ( 1- ( ash 1 56 ) )
(parray-ref b c id->value id)))
(lambda (b c id)
(pobject->lisp-object b c
(parray-ref b c id->value id)))))))
(slot-value instance 'base-vector)
(slot-value instance 'changed-blocks)
(slot-value instance (class-name (ccl::slot-definition-class slot-definition)))))
(defmethod ccl:slot-boundp-using-class ((class cldb-class) instance (slot-definition cldb-effective-slot-definition))
(declare (ignore instance))
t)
(defun find-instances (b c class slot value)
(when (symbolp class)
(setf class (find-class class)))
(let ((r nil))
(map-ids-for-value b c
(slot-column b c slot)
value
(lambda (id)
(push (heap-instance b c class :id id) r)))
r))
#+nil(defun find-instance (b c class slot value)
(let ((a (find-instances class slot value)))
(if (= (length a) 1)
(error "Found ~A instances of ~A with ~A = ~A - not just 1"
class slot value))))
TODO
#+nil(defmethod map-tuples (f (x cldb-class))
(map-row-ids (lambda (id)
(funcall f (make-instance x :id id)))
(find-table *database* (class-table-name x))))
( which is annoying because we wo n't see
(defun heap-instance (b c class id-slot-name id)
MI should n't be hard to add
! ! !
(when (symbolp class)
(setf class (find-class class)))
(labels ((create (class identifiers id)
(or (loop for sub in (ccl:class-direct-subclasses class)
for match = (collect-1 b c
(index-lookup b c
(class-table-name sub)
(class-table-name class))
id)
when match
return (create sub (cons (intern (symbol-name (class-name sub))
:keyword)
(cons match
identifiers))
match))
(apply #'make-instance
(append (list class
:base-vector b
:changed-blocks c)
identifiers)))))
(let ((identifiers (list id-slot-name id)))
(create class
identifiers id))))
(defun simple-heap-instance (b c class id-slot-name id)
(make-instance class
:base-vector b
:changed-blocks c
id-slot-name id))
(defun get-instance (class &optional id)
(with-database (b c)
(heap-instance b c class
(intern (symbol-name class) :keyword)
id)))
(defun id/instance-id (object class)
(if (integerp object)
object
(slot-value object class)))
(defun map-heap-instance (class)
(let ((id-slot-name (intern (symbol-name class) :keyword)))
(lambda (b c id)
(lambda (f)
(funcall f (heap-instance b c class id-slot-name id))))))
|
49f36daf9060d9104ca77bf87004579027fa130f363c78b83d214e89fb1ce630 | techascent/tech.compute | context.clj | (ns tech.compute.context
"Compute context allows someone to setup the default driver, device, and stream to
use in function calls."
(:require [tech.compute.registry :as registry]
[tech.compute.driver :as drv]))
(def ^:dynamic *context {})
(defn default-driver
[]
(or (:driver *context)
(registry/driver @registry/*cpu-driver-name*)))
(defn default-device
[]
(let [retval
(or (:device *context)
(first (drv/get-devices (default-driver))))]
(when-not retval
(throw (Exception.
(format "%s: No devices found"
(drv/driver-name (default-driver))))))
retval))
(defn default-stream
[]
(or (:stream *context)
(drv/default-stream (default-device))))
(defmacro with-context
[context & body]
`(with-bindings {#'*context ~context}
~@body))
(defmacro with-merged-context
[context & body]
`(with-context
(merge *context ~context)
~@body))
(defn default-context
[]
{:driver (default-driver)
:device (default-device)
:stream (default-stream)})
(defn options->context
"Given an options map, return a augmented map that always includes
device, driver, and stream."
[opt-map]
(merge (default-context) opt-map))
| null | https://raw.githubusercontent.com/techascent/tech.compute/716d270da7018915bcdb42d9942d33991b5931c8/src/tech/compute/context.clj | clojure | (ns tech.compute.context
"Compute context allows someone to setup the default driver, device, and stream to
use in function calls."
(:require [tech.compute.registry :as registry]
[tech.compute.driver :as drv]))
(def ^:dynamic *context {})
(defn default-driver
[]
(or (:driver *context)
(registry/driver @registry/*cpu-driver-name*)))
(defn default-device
[]
(let [retval
(or (:device *context)
(first (drv/get-devices (default-driver))))]
(when-not retval
(throw (Exception.
(format "%s: No devices found"
(drv/driver-name (default-driver))))))
retval))
(defn default-stream
[]
(or (:stream *context)
(drv/default-stream (default-device))))
(defmacro with-context
[context & body]
`(with-bindings {#'*context ~context}
~@body))
(defmacro with-merged-context
[context & body]
`(with-context
(merge *context ~context)
~@body))
(defn default-context
[]
{:driver (default-driver)
:device (default-device)
:stream (default-stream)})
(defn options->context
"Given an options map, return a augmented map that always includes
device, driver, and stream."
[opt-map]
(merge (default-context) opt-map))
| |
3cf801a601170aebce4de8770ab42aaf87bbe831f3fb8bbe93949d6b10503c26 | MyDataFlow/ttalk-server | ejabberd_config.erl | %%%----------------------------------------------------------------------
%%% File : ejabberd_config.erl
Author : < >
%%% Purpose : Load config file
Created : 14 Dec 2002 by < >
%%%
%%%
ejabberd , Copyright ( C ) 2002 - 2011 ProcessOne
%%%
%%% 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. , 59 Temple Place , Suite 330 , Boston , MA
02111 - 1307 USA
%%%
%%%----------------------------------------------------------------------
-module(ejabberd_config).
-author('').
-export([start/0,
load_file/1,
add_global_option/2,
get_global_option/1,
add_local_option/2,
get_local_option/1,
get_local_option/2,
del_local_option/1,
get_local_option_or_default/2]).
-export([get_vh_by_auth_method/1]).
-export([is_file_readable/1]).
%% for unit tests
-export([check_hosts/2,
compare_modules/2,
compare_listeners/2,
group_host_changes/1]).
%% conf reload
-export([reload_local/0,
reload_cluster/0,
apply_changes_remote/4,
apply_changes/5]).
-export([compute_config_version/2,
get_local_config/0,
get_host_local_config/0]).
-include("ejabberd.hrl").
-include("ejabberd_config.hrl").
-include_lib("kernel/include/file.hrl").
-define(CONFIG_RELOAD_TIMEOUT, 30000).
-type key() :: atom()
| {key(), ejabberd:server() | atom() | list()}
| {atom(), atom(), atom()}
| binary(). % TODO: binary is questionable here
-type value() :: atom()
| binary()
| integer()
| string()
| [value()]
| tuple().
-export_type([key/0, value/0]).
-record(state, { opts = [] :: list(),
hosts = [] :: [host()],
override_local = false :: boolean(),
override_global = false :: boolean(),
override_acls = false :: boolean() }).
-record(compare_result, {to_start = [] :: list(),
to_stop = [] :: list(),
to_reload = [] :: list()}).
-type compare_result() :: #compare_result{}.
-type host() :: any(). % TODO: specify this
-type state() :: #state{}.
-type macro() :: {macro_key(), macro_value()}.
%% The atom must have all characters in uppercase.
-type macro_key() :: atom().
-type macro_value() :: term().
-type known_term() :: override_global
| override_local
| override_acls
| {acl, _, _}
| {alarms, _}
| {access, _, _}
| {shaper, _, _}
| {host, _}
| {hosts, _}
| {host_config, _, _}
| {listen, _}
| {language, _}
| {sm_backend, _}
| {outgoing_s2s_port, integer()}
| {outgoing_s2s_options, _, integer()}
| {{s2s_addr, _}, _}
| {s2s_dns_options, [tuple()]}
| {s2s_use_starttls, integer()}
| {s2s_certfile, _}
| {domain_certfile, _, _}
| {node_type, _}
| {cluster_nodes, _}
| {registration_timeout, integer()}
| {mongooseimctl_access_commands, list()}
| {loglevel, _}
| {max_fsm_queue, _}
| host_term().
-type host_term() :: {acl, _, _}
| {access, _, _}
| {shaper, _, _}
| {host, _}
| {hosts, _}
| {odbc_server, _}.
-spec start() -> ok.
start() ->
mnesia:create_table(config,
[{ram_copies, [node()]},
{storage_properties,
[{ets, [{read_concurrency,true}]}]},
{attributes, record_info(fields, config)}]),
mnesia:add_table_copy(config, node(), ram_copies),
mnesia:create_table(local_config,
[{ram_copies, [node()]},
{storage_properties,
[{ets, [{read_concurrency,true}]}]},
{local_content, true},
{attributes, record_info(fields, local_config)}]),
mnesia:add_table_copy(local_config, node(), ram_copies),
Config = get_ejabberd_config_path(),
ejabberd_config:load_file(Config),
%% This start time is used by mod_last:
add_local_option(node_start, now()),
ok.
%% @doc Get the filename of the ejabberd configuration file.
%% The filename can be specified with: erl -config "/path/to/ejabberd.cfg".
%% It can also be specified with the environtment variable EJABBERD_CONFIG_PATH.
%% If not specified, the default value 'ejabberd.cfg' is assumed.
-spec get_ejabberd_config_path() -> string().
get_ejabberd_config_path() ->
DefaultPath = case os:getenv("EJABBERD_CONFIG_PATH") of
false ->
?CONFIG_PATH;
Path ->
Path
end,
application:get_env(ejabberd, config, DefaultPath).
%% @doc Load the ejabberd configuration file.
%% It also includes additional configuration files and replaces macros.
%% This function will crash if finds some error in the configuration file.
-spec load_file(File::string()) -> ok.
load_file(File) ->
Terms = get_plain_terms_file(File),
State = lists:foldl(fun search_hosts/2, #state{}, Terms),
Terms_macros = replace_macros(Terms),
Res = lists:foldl(fun process_term/2, State, Terms_macros),
set_opts(Res).
%% @doc Read an ejabberd configuration file and return the terms.
%% Input is an absolute or relative path to an ejabberd config file.
%% Returns a list of plain terms,
%% in which the options 'include_config_file' were parsed
%% and the terms in those files were included.
-spec get_plain_terms_file(string()) -> [term()].
get_plain_terms_file(File1) ->
File = get_absolute_path(File1),
case file:consult(File) of
{ok, Terms} ->
include_config_files(Terms);
{error, {LineNumber, erl_parse, _ParseMessage} = Reason} ->
ExitText = describe_config_problem(File, Reason, LineNumber),
?ERROR_MSG(ExitText, []),
exit_or_halt(ExitText);
{error, Reason} ->
ExitText = describe_config_problem(File, Reason),
?ERROR_MSG(ExitText, []),
exit_or_halt(ExitText)
end.
%% @doc Convert configuration filename to absolute path.
%% Input is an absolute or relative path to an ejabberd configuration file.
%% And returns an absolute path to the configuration file.
-spec get_absolute_path(string()) -> string().
get_absolute_path(File) ->
case filename:pathtype(File) of
absolute ->
File;
relative ->
{ok, Cwd} = file:get_cwd(),
filename:absname_join(Cwd, File)
end.
-spec search_hosts({host|hosts, [host()] | host()}, state()) -> any().
search_hosts(Term, State) ->
case Term of
{host, Host} ->
if
State#state.hosts == [] ->
add_hosts_to_option([Host], State);
true ->
?ERROR_MSG("Can't load config file: "
"too many hosts definitions", []),
exit("too many hosts definitions")
end;
{hosts, Hosts} ->
if
State#state.hosts == [] ->
add_hosts_to_option(Hosts, State);
true ->
?ERROR_MSG("Can't load config file: "
"too many hosts definitions", []),
exit("too many hosts definitions")
end;
_ ->
State
end.
-spec add_hosts_to_option(Hosts :: [host()],
State :: state()) -> state().
add_hosts_to_option(Hosts, State) ->
PrepHosts = normalize_hosts(Hosts),
add_option(hosts, PrepHosts, State#state{hosts = PrepHosts}).
-spec normalize_hosts([host()]) -> [binary() | tuple()].
normalize_hosts(Hosts) ->
normalize_hosts(Hosts,[]).
normalize_hosts([], PrepHosts) ->
lists:reverse(PrepHosts);
normalize_hosts([Host|Hosts], PrepHosts) ->
case jid:nodeprep(host_to_binary(Host)) of
error ->
?ERROR_MSG("Can't load config file: "
"invalid host name [~p]", [Host]),
exit("invalid hostname");
PrepHost ->
normalize_hosts(Hosts, [PrepHost|PrepHosts])
end.
-ifdef(latin1_characters).
host_to_binary(Host) ->
list_to_binary(Host).
-else.
host_to_binary(Host) ->
unicode:characters_to_binary(Host).
-endif.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Errors reading the config file
-type config_problem() :: atom() | {integer(),atom() | tuple(),_}. % spec me better
-type config_line() :: [[any()] | non_neg_integer(),...]. % spec me better
-spec describe_config_problem(Filename :: string(),
Reason :: config_problem()) -> string().
describe_config_problem(Filename, Reason) ->
Text1 = lists:flatten("Problem loading ejabberd config file " ++ Filename),
Text2 = lists:flatten(" : " ++ file:format_error(Reason)),
ExitText = Text1 ++ Text2,
ExitText.
-spec describe_config_problem(Filename :: string(),
Reason :: config_problem(),
Line :: pos_integer()) -> string().
describe_config_problem(Filename, Reason, LineNumber) ->
Text1 = lists:flatten("Problem loading ejabberd config file " ++ Filename),
Text2 = lists:flatten(" approximately in the line "
++ file:format_error(Reason)),
ExitText = Text1 ++ Text2,
Lines = get_config_lines(Filename, LineNumber, 10, 3),
?ERROR_MSG("The following lines from your configuration file might be"
" relevant to the error: ~n~s", [Lines]),
ExitText.
-spec get_config_lines(Filename :: string(),
TargetNumber :: integer(),
PreContext :: 10,
PostContext :: 3) -> [config_line()].
get_config_lines(Filename, TargetNumber, PreContext, PostContext) ->
{ok, Fd} = file:open(Filename, [read]),
LNumbers = lists:seq(TargetNumber-PreContext, TargetNumber+PostContext),
NextL = io:get_line(Fd, no_prompt),
R = get_config_lines2(Fd, NextL, 1, LNumbers, []),
file:close(Fd),
R.
get_config_lines2(_Fd, eof, _CurrLine, _LNumbers, R) ->
lists:reverse(R);
get_config_lines2(_Fd, _NewLine, _CurrLine, [], R) ->
lists:reverse(R);
get_config_lines2(Fd, Data, CurrLine, [NextWanted | LNumbers], R) when is_list(Data) ->
NextL = io:get_line(Fd, no_prompt),
if
CurrLine >= NextWanted ->
Line2 = [integer_to_list(CurrLine), ": " | Data],
get_config_lines2(Fd, NextL, CurrLine+1, LNumbers, [Line2 | R]);
true ->
get_config_lines2(Fd, NextL, CurrLine+1, [NextWanted | LNumbers], R)
end.
%% @doc If ejabberd isn't yet running in this node, then halt the node
-spec exit_or_halt(ExitText :: string()) -> none().
exit_or_halt(ExitText) ->
case [Vsn || {ejabberd, _Desc, Vsn} <- application:which_applications()] of
[] ->
timer:sleep(1000),
halt(string:substr(ExitText, 1, 199));
[_] ->
exit(ExitText)
end.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Support for 'include_config_file'
%% @doc Include additional configuration files in the list of terms.
-spec include_config_files([term()]) -> [term()].
include_config_files(Terms) ->
include_config_files(Terms, []).
include_config_files([], Res) ->
Res;
include_config_files([{include_config_file, Filename} | Terms], Res) ->
include_config_files([{include_config_file, Filename, []} | Terms], Res);
include_config_files([{include_config_file, Filename, Options} | Terms], Res) ->
Included_terms = get_plain_terms_file(Filename),
Disallow = proplists:get_value(disallow, Options, []),
Included_terms2 = delete_disallowed(Disallow, Included_terms),
Allow_only = proplists:get_value(allow_only, Options, all),
Included_terms3 = keep_only_allowed(Allow_only, Included_terms2),
include_config_files(Terms, Res ++ Included_terms3);
include_config_files([Term | Terms], Res) ->
include_config_files(Terms, Res ++ [Term]).
%% @doc Filter from the list of terms the disallowed.
Returns a sublist of Terms without the ones which first element is
included in Disallowed .
-spec delete_disallowed(Disallowed :: [atom()],
Terms :: [term()]) -> [term()].
delete_disallowed(Disallowed, Terms) ->
lists:foldl(
fun(Dis, Ldis) ->
delete_disallowed2(Dis, Ldis)
end,
Terms,
Disallowed).
delete_disallowed2(Disallowed, [H|T]) ->
case element(1, H) of
Disallowed ->
?WARNING_MSG("The option '~p' is disallowed, "
"and will not be accepted", [Disallowed]),
delete_disallowed2(Disallowed, T);
_ ->
[H|delete_disallowed2(Disallowed, T)]
end;
delete_disallowed2(_, []) ->
[].
%% @doc Keep from the list only the allowed terms.
Returns a sublist of Terms with only the ones which first element is
%% included in Allowed.
-spec keep_only_allowed(Allowed :: [atom()],
Terms::[term()]) -> [term()].
keep_only_allowed(all, Terms) ->
Terms;
keep_only_allowed(Allowed, Terms) ->
{As, NAs} = lists:partition(
fun(Term) ->
lists:member(element(1, Term), Allowed)
end,
Terms),
[?WARNING_MSG("This option is not allowed, "
"and will not be accepted:~n~p", [NA])
|| NA <- NAs],
As.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Support for Macro
%% @doc Replace the macros with their defined values.
-spec replace_macros(Terms :: [term()]) -> [term()].
replace_macros(Terms) ->
{TermsOthers, Macros} = split_terms_macros(Terms),
replace(TermsOthers, Macros).
%% @doc Split Terms into normal terms and macro definitions.
-spec split_terms_macros(Terms :: [term()]) -> {[term()], [macro()]}.
split_terms_macros(Terms) ->
lists:foldl(
fun(Term, {TOs, Ms}) ->
case Term of
{define_macro, Key, Value} ->
case is_atom(Key) and is_all_uppercase(Key) of
true ->
{TOs, Ms++[{Key, Value}]};
false ->
exit({macro_not_properly_defined, Term})
end;
Term ->
{TOs ++ [Term], Ms}
end
end,
{[], []},
Terms).
%% @doc Recursively replace in Terms macro usages with the defined value.
-spec replace(Terms :: [term()],
Macros :: [macro()]) -> [term()].
replace([], _) ->
[];
replace([Term|Terms], Macros) ->
[replace_term(Term, Macros) | replace(Terms, Macros)].
replace_term(Key, Macros) when is_atom(Key) ->
case is_all_uppercase(Key) of
true ->
case proplists:get_value(Key, Macros) of
undefined -> exit({undefined_macro, Key});
Value -> Value
end;
false ->
Key
end;
replace_term({use_macro, Key, Value}, Macros) ->
proplists:get_value(Key, Macros, Value);
replace_term(Term, Macros) when is_list(Term) ->
replace(Term, Macros);
replace_term(Term, Macros) when is_tuple(Term) ->
List = tuple_to_list(Term),
List2 = replace(List, Macros),
list_to_tuple(List2);
replace_term(Term, _) ->
Term.
-spec is_all_uppercase(atom()) -> boolean().
is_all_uppercase(Atom) ->
String = erlang:atom_to_list(Atom),
lists:all(fun(C) when C >= $a, C =< $z -> false;
(_) -> true
end, String).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Process terms
-spec process_term(Term :: known_term(),
State :: state()) -> state().
process_term(Term, State) ->
case Term of
override_global ->
State#state{override_global = true};
override_local ->
State#state{override_local = true};
override_acls ->
State#state{override_acls = true};
{acl, _ACLName, _ACLData} ->
process_host_term(Term, global, State);
{alarms, Env} ->
add_option(alarms, Env, State);
{access, _RuleName, _Rules} ->
process_host_term(Term, global, State);
{shaper, _Name, _Data} ->
%%lists:foldl(fun(Host, S) -> process_host_term(Term, Host, S) end,
State , State#state.hosts ) ;
process_host_term(Term, global, State);
{host, _Host} ->
State;
{hosts, _Hosts} ->
State;
{host_config, Host, Terms} ->
lists:foldl(fun(T, S) ->
process_host_term(T, list_to_binary(Host), S) end,
State, Terms);
{listen, Listeners} ->
Listeners2 =
lists:map(
fun({PortIP, Module, Opts}) ->
{Port, IPT, _, _, Proto, OptsClean} =
ejabberd_listener:parse_listener_portip(PortIP, Opts),
{{Port, IPT, Proto}, Module, OptsClean}
end,
Listeners),
add_option(listen, Listeners2, State);
{language, Val} ->
add_option(language, list_to_binary(Val), State);
{sm_backend, Val} ->
add_option(sm_backend, Val, State);
{outgoing_s2s_port, Port} ->
add_option(outgoing_s2s_port, Port, State);
{outgoing_s2s_options, Methods, Timeout} ->
add_option(outgoing_s2s_options, {Methods, Timeout}, State);
{{s2s_addr, Host}, Addr} ->
add_option({s2s_addr, list_to_binary(Host)}, Addr, State);
{s2s_dns_options, PropList} ->
add_option(s2s_dns_options, PropList, State);
{s2s_use_starttls, Port} ->
add_option(s2s_use_starttls, Port, State);
{s2s_ciphers, Ciphers} ->
add_option(s2s_ciphers, Ciphers, State);
{s2s_certfile, CertFile} ->
case ejabberd_config:is_file_readable(CertFile) of
true -> add_option(s2s_certfile, CertFile, State);
false ->
ErrorText = "There is a problem in the configuration: "
"the specified file is not readable: ",
throw({error, ErrorText ++ CertFile})
end;
{domain_certfile, Domain, CertFile} ->
case ejabberd_config:is_file_readable(CertFile) of
true -> add_option({domain_certfile, Domain}, CertFile, State);
false ->
ErrorText = "There is a problem in the configuration: "
"the specified file is not readable: ",
throw({error, ErrorText ++ CertFile})
end;
{node_type, NodeType} ->
add_option(node_type, NodeType, State);
{cluster_nodes, Nodes} ->
add_option(cluster_nodes, Nodes, State);
{watchdog_admins, Admins} ->
add_option(watchdog_admins, Admins, State);
{watchdog_large_heap, LH} ->
add_option(watchdog_large_heap, LH, State);
{registration_timeout, Timeout} ->
add_option(registration_timeout, Timeout, State);
{mongooseimctl_access_commands, ACs} ->
add_option(mongooseimctl_access_commands, ACs, State);
{loglevel, Loglevel} ->
ejabberd_loglevel:set(Loglevel),
State;
{max_fsm_queue, N} ->
add_option(max_fsm_queue, N, State);
{_Opt, _Val} ->
lists:foldl(fun(Host, S) -> process_host_term(Term, Host, S) end,
State, State#state.hosts)
end.
-spec process_host_term(Term :: host_term(),
Host :: acl:host(),
State :: state()) -> state().
process_host_term(Term, Host, State) ->
case Term of
{acl, ACLName, ACLData} ->
State#state{opts =
[acl:to_record(Host, ACLName, ACLData) | State#state.opts]};
{access, RuleName, Rules} ->
State#state{opts = [#config{key = {access, RuleName, Host},
value = Rules} |
State#state.opts]};
{shaper, Name, Data} ->
State#state{opts = [#config{key = {shaper, Name, Host},
value = Data} |
State#state.opts]};
{host, Host} ->
State;
{hosts, _Hosts} ->
State;
{odbc_server, ODBC_server} ->
add_option({odbc_server, Host}, ODBC_server, State);
{riak_server, RiakConfig} ->
add_option(riak_server, RiakConfig, State);
{Opt, Val} ->
add_option({Opt, Host}, Val, State)
end.
-spec add_option(Opt :: key(),
Val :: value(),
State :: state()) -> state().
add_option(Opt, Val, State) ->
Table = case Opt of
hosts ->
config;
language ->
config;
sm_backend ->
config;
_ ->
local_config
end,
case Table of
config ->
State#state{opts = [#config{key = Opt, value = Val} |
State#state.opts]};
local_config ->
case Opt of
{{add, OptName}, Host} ->
State#state{opts = compact({OptName, Host}, Val,
State#state.opts, [])};
_ ->
State#state{opts = [#local_config{key = Opt, value = Val} |
State#state.opts]}
end
end.
compact({OptName, Host} = Opt, Val, [], Os) ->
?WARNING_MSG("The option '~p' is defined for the host ~p using host_config "
"before the global '~p' option. This host_config option may "
"get overwritten.", [OptName, Host, OptName]),
[#local_config{key = Opt, value = Val}] ++ Os;
Traverse the list of the options already parsed
compact(Opt, Val, [O | Os1], Os2) ->
case catch O#local_config.key of
%% If the key of a local_config matches the Opt that wants to be added
Opt ->
%% Then prepend the new value to the list of old values
Os2 ++ [#local_config{key = Opt,
value = Val++O#local_config.value}
] ++ Os1;
_ ->
compact(Opt, Val, Os1, Os2++[O])
end.
-spec set_opts(state()) -> 'ok' | none().
set_opts(State) ->
Opts = lists:reverse(State#state.opts),
F = fun() ->
if
State#state.override_global ->
Ksg = mnesia:all_keys(config),
lists:foreach(fun(K) ->
mnesia:delete({config, K})
end, Ksg);
true ->
ok
end,
if
State#state.override_local ->
Ksl = mnesia:all_keys(local_config),
lists:foreach(fun(K) ->
mnesia:delete({local_config, K})
end, lists:delete(node_start, Ksl));
true ->
ok
end,
if
State#state.override_acls ->
Ksa = mnesia:all_keys(acl),
lists:foreach(fun(K) ->
mnesia:delete({acl, K})
end, Ksa);
true ->
ok
end,
lists:foreach(fun(R) ->
mnesia:write(R)
end, Opts)
end,
case mnesia:transaction(F) of
{atomic, _} -> ok;
{aborted,{no_exists,Table}} ->
MnesiaDirectory = mnesia:system_info(directory),
?ERROR_MSG("Error reading Mnesia database spool files:~n"
"The Mnesia database couldn't read the spool file for the table '~p'.~n"
"ejabberd needs read and write access in the directory:~n ~s~n"
"Maybe the problem is a change in the computer hostname,~n"
"or a change in the Erlang node name, which is currently:~n ~p~n"
"Check the ejabberd guide for details about changing the~n"
"computer hostname or Erlang node name.~n",
[Table, MnesiaDirectory, node()]),
exit("Error reading Mnesia database")
end.
-spec add_global_option(Opt :: key(), Val :: value()) -> {atomic|aborted, _}.
add_global_option(Opt, Val) ->
mnesia:transaction(fun() ->
mnesia:write(#config{key = Opt,
value = Val})
end).
-spec add_local_option(Opt :: key(), Val :: value()) -> {atomic|aborted, _}.
add_local_option(Opt, Val) ->
mnesia:transaction(fun() ->
mnesia:write(#local_config{key = Opt,
value = Val})
end).
-spec del_local_option(Opt :: key()) -> {atomic | aborted, _}.
del_local_option(Opt) ->
mnesia:transaction(fun mnesia:delete/1, [{local_config, Opt}]).
-spec get_global_option(key()) -> value() | undefined.
get_global_option(Opt) ->
case ets:lookup(config, Opt) of
[#config{value = Val}] ->
Val;
_ ->
undefined
end.
-spec get_local_option(key()) -> value() | undefined.
get_local_option(Opt) ->
case ets:lookup(local_config, Opt) of
[#local_config{value = Val}] ->
Val;
_ ->
undefined
end.
-spec get_local_option(key(), host()) -> value() | undefined.
get_local_option(Opt, Host) ->
case get_local_option({Opt, Host}) of
undefined -> get_global_option(Opt);
Val -> Val
end.
-spec get_local_option_or_default(key(), value()) -> value().
get_local_option_or_default(Opt, Default) ->
case get_local_option(Opt) of
undefined ->
Default;
Value ->
Value
end.
%% @doc Return the list of hosts handled by a given module
get_vh_by_auth_method(AuthMethod) ->
mnesia:dirty_select(local_config,
[{#local_config{key = {auth_method, '$1'},
value=AuthMethod},[],['$1']}]).
-spec is_file_readable(Path :: string()) -> boolean().
is_file_readable(Path) ->
case file:read_file_info(Path) of
{ok, FileInfo} ->
case {FileInfo#file_info.type, FileInfo#file_info.access} of
{regular, read} -> true;
{regular, read_write} -> true;
_ -> false
end;
{error, _Reason} ->
false
end.
%%--------------------------------------------------------------------
%% Configuration reload
%%--------------------------------------------------------------------
-spec parse_file(file:name()) -> state().
parse_file(ConfigFile) ->
Terms = get_plain_terms_file(ConfigFile),
State = lists:foldl(fun search_hosts/2, #state{}, Terms),
TermsWExpandedMacros = replace_macros(Terms),
lists:foldl(fun process_term/2, State, TermsWExpandedMacros).
-spec reload_local() -> {ok, iolist()} | no_return().
reload_local() ->
ConfigFile = get_ejabberd_config_path(),
State0 = parse_file(ConfigFile),
{CC, LC, LHC} = get_config_diff(State0),
ConfigVersion = compute_config_version(get_local_config(),
get_host_local_config()),
State1 = State0#state{override_global = true,
override_local = true,
override_acls = true},
try
{ok, _} = apply_changes(CC, LC, LHC, State1, ConfigVersion),
?WARNING_MSG("node config reloaded from ~s", [ConfigFile]),
{ok, io_lib:format("# Reloaded: ~s", [node()])}
catch
Error:Reason ->
Msg = msg("failed to apply config on node: ~p~nreason: ~p",
[node(), {Error, Reason}]),
?WARNING_MSG("node config reload failed!~n"
"current config version: ~p~n"
"config file: ~s~n"
"reason: ~p~n"
"stacktrace: ~ts",
[ConfigVersion, ConfigFile, Msg,
msg("~p", [erlang:get_stacktrace()])]),
error(Msg)
end.
%% Won't be unnecessarily evaluated if used as an argument
%% to lager parse transform.
msg(Fmt, Args) ->
lists:flatten(io_lib:format(Fmt, Args)).
-spec reload_cluster() -> {ok, string()} | no_return().
reload_cluster() ->
CurrentNode = node(),
ConfigFile = get_ejabberd_config_path(),
State0 = parse_file(ConfigFile),
ConfigDiff = {CC, LC, LHC} = get_config_diff(State0),
ConfigVersion = compute_config_version(get_local_config(),
get_host_local_config()),
FileVersion = compute_config_file_version(State0),
?WARNING_MSG("cluster config reload from ~s scheduled", [ConfigFile]),
%% first apply on local
State1 = State0#state{override_global = true,
override_local = true, override_acls = true},
case catch apply_changes(CC, LC, LHC, State1, ConfigVersion) of
{ok, CurrentNode} ->
%% apply on other nodes
{S,F} = rpc:multicall(nodes(), ?MODULE, apply_changes_remote,
[ConfigFile, ConfigDiff,
ConfigVersion, FileVersion],
30000),
{S1,F1} = group_nodes_results([{ok,node()} | S],F),
ResultText = (groups_to_string("# Reloaded:", S1)
++ groups_to_string("\n# Failed:", F1)),
case F1 of
[] -> ?WARNING_MSG("cluster config reloaded successfully", []);
[_|_] ->
FailedUpdateOrRPC = F ++ [Node || {error, Node, _} <- S],
?WARNING_MSG("cluster config reload failed on nodes: ~p",
[FailedUpdateOrRPC])
end,
{ok, ResultText};
Error ->
Reason = msg("failed to apply config on node: ~p~nreason: ~p",
[CurrentNode, Error]),
?WARNING_MSG("cluster config reload failed!~n"
"config file: ~s~n"
"reason: ~ts", [ConfigFile, Reason]),
exit(Reason)
end.
-spec groups_to_string(string(), [string()]) -> string().
groups_to_string(_Header, []) ->
"";
groups_to_string(Header, S) ->
Header++"\n"++string:join(S,"\n").
-spec group_nodes_results(list(), [atom]) -> {[string()],[string()]}.
group_nodes_results(SuccessfullRPC, FailedRPC) ->
{S,F} = lists:foldl(fun (El, {SN,FN}) ->
case El of
{ok, Node} ->
{[atom_to_list(Node) | SN], FN};
{error, Node, Reason} ->
{SN, [atom_to_list(Node)++" "++Reason|FN]}
end
end, {[],[]}, SuccessfullRPC),
{S,F ++ lists:map(fun (E) -> {atom_to_list(E)++" "++"RPC failed"} end, FailedRPC)}.
-spec get_config_diff(state()) -> {ConfigChanges,
LocalConfigChanges,
LocalHostsChanges} when
ConfigChanges :: compare_result(),
LocalConfigChanges :: compare_result(),
LocalHostsChanges :: compare_result().
get_config_diff(State) ->
% New Options
{NewConfig, NewLocal, NewHostsLocal} = categorize_options(State#state.opts),
% Current Options
Config = get_global_config(),
Local = get_local_config(),
HostsLocal = get_host_local_config(),
%% global config diff
CC = compare_terms(Config, NewConfig, 2, 3),
LC = compare_terms(Local, NewLocal, 2, 3),
LHC = compare_terms(group_host_changes(HostsLocal), group_host_changes(NewHostsLocal), 1, 2),
{CC, LC, LHC}.
-spec apply_changes_remote(file:name(), term(), binary(), binary()) ->
{ok, node()}| {error,node(),string()}.
apply_changes_remote(NewConfigFilePath, ConfigDiff,
DesiredConfigVersion, DesiredFileVersion) ->
?WARNING_MSG("remote config reload scheduled", []),
?DEBUG("~ndesired config version: ~p"
"~ndesired file version: ~p",
[DesiredConfigVersion, DesiredFileVersion]),
Node = node(),
{CC, LC, LHC} = ConfigDiff,
State0 = parse_file(NewConfigFilePath),
case compute_config_file_version(State0) of
DesiredFileVersion ->
State1 = State0#state{override_global = false,
override_local = true,
override_acls = false},
case catch apply_changes(CC, LC, LHC, State1,
DesiredConfigVersion) of
{ok, Node} = R ->
?WARNING_MSG("remote config reload succeeded", []),
R;
UnknownResult ->
?WARNING_MSG("remote config reload failed! "
"can't apply desired config", []),
{error, Node,
lists:flatten(io_lib:format("~p", [UnknownResult]))}
end;
_ ->
?WARNING_MSG("remote config reload failed! "
"can't compute current config version", []),
{error, Node, io_lib:format("Mismatching config file", [])}
end.
-spec apply_changes(term(), term(), term(), state(), binary()) ->
{ok, node()} | {error, node(), string()}.
apply_changes(ConfigChanges, LocalConfigChanges, LocalHostsChanges,
State, DesiredConfigVersion) ->
ConfigVersion = compute_config_version(get_local_config(),
get_host_local_config()),
?DEBUG("config version: ~p", [ConfigVersion]),
case ConfigVersion of
DesiredConfigVersion ->
ok;
_ ->
exit("Outdated configuration on node; cannot apply new one")
end,
%% apply config
set_opts(State),
reload_config(ConfigChanges),
reload_local_config(LocalConfigChanges),
reload_local_hosts_config(LocalHostsChanges),
{ok, node()}.
reload_config(#compare_result{to_start = CAdd, to_stop = CDel,
to_reload = CChange}) ->
lists:foreach(fun handle_config_change/1, CChange),
lists:foreach(fun handle_config_add/1, CAdd),
lists:foreach(fun handle_config_del/1, CDel).
reload_local_config(#compare_result{to_start = LCAdd, to_stop = LCDel,
to_reload = LCChange}) ->
lists:foreach(fun handle_local_config_change/1, LCChange),
lists:foreach(fun handle_local_config_add/1, LCAdd),
lists:foreach(fun handle_local_config_del/1, LCDel).
reload_local_hosts_config(#compare_result{to_start = LCHAdd, to_stop = LCHDel,
to_reload = LCHChange}) ->
lists:foreach(fun handle_local_hosts_config_change/1, LCHChange),
lists:foreach(fun handle_local_hosts_config_add/1, LCHAdd),
lists:foreach(fun handle_local_hosts_config_del/1, LCHDel).
%% ----------------------------------------------------------------
CONFIG
%% ----------------------------------------------------------------
handle_config_add(#config{key = hosts, value = Hosts}) when is_list(Hosts) ->
lists:foreach(fun(Host) -> add_virtual_host(Host) end, Hosts).
handle_config_del(#config{key = hosts,value = Hosts}) ->
lists:foreach(fun(Host) -> remove_virtual_host(Host) end, Hosts).
%% handle add/remove new hosts
handle_config_change({hosts, OldHosts, NewHosts})->
{ToDel, ToAdd} = check_hosts(NewHosts, OldHosts),
lists:foreach(fun remove_virtual_host/1, ToDel),
lists:foreach(fun add_virtual_host/1, ToAdd);
handle_config_change({language, _Old, _New}) ->
ok;
handle_config_change({_Key, _OldValue, _NewValue}) ->
ok.
%% ----------------------------------------------------------------
%% LOCAL CONFIG
%% ----------------------------------------------------------------
handle_local_config_add(#local_config{key = riak_server}) ->
mongoose_riak:start();
handle_local_config_add(#local_config{key=Key} = El) ->
case Key of
true ->
ok;
false ->
?WARNING_MSG("local config add ~p option unhandled",[El])
end.
handle_local_config_del(#local_config{key = riak_server}) ->
mongoose_riak:stop();
handle_local_config_del(#local_config{key = node_start}) ->
%% do nothing with it
ok;
handle_local_config_del(#local_config{key=Key} = El) ->
case can_be_ignored(Key) of
true ->
ok;
false ->
?WARNING_MSG("local config change: ~p unhandled",[El])
end.
handle_local_config_change({listen, Old, New}) ->
reload_listeners(compare_listeners(Old, New));
handle_local_config_change({riak_server, _Old, _New}) ->
mongoose_riak:stop(),
mongoose_riak:start(),
ok;
handle_local_config_change({Key, _Old, _New} = El) ->
case can_be_ignored(Key) of
true ->
ok;
false ->
?WARNING_MSG("local config change: ~p unhandled",[El])
end.
%% ----------------------------------------------------------------
%% LOCAL HOST CONFIG
%% ----------------------------------------------------------------
handle_local_hosts_config_add({{auth, Host}, _}) ->
ejabberd_auth:start(Host);
handle_local_hosts_config_add({{odbc, Host}, _}) ->
ejabberd_rdbms:start(Host);
handle_local_hosts_config_add({{ldap, _Host}, _}) ->
ignore ldap section
ok;
handle_local_hosts_config_add({{modules, Host}, Modules}) ->
lists:foreach(
fun({Module, Args}) ->
gen_mod:start_module(Host, Module, Args)
end, Modules);
handle_local_hosts_config_add({{Key,_Host}, _} = El) ->
case can_be_ignored(Key) of
true ->
ok;
false ->
?WARNING_MSG("local hosts config add option: ~p unhandled",[El])
end.
handle_local_hosts_config_del({{auth, Host}, Opts}) ->
case lists:keyfind(auth_method, 1, Opts) of
false ->
ok;%nothing to stop?
{auth_method, Val} ->
AuthModules = methods_to_auth_modules(Val),
lists:foreach(fun(M) ->
M:stop(Host)
end, AuthModules)
end;
handle_local_hosts_config_del({{odbc, Host}, _}) ->
ejabberd_rdbms:stop_odbc(Host);
handle_local_hosts_config_del({{ldap, _Host}, _I}) ->
ignore ldap section , only appli
ok;
handle_local_hosts_config_del({{modules, Host}, Modules}) ->
lists:foreach(
fun({Module, _Args}) ->
gen_mod:stop_module(Host, Module)
end, Modules);
handle_local_hosts_config_del({{Key,_}, _} =El) ->
case can_be_ignored(Key) of
true ->
ok;
false ->
?WARNING_MSG("local hosts config delete option: ~p unhandled",[El])
end.
handle_local_hosts_config_change({{odbc,Host}, Old, _}) ->
%% stop rdbms
case lists:keyfind({odbc_server, Host},1 ,Old) of
false ->
ok;
#local_config{} ->
ejabberd_rdbms:stop_odbc(Host)
end,
ejabberd_rdbms:start(Host);
handle_local_hosts_config_change({{auth, Host}, OldVals, _}) ->
case lists:keyfind(auth_method, 1, OldVals) of
false ->
ejabberd_auth:stop(Host);
{auth_method, Val} ->
%% stop old modules
AuthModules = methods_to_auth_modules(Val),
lists:foreach(fun (M) ->
M:stop(Host)
end, AuthModules)
end,
ejabberd_auth:start(Host);
handle_local_hosts_config_change({{ldap, Host}, _OldConfig, NewConfig}) ->
ok = ejabberd_hooks:run_fold(host_config_update, Host, ok, [Host, ldap, NewConfig]);
handle_local_hosts_config_change({{modules,Host}, OldModules, NewModules}) ->
Res = compare_modules(OldModules, NewModules),
reload_modules(Host, Res);
handle_local_hosts_config_change({{Key,_Host},_Old,_New} = El) ->
case can_be_ignored(Key) of
true ->
ok;
false ->
?WARNING_MSG("local hosts config change option: ~p unhandled",[El])
end.
methods_to_auth_modules(L) when is_list(L) ->
[list_to_atom("ejabberd_auth_" ++ atom_to_list(M)) || M <- L];
methods_to_auth_modules(A) when is_atom(A) ->
methods_to_auth_modules([A]).
compute_config_version(LC, LCH) ->
L0 = lists:filter(mk_node_start_filter(), LC ++ LCH),
L1 = sort_config(L0),
crypto:hash(sha, term_to_binary(L1)).
compute_config_file_version(#state{opts = Opts, hosts = Hosts}) ->
L = sort_config(Opts ++ Hosts),
crypto:hash(sha, term_to_binary(L)).
-spec check_hosts([ejabberd:server()], [ejabberd:server()]) -> {[ejabberd:server()],
[ejabberd:server()]}.
check_hosts(NewHosts, OldHosts) ->
Old = sets:from_list(OldHosts),
New = sets:from_list(NewHosts),
ListToAdd = sets:to_list(sets:subtract(New,Old)),
ListToDel = sets:to_list(sets:subtract(Old,New)),
{ListToDel, ListToAdd}.
-spec add_virtual_host(Host :: ejabberd:server()) -> any().
add_virtual_host(Host) ->
?DEBUG("Register host:~p",[Host]),
ejabberd_local:register_host(Host).
-spec can_be_ignored(Key :: atom()) -> boolean().
can_be_ignored(Key) when is_atom(Key) ->
L = [domain_certfile, s2s],
lists:member(Key,L).
-spec remove_virtual_host(ejabberd:server()) -> any().
remove_virtual_host(Host) ->
?DEBUG("Unregister host :~p", [Host]),
ejabberd_local:unregister_host(Host).
-spec reload_modules(Host :: ejabberd:server(),
ChangedModules :: compare_result()) -> 'ok'.
reload_modules(Host, #compare_result{to_start = Start, to_stop = Stop,
to_reload = Reload} = ChangedModules) ->
?DEBUG("reload modules: ~p", [lager:pr(ChangedModules, ?MODULE)]),
lists:foreach(fun ({M, _}) ->
gen_mod:stop_module(Host, M)
end, Stop),
lists:foreach(fun ({M, Args}) ->
gen_mod:start_module(Host, M, Args)
end, Start),
lists:foreach(fun({M, _, Args}) ->
gen_mod:reload_module(Host, M, Args)
end, Reload).
-spec reload_listeners(ChangedListeners :: compare_result()) -> 'ok'.
reload_listeners(#compare_result{to_start = Add, to_stop = Del,
to_reload = Change} = ChangedListeners) ->
?DEBUG("reload listeners: ~p", [lager:pr(ChangedListeners, ?MODULE)]),
lists:foreach(fun ({{PortIP, Module}, Opts}) ->
ejabberd_listener:delete_listener(PortIP, Module, Opts)
end, Del),
lists:foreach(fun ({{PortIP, Module}, Opts}) ->
ejabberd_listener:add_listener(PortIP, Module, Opts)
end, Add),
lists:foreach(fun ({{PortIP,Module}, OldOpts, NewOpts}) ->
ejabberd_listener:delete_listener(PortIP, Module, OldOpts),
ejabberd_listener:add_listener(PortIP, Module, NewOpts)
end, Change).
-spec compare_modules(term(), term()) -> compare_result().
compare_modules(OldMods, NewMods) ->
compare_terms(OldMods, NewMods, 1, 2).
-spec compare_listeners(term(), term()) -> compare_result().
compare_listeners(OldListeners, NewListeners) ->
compare_terms(map_listeners(OldListeners), map_listeners(NewListeners), 1, 2).
map_listeners(Listeners) ->
lists:map(fun ({PortIP,Module,Opts})->
{{PortIP,Module},Opts}
end, Listeners).
% group values which can be grouped like odbc ones
-spec group_host_changes([term()]) -> [{atom(), [term()]}].
group_host_changes(Changes) when is_list(Changes) ->
D = lists:foldl(fun (#local_config{key = {Key, Host}, value = Val}, Dict) ->
BKey = atom_to_binary(Key, utf8),
case get_key_group(BKey,Key) of
Key ->
dict:append({Key,Host}, Val, Dict);
NewKey ->
dict:append({NewKey,Host}, {Key, Val}, Dict)
end
end, dict:new(), Changes),
[{Group, lists:sort(lists:flatten(MaybeDeepList))}
|| {Group, MaybeDeepList} <- dict:to_list(D)].
%% match all hosts
-spec get_host_local_config() -> [{local_config, {term(), ejabberd:server()}, term()}].
get_host_local_config() ->
mnesia:dirty_match_object({local_config, {'_','_'}, '_'}).
-spec get_local_config() -> [{local_config, term(), term()}].
get_local_config() ->
Keys = lists:filter(fun is_not_host_specific/1,mnesia:dirty_all_keys(local_config)),
lists:flatten(lists:map(fun (Key) ->
mnesia:dirty_read(local_config, Key)
end,
Keys)).
-spec get_global_config() -> [{config, term(), term()}].
get_global_config() ->
mnesia:dirty_match_object(config, {config, '_', '_'}).
-spec is_not_host_specific(atom() | {atom(), ejabberd:server()}) -> boolean().
is_not_host_specific( Key ) when is_atom(Key) ->
true;
is_not_host_specific({Key, Host}) when is_atom(Key), is_binary(Host) ->
false.
-spec categorize_options([term()]) -> {GlobalConfig, LocalConfig, HostsConfig} when
GlobalConfig :: list(),
LocalConfig :: list(),
HostsConfig :: list().
categorize_options(Opts) ->
lists:foldl(fun ({config, _, _} = El, Acc) ->
as_global(El, Acc);
({local_config, {Key, Host}, _} = El, Acc)
when is_atom(Key), is_binary(Host) ->
as_hosts(El, Acc);
({local_config, _, _} = El, Acc) ->
as_local(El, Acc);
({acl, _, _}, R) ->
%% no need to do extra work here
R;
(R, R2) ->
?ERROR_MSG("not matched ~p", [R]),
R2
end, {[], [], []}, Opts).
as_global(El, {Config, Local, HostLocal}) -> {[El | Config], Local, HostLocal}.
as_local(El, {Config, Local, HostLocal}) -> {Config, [El | Local], HostLocal}.
as_hosts(El, {Config, Local, HostLocal}) -> {Config, Local, [El | HostLocal]}.
-spec get_key_group(binary(), atom()) -> atom().
get_key_group(<<"ldap_", _/binary>>, _) ->
ldap;
get_key_group(<<"odbc_", _/binary>>, _) ->
odbc;
get_key_group(<<"pgsql_", _/binary>>, _) ->
odbc;
get_key_group(<<"auth_", _/binary>>, _) ->
auth;
get_key_group(<<"ext_auth_", _/binary>>, _) ->
auth;
get_key_group(<<"s2s_",_/binary>>, _) ->
s2s;
get_key_group(_, Key) when is_atom(Key)->
Key.
-spec compare_terms(OldTerms :: [tuple()],
NewTerms :: [tuple()],
KeyPos :: non_neg_integer(),
ValuePos :: non_neg_integer()) -> compare_result().
compare_terms(OldTerms, NewTerms, KeyPos, ValuePos)
when is_integer(KeyPos), is_integer(ValuePos) ->
{ToStop, ToReload} = lists:foldl(pa:bind(fun find_modules_to_change/5,
KeyPos, NewTerms, ValuePos),
{[], []}, OldTerms),
ToStart = lists:foldl(pa:bind(fun find_modules_to_start/4,
KeyPos, OldTerms), [], NewTerms),
#compare_result{to_start = ToStart,
to_stop = ToStop,
to_reload = ToReload}.
find_modules_to_start(KeyPos, OldTerms, Element, ToStart) ->
case lists:keyfind(element(KeyPos, Element), KeyPos, OldTerms) of
false -> [ Element | ToStart ];
_ -> ToStart
end.
find_modules_to_change(KeyPos, NewTerms, ValuePos,
Element, {ToStop, ToReload}) ->
case lists:keyfind(element(KeyPos, Element), KeyPos, NewTerms) of
false ->
{ [Element | ToStop], ToReload };
NewElement ->
OldVal = element(ValuePos, Element),
NewVal = element(ValuePos, NewElement),
case OldVal == NewVal of
true ->
{ToStop, ToReload};
false ->
%% add also old value
{ToStop,
[ {element(KeyPos, Element), OldVal, NewVal} | ToReload ]}
end
end.
mk_node_start_filter() ->
fun(#local_config{key = node_start}) ->
false;
(_) ->
true
end.
sort_config(Config) when is_list(Config) ->
L = lists:map(fun(ConfigItem) when is_list(ConfigItem) ->
sort_config(ConfigItem);
(ConfigItem) when is_tuple(ConfigItem) ->
sort_config(tuple_to_list(ConfigItem));
(ConfigItem) ->
ConfigItem
end, Config),
lists:sort(L).
| null | https://raw.githubusercontent.com/MyDataFlow/ttalk-server/07a60d5d74cd86aedd1f19c922d9d3abf2ebf28d/apps/ejabberd/src/ejabberd_config.erl | erlang | ----------------------------------------------------------------------
File : ejabberd_config.erl
Purpose : Load config file
This program is free software; you can redistribute it and/or
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.
along with this program; if not, write to the Free Software
----------------------------------------------------------------------
for unit tests
conf reload
TODO: binary is questionable here
TODO: specify this
The atom must have all characters in uppercase.
This start time is used by mod_last:
@doc Get the filename of the ejabberd configuration file.
The filename can be specified with: erl -config "/path/to/ejabberd.cfg".
It can also be specified with the environtment variable EJABBERD_CONFIG_PATH.
If not specified, the default value 'ejabberd.cfg' is assumed.
@doc Load the ejabberd configuration file.
It also includes additional configuration files and replaces macros.
This function will crash if finds some error in the configuration file.
@doc Read an ejabberd configuration file and return the terms.
Input is an absolute or relative path to an ejabberd config file.
Returns a list of plain terms,
in which the options 'include_config_file' were parsed
and the terms in those files were included.
@doc Convert configuration filename to absolute path.
Input is an absolute or relative path to an ejabberd configuration file.
And returns an absolute path to the configuration file.
Errors reading the config file
spec me better
spec me better
@doc If ejabberd isn't yet running in this node, then halt the node
Support for 'include_config_file'
@doc Include additional configuration files in the list of terms.
@doc Filter from the list of terms the disallowed.
@doc Keep from the list only the allowed terms.
included in Allowed.
Support for Macro
@doc Replace the macros with their defined values.
@doc Split Terms into normal terms and macro definitions.
@doc Recursively replace in Terms macro usages with the defined value.
Process terms
lists:foldl(fun(Host, S) -> process_host_term(Term, Host, S) end,
If the key of a local_config matches the Opt that wants to be added
Then prepend the new value to the list of old values
@doc Return the list of hosts handled by a given module
--------------------------------------------------------------------
Configuration reload
--------------------------------------------------------------------
Won't be unnecessarily evaluated if used as an argument
to lager parse transform.
first apply on local
apply on other nodes
New Options
Current Options
global config diff
apply config
----------------------------------------------------------------
----------------------------------------------------------------
handle add/remove new hosts
----------------------------------------------------------------
LOCAL CONFIG
----------------------------------------------------------------
do nothing with it
----------------------------------------------------------------
LOCAL HOST CONFIG
----------------------------------------------------------------
nothing to stop?
stop rdbms
stop old modules
group values which can be grouped like odbc ones
match all hosts
no need to do extra work here
add also old value | Author : < >
Created : 14 Dec 2002 by < >
ejabberd , Copyright ( C ) 2002 - 2011 ProcessOne
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 2 of the
You should have received a copy of the GNU General Public License
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA
02111 - 1307 USA
-module(ejabberd_config).
-author('').
-export([start/0,
load_file/1,
add_global_option/2,
get_global_option/1,
add_local_option/2,
get_local_option/1,
get_local_option/2,
del_local_option/1,
get_local_option_or_default/2]).
-export([get_vh_by_auth_method/1]).
-export([is_file_readable/1]).
-export([check_hosts/2,
compare_modules/2,
compare_listeners/2,
group_host_changes/1]).
-export([reload_local/0,
reload_cluster/0,
apply_changes_remote/4,
apply_changes/5]).
-export([compute_config_version/2,
get_local_config/0,
get_host_local_config/0]).
-include("ejabberd.hrl").
-include("ejabberd_config.hrl").
-include_lib("kernel/include/file.hrl").
-define(CONFIG_RELOAD_TIMEOUT, 30000).
-type key() :: atom()
| {key(), ejabberd:server() | atom() | list()}
| {atom(), atom(), atom()}
-type value() :: atom()
| binary()
| integer()
| string()
| [value()]
| tuple().
-export_type([key/0, value/0]).
-record(state, { opts = [] :: list(),
hosts = [] :: [host()],
override_local = false :: boolean(),
override_global = false :: boolean(),
override_acls = false :: boolean() }).
-record(compare_result, {to_start = [] :: list(),
to_stop = [] :: list(),
to_reload = [] :: list()}).
-type compare_result() :: #compare_result{}.
-type state() :: #state{}.
-type macro() :: {macro_key(), macro_value()}.
-type macro_key() :: atom().
-type macro_value() :: term().
-type known_term() :: override_global
| override_local
| override_acls
| {acl, _, _}
| {alarms, _}
| {access, _, _}
| {shaper, _, _}
| {host, _}
| {hosts, _}
| {host_config, _, _}
| {listen, _}
| {language, _}
| {sm_backend, _}
| {outgoing_s2s_port, integer()}
| {outgoing_s2s_options, _, integer()}
| {{s2s_addr, _}, _}
| {s2s_dns_options, [tuple()]}
| {s2s_use_starttls, integer()}
| {s2s_certfile, _}
| {domain_certfile, _, _}
| {node_type, _}
| {cluster_nodes, _}
| {registration_timeout, integer()}
| {mongooseimctl_access_commands, list()}
| {loglevel, _}
| {max_fsm_queue, _}
| host_term().
-type host_term() :: {acl, _, _}
| {access, _, _}
| {shaper, _, _}
| {host, _}
| {hosts, _}
| {odbc_server, _}.
-spec start() -> ok.
start() ->
mnesia:create_table(config,
[{ram_copies, [node()]},
{storage_properties,
[{ets, [{read_concurrency,true}]}]},
{attributes, record_info(fields, config)}]),
mnesia:add_table_copy(config, node(), ram_copies),
mnesia:create_table(local_config,
[{ram_copies, [node()]},
{storage_properties,
[{ets, [{read_concurrency,true}]}]},
{local_content, true},
{attributes, record_info(fields, local_config)}]),
mnesia:add_table_copy(local_config, node(), ram_copies),
Config = get_ejabberd_config_path(),
ejabberd_config:load_file(Config),
add_local_option(node_start, now()),
ok.
-spec get_ejabberd_config_path() -> string().
get_ejabberd_config_path() ->
DefaultPath = case os:getenv("EJABBERD_CONFIG_PATH") of
false ->
?CONFIG_PATH;
Path ->
Path
end,
application:get_env(ejabberd, config, DefaultPath).
-spec load_file(File::string()) -> ok.
load_file(File) ->
Terms = get_plain_terms_file(File),
State = lists:foldl(fun search_hosts/2, #state{}, Terms),
Terms_macros = replace_macros(Terms),
Res = lists:foldl(fun process_term/2, State, Terms_macros),
set_opts(Res).
-spec get_plain_terms_file(string()) -> [term()].
get_plain_terms_file(File1) ->
File = get_absolute_path(File1),
case file:consult(File) of
{ok, Terms} ->
include_config_files(Terms);
{error, {LineNumber, erl_parse, _ParseMessage} = Reason} ->
ExitText = describe_config_problem(File, Reason, LineNumber),
?ERROR_MSG(ExitText, []),
exit_or_halt(ExitText);
{error, Reason} ->
ExitText = describe_config_problem(File, Reason),
?ERROR_MSG(ExitText, []),
exit_or_halt(ExitText)
end.
-spec get_absolute_path(string()) -> string().
get_absolute_path(File) ->
case filename:pathtype(File) of
absolute ->
File;
relative ->
{ok, Cwd} = file:get_cwd(),
filename:absname_join(Cwd, File)
end.
-spec search_hosts({host|hosts, [host()] | host()}, state()) -> any().
search_hosts(Term, State) ->
case Term of
{host, Host} ->
if
State#state.hosts == [] ->
add_hosts_to_option([Host], State);
true ->
?ERROR_MSG("Can't load config file: "
"too many hosts definitions", []),
exit("too many hosts definitions")
end;
{hosts, Hosts} ->
if
State#state.hosts == [] ->
add_hosts_to_option(Hosts, State);
true ->
?ERROR_MSG("Can't load config file: "
"too many hosts definitions", []),
exit("too many hosts definitions")
end;
_ ->
State
end.
-spec add_hosts_to_option(Hosts :: [host()],
State :: state()) -> state().
add_hosts_to_option(Hosts, State) ->
PrepHosts = normalize_hosts(Hosts),
add_option(hosts, PrepHosts, State#state{hosts = PrepHosts}).
-spec normalize_hosts([host()]) -> [binary() | tuple()].
normalize_hosts(Hosts) ->
normalize_hosts(Hosts,[]).
normalize_hosts([], PrepHosts) ->
lists:reverse(PrepHosts);
normalize_hosts([Host|Hosts], PrepHosts) ->
case jid:nodeprep(host_to_binary(Host)) of
error ->
?ERROR_MSG("Can't load config file: "
"invalid host name [~p]", [Host]),
exit("invalid hostname");
PrepHost ->
normalize_hosts(Hosts, [PrepHost|PrepHosts])
end.
-ifdef(latin1_characters).
host_to_binary(Host) ->
list_to_binary(Host).
-else.
host_to_binary(Host) ->
unicode:characters_to_binary(Host).
-endif.
-spec describe_config_problem(Filename :: string(),
Reason :: config_problem()) -> string().
describe_config_problem(Filename, Reason) ->
Text1 = lists:flatten("Problem loading ejabberd config file " ++ Filename),
Text2 = lists:flatten(" : " ++ file:format_error(Reason)),
ExitText = Text1 ++ Text2,
ExitText.
-spec describe_config_problem(Filename :: string(),
Reason :: config_problem(),
Line :: pos_integer()) -> string().
describe_config_problem(Filename, Reason, LineNumber) ->
Text1 = lists:flatten("Problem loading ejabberd config file " ++ Filename),
Text2 = lists:flatten(" approximately in the line "
++ file:format_error(Reason)),
ExitText = Text1 ++ Text2,
Lines = get_config_lines(Filename, LineNumber, 10, 3),
?ERROR_MSG("The following lines from your configuration file might be"
" relevant to the error: ~n~s", [Lines]),
ExitText.
-spec get_config_lines(Filename :: string(),
TargetNumber :: integer(),
PreContext :: 10,
PostContext :: 3) -> [config_line()].
get_config_lines(Filename, TargetNumber, PreContext, PostContext) ->
{ok, Fd} = file:open(Filename, [read]),
LNumbers = lists:seq(TargetNumber-PreContext, TargetNumber+PostContext),
NextL = io:get_line(Fd, no_prompt),
R = get_config_lines2(Fd, NextL, 1, LNumbers, []),
file:close(Fd),
R.
get_config_lines2(_Fd, eof, _CurrLine, _LNumbers, R) ->
lists:reverse(R);
get_config_lines2(_Fd, _NewLine, _CurrLine, [], R) ->
lists:reverse(R);
get_config_lines2(Fd, Data, CurrLine, [NextWanted | LNumbers], R) when is_list(Data) ->
NextL = io:get_line(Fd, no_prompt),
if
CurrLine >= NextWanted ->
Line2 = [integer_to_list(CurrLine), ": " | Data],
get_config_lines2(Fd, NextL, CurrLine+1, LNumbers, [Line2 | R]);
true ->
get_config_lines2(Fd, NextL, CurrLine+1, [NextWanted | LNumbers], R)
end.
-spec exit_or_halt(ExitText :: string()) -> none().
exit_or_halt(ExitText) ->
case [Vsn || {ejabberd, _Desc, Vsn} <- application:which_applications()] of
[] ->
timer:sleep(1000),
halt(string:substr(ExitText, 1, 199));
[_] ->
exit(ExitText)
end.
-spec include_config_files([term()]) -> [term()].
include_config_files(Terms) ->
include_config_files(Terms, []).
include_config_files([], Res) ->
Res;
include_config_files([{include_config_file, Filename} | Terms], Res) ->
include_config_files([{include_config_file, Filename, []} | Terms], Res);
include_config_files([{include_config_file, Filename, Options} | Terms], Res) ->
Included_terms = get_plain_terms_file(Filename),
Disallow = proplists:get_value(disallow, Options, []),
Included_terms2 = delete_disallowed(Disallow, Included_terms),
Allow_only = proplists:get_value(allow_only, Options, all),
Included_terms3 = keep_only_allowed(Allow_only, Included_terms2),
include_config_files(Terms, Res ++ Included_terms3);
include_config_files([Term | Terms], Res) ->
include_config_files(Terms, Res ++ [Term]).
Returns a sublist of Terms without the ones which first element is
included in Disallowed .
-spec delete_disallowed(Disallowed :: [atom()],
Terms :: [term()]) -> [term()].
delete_disallowed(Disallowed, Terms) ->
lists:foldl(
fun(Dis, Ldis) ->
delete_disallowed2(Dis, Ldis)
end,
Terms,
Disallowed).
delete_disallowed2(Disallowed, [H|T]) ->
case element(1, H) of
Disallowed ->
?WARNING_MSG("The option '~p' is disallowed, "
"and will not be accepted", [Disallowed]),
delete_disallowed2(Disallowed, T);
_ ->
[H|delete_disallowed2(Disallowed, T)]
end;
delete_disallowed2(_, []) ->
[].
Returns a sublist of Terms with only the ones which first element is
-spec keep_only_allowed(Allowed :: [atom()],
Terms::[term()]) -> [term()].
keep_only_allowed(all, Terms) ->
Terms;
keep_only_allowed(Allowed, Terms) ->
{As, NAs} = lists:partition(
fun(Term) ->
lists:member(element(1, Term), Allowed)
end,
Terms),
[?WARNING_MSG("This option is not allowed, "
"and will not be accepted:~n~p", [NA])
|| NA <- NAs],
As.
-spec replace_macros(Terms :: [term()]) -> [term()].
replace_macros(Terms) ->
{TermsOthers, Macros} = split_terms_macros(Terms),
replace(TermsOthers, Macros).
-spec split_terms_macros(Terms :: [term()]) -> {[term()], [macro()]}.
split_terms_macros(Terms) ->
lists:foldl(
fun(Term, {TOs, Ms}) ->
case Term of
{define_macro, Key, Value} ->
case is_atom(Key) and is_all_uppercase(Key) of
true ->
{TOs, Ms++[{Key, Value}]};
false ->
exit({macro_not_properly_defined, Term})
end;
Term ->
{TOs ++ [Term], Ms}
end
end,
{[], []},
Terms).
-spec replace(Terms :: [term()],
Macros :: [macro()]) -> [term()].
replace([], _) ->
[];
replace([Term|Terms], Macros) ->
[replace_term(Term, Macros) | replace(Terms, Macros)].
replace_term(Key, Macros) when is_atom(Key) ->
case is_all_uppercase(Key) of
true ->
case proplists:get_value(Key, Macros) of
undefined -> exit({undefined_macro, Key});
Value -> Value
end;
false ->
Key
end;
replace_term({use_macro, Key, Value}, Macros) ->
proplists:get_value(Key, Macros, Value);
replace_term(Term, Macros) when is_list(Term) ->
replace(Term, Macros);
replace_term(Term, Macros) when is_tuple(Term) ->
List = tuple_to_list(Term),
List2 = replace(List, Macros),
list_to_tuple(List2);
replace_term(Term, _) ->
Term.
-spec is_all_uppercase(atom()) -> boolean().
is_all_uppercase(Atom) ->
String = erlang:atom_to_list(Atom),
lists:all(fun(C) when C >= $a, C =< $z -> false;
(_) -> true
end, String).
-spec process_term(Term :: known_term(),
State :: state()) -> state().
process_term(Term, State) ->
case Term of
override_global ->
State#state{override_global = true};
override_local ->
State#state{override_local = true};
override_acls ->
State#state{override_acls = true};
{acl, _ACLName, _ACLData} ->
process_host_term(Term, global, State);
{alarms, Env} ->
add_option(alarms, Env, State);
{access, _RuleName, _Rules} ->
process_host_term(Term, global, State);
{shaper, _Name, _Data} ->
State , State#state.hosts ) ;
process_host_term(Term, global, State);
{host, _Host} ->
State;
{hosts, _Hosts} ->
State;
{host_config, Host, Terms} ->
lists:foldl(fun(T, S) ->
process_host_term(T, list_to_binary(Host), S) end,
State, Terms);
{listen, Listeners} ->
Listeners2 =
lists:map(
fun({PortIP, Module, Opts}) ->
{Port, IPT, _, _, Proto, OptsClean} =
ejabberd_listener:parse_listener_portip(PortIP, Opts),
{{Port, IPT, Proto}, Module, OptsClean}
end,
Listeners),
add_option(listen, Listeners2, State);
{language, Val} ->
add_option(language, list_to_binary(Val), State);
{sm_backend, Val} ->
add_option(sm_backend, Val, State);
{outgoing_s2s_port, Port} ->
add_option(outgoing_s2s_port, Port, State);
{outgoing_s2s_options, Methods, Timeout} ->
add_option(outgoing_s2s_options, {Methods, Timeout}, State);
{{s2s_addr, Host}, Addr} ->
add_option({s2s_addr, list_to_binary(Host)}, Addr, State);
{s2s_dns_options, PropList} ->
add_option(s2s_dns_options, PropList, State);
{s2s_use_starttls, Port} ->
add_option(s2s_use_starttls, Port, State);
{s2s_ciphers, Ciphers} ->
add_option(s2s_ciphers, Ciphers, State);
{s2s_certfile, CertFile} ->
case ejabberd_config:is_file_readable(CertFile) of
true -> add_option(s2s_certfile, CertFile, State);
false ->
ErrorText = "There is a problem in the configuration: "
"the specified file is not readable: ",
throw({error, ErrorText ++ CertFile})
end;
{domain_certfile, Domain, CertFile} ->
case ejabberd_config:is_file_readable(CertFile) of
true -> add_option({domain_certfile, Domain}, CertFile, State);
false ->
ErrorText = "There is a problem in the configuration: "
"the specified file is not readable: ",
throw({error, ErrorText ++ CertFile})
end;
{node_type, NodeType} ->
add_option(node_type, NodeType, State);
{cluster_nodes, Nodes} ->
add_option(cluster_nodes, Nodes, State);
{watchdog_admins, Admins} ->
add_option(watchdog_admins, Admins, State);
{watchdog_large_heap, LH} ->
add_option(watchdog_large_heap, LH, State);
{registration_timeout, Timeout} ->
add_option(registration_timeout, Timeout, State);
{mongooseimctl_access_commands, ACs} ->
add_option(mongooseimctl_access_commands, ACs, State);
{loglevel, Loglevel} ->
ejabberd_loglevel:set(Loglevel),
State;
{max_fsm_queue, N} ->
add_option(max_fsm_queue, N, State);
{_Opt, _Val} ->
lists:foldl(fun(Host, S) -> process_host_term(Term, Host, S) end,
State, State#state.hosts)
end.
-spec process_host_term(Term :: host_term(),
Host :: acl:host(),
State :: state()) -> state().
process_host_term(Term, Host, State) ->
case Term of
{acl, ACLName, ACLData} ->
State#state{opts =
[acl:to_record(Host, ACLName, ACLData) | State#state.opts]};
{access, RuleName, Rules} ->
State#state{opts = [#config{key = {access, RuleName, Host},
value = Rules} |
State#state.opts]};
{shaper, Name, Data} ->
State#state{opts = [#config{key = {shaper, Name, Host},
value = Data} |
State#state.opts]};
{host, Host} ->
State;
{hosts, _Hosts} ->
State;
{odbc_server, ODBC_server} ->
add_option({odbc_server, Host}, ODBC_server, State);
{riak_server, RiakConfig} ->
add_option(riak_server, RiakConfig, State);
{Opt, Val} ->
add_option({Opt, Host}, Val, State)
end.
-spec add_option(Opt :: key(),
Val :: value(),
State :: state()) -> state().
add_option(Opt, Val, State) ->
Table = case Opt of
hosts ->
config;
language ->
config;
sm_backend ->
config;
_ ->
local_config
end,
case Table of
config ->
State#state{opts = [#config{key = Opt, value = Val} |
State#state.opts]};
local_config ->
case Opt of
{{add, OptName}, Host} ->
State#state{opts = compact({OptName, Host}, Val,
State#state.opts, [])};
_ ->
State#state{opts = [#local_config{key = Opt, value = Val} |
State#state.opts]}
end
end.
compact({OptName, Host} = Opt, Val, [], Os) ->
?WARNING_MSG("The option '~p' is defined for the host ~p using host_config "
"before the global '~p' option. This host_config option may "
"get overwritten.", [OptName, Host, OptName]),
[#local_config{key = Opt, value = Val}] ++ Os;
Traverse the list of the options already parsed
compact(Opt, Val, [O | Os1], Os2) ->
case catch O#local_config.key of
Opt ->
Os2 ++ [#local_config{key = Opt,
value = Val++O#local_config.value}
] ++ Os1;
_ ->
compact(Opt, Val, Os1, Os2++[O])
end.
-spec set_opts(state()) -> 'ok' | none().
set_opts(State) ->
Opts = lists:reverse(State#state.opts),
F = fun() ->
if
State#state.override_global ->
Ksg = mnesia:all_keys(config),
lists:foreach(fun(K) ->
mnesia:delete({config, K})
end, Ksg);
true ->
ok
end,
if
State#state.override_local ->
Ksl = mnesia:all_keys(local_config),
lists:foreach(fun(K) ->
mnesia:delete({local_config, K})
end, lists:delete(node_start, Ksl));
true ->
ok
end,
if
State#state.override_acls ->
Ksa = mnesia:all_keys(acl),
lists:foreach(fun(K) ->
mnesia:delete({acl, K})
end, Ksa);
true ->
ok
end,
lists:foreach(fun(R) ->
mnesia:write(R)
end, Opts)
end,
case mnesia:transaction(F) of
{atomic, _} -> ok;
{aborted,{no_exists,Table}} ->
MnesiaDirectory = mnesia:system_info(directory),
?ERROR_MSG("Error reading Mnesia database spool files:~n"
"The Mnesia database couldn't read the spool file for the table '~p'.~n"
"ejabberd needs read and write access in the directory:~n ~s~n"
"Maybe the problem is a change in the computer hostname,~n"
"or a change in the Erlang node name, which is currently:~n ~p~n"
"Check the ejabberd guide for details about changing the~n"
"computer hostname or Erlang node name.~n",
[Table, MnesiaDirectory, node()]),
exit("Error reading Mnesia database")
end.
-spec add_global_option(Opt :: key(), Val :: value()) -> {atomic|aborted, _}.
add_global_option(Opt, Val) ->
mnesia:transaction(fun() ->
mnesia:write(#config{key = Opt,
value = Val})
end).
-spec add_local_option(Opt :: key(), Val :: value()) -> {atomic|aborted, _}.
add_local_option(Opt, Val) ->
mnesia:transaction(fun() ->
mnesia:write(#local_config{key = Opt,
value = Val})
end).
-spec del_local_option(Opt :: key()) -> {atomic | aborted, _}.
del_local_option(Opt) ->
mnesia:transaction(fun mnesia:delete/1, [{local_config, Opt}]).
-spec get_global_option(key()) -> value() | undefined.
get_global_option(Opt) ->
case ets:lookup(config, Opt) of
[#config{value = Val}] ->
Val;
_ ->
undefined
end.
-spec get_local_option(key()) -> value() | undefined.
get_local_option(Opt) ->
case ets:lookup(local_config, Opt) of
[#local_config{value = Val}] ->
Val;
_ ->
undefined
end.
-spec get_local_option(key(), host()) -> value() | undefined.
get_local_option(Opt, Host) ->
case get_local_option({Opt, Host}) of
undefined -> get_global_option(Opt);
Val -> Val
end.
-spec get_local_option_or_default(key(), value()) -> value().
get_local_option_or_default(Opt, Default) ->
case get_local_option(Opt) of
undefined ->
Default;
Value ->
Value
end.
get_vh_by_auth_method(AuthMethod) ->
mnesia:dirty_select(local_config,
[{#local_config{key = {auth_method, '$1'},
value=AuthMethod},[],['$1']}]).
-spec is_file_readable(Path :: string()) -> boolean().
is_file_readable(Path) ->
case file:read_file_info(Path) of
{ok, FileInfo} ->
case {FileInfo#file_info.type, FileInfo#file_info.access} of
{regular, read} -> true;
{regular, read_write} -> true;
_ -> false
end;
{error, _Reason} ->
false
end.
-spec parse_file(file:name()) -> state().
parse_file(ConfigFile) ->
Terms = get_plain_terms_file(ConfigFile),
State = lists:foldl(fun search_hosts/2, #state{}, Terms),
TermsWExpandedMacros = replace_macros(Terms),
lists:foldl(fun process_term/2, State, TermsWExpandedMacros).
-spec reload_local() -> {ok, iolist()} | no_return().
reload_local() ->
ConfigFile = get_ejabberd_config_path(),
State0 = parse_file(ConfigFile),
{CC, LC, LHC} = get_config_diff(State0),
ConfigVersion = compute_config_version(get_local_config(),
get_host_local_config()),
State1 = State0#state{override_global = true,
override_local = true,
override_acls = true},
try
{ok, _} = apply_changes(CC, LC, LHC, State1, ConfigVersion),
?WARNING_MSG("node config reloaded from ~s", [ConfigFile]),
{ok, io_lib:format("# Reloaded: ~s", [node()])}
catch
Error:Reason ->
Msg = msg("failed to apply config on node: ~p~nreason: ~p",
[node(), {Error, Reason}]),
?WARNING_MSG("node config reload failed!~n"
"current config version: ~p~n"
"config file: ~s~n"
"reason: ~p~n"
"stacktrace: ~ts",
[ConfigVersion, ConfigFile, Msg,
msg("~p", [erlang:get_stacktrace()])]),
error(Msg)
end.
msg(Fmt, Args) ->
lists:flatten(io_lib:format(Fmt, Args)).
-spec reload_cluster() -> {ok, string()} | no_return().
reload_cluster() ->
CurrentNode = node(),
ConfigFile = get_ejabberd_config_path(),
State0 = parse_file(ConfigFile),
ConfigDiff = {CC, LC, LHC} = get_config_diff(State0),
ConfigVersion = compute_config_version(get_local_config(),
get_host_local_config()),
FileVersion = compute_config_file_version(State0),
?WARNING_MSG("cluster config reload from ~s scheduled", [ConfigFile]),
State1 = State0#state{override_global = true,
override_local = true, override_acls = true},
case catch apply_changes(CC, LC, LHC, State1, ConfigVersion) of
{ok, CurrentNode} ->
{S,F} = rpc:multicall(nodes(), ?MODULE, apply_changes_remote,
[ConfigFile, ConfigDiff,
ConfigVersion, FileVersion],
30000),
{S1,F1} = group_nodes_results([{ok,node()} | S],F),
ResultText = (groups_to_string("# Reloaded:", S1)
++ groups_to_string("\n# Failed:", F1)),
case F1 of
[] -> ?WARNING_MSG("cluster config reloaded successfully", []);
[_|_] ->
FailedUpdateOrRPC = F ++ [Node || {error, Node, _} <- S],
?WARNING_MSG("cluster config reload failed on nodes: ~p",
[FailedUpdateOrRPC])
end,
{ok, ResultText};
Error ->
Reason = msg("failed to apply config on node: ~p~nreason: ~p",
[CurrentNode, Error]),
?WARNING_MSG("cluster config reload failed!~n"
"config file: ~s~n"
"reason: ~ts", [ConfigFile, Reason]),
exit(Reason)
end.
-spec groups_to_string(string(), [string()]) -> string().
groups_to_string(_Header, []) ->
"";
groups_to_string(Header, S) ->
Header++"\n"++string:join(S,"\n").
-spec group_nodes_results(list(), [atom]) -> {[string()],[string()]}.
group_nodes_results(SuccessfullRPC, FailedRPC) ->
{S,F} = lists:foldl(fun (El, {SN,FN}) ->
case El of
{ok, Node} ->
{[atom_to_list(Node) | SN], FN};
{error, Node, Reason} ->
{SN, [atom_to_list(Node)++" "++Reason|FN]}
end
end, {[],[]}, SuccessfullRPC),
{S,F ++ lists:map(fun (E) -> {atom_to_list(E)++" "++"RPC failed"} end, FailedRPC)}.
-spec get_config_diff(state()) -> {ConfigChanges,
LocalConfigChanges,
LocalHostsChanges} when
ConfigChanges :: compare_result(),
LocalConfigChanges :: compare_result(),
LocalHostsChanges :: compare_result().
get_config_diff(State) ->
{NewConfig, NewLocal, NewHostsLocal} = categorize_options(State#state.opts),
Config = get_global_config(),
Local = get_local_config(),
HostsLocal = get_host_local_config(),
CC = compare_terms(Config, NewConfig, 2, 3),
LC = compare_terms(Local, NewLocal, 2, 3),
LHC = compare_terms(group_host_changes(HostsLocal), group_host_changes(NewHostsLocal), 1, 2),
{CC, LC, LHC}.
-spec apply_changes_remote(file:name(), term(), binary(), binary()) ->
{ok, node()}| {error,node(),string()}.
apply_changes_remote(NewConfigFilePath, ConfigDiff,
DesiredConfigVersion, DesiredFileVersion) ->
?WARNING_MSG("remote config reload scheduled", []),
?DEBUG("~ndesired config version: ~p"
"~ndesired file version: ~p",
[DesiredConfigVersion, DesiredFileVersion]),
Node = node(),
{CC, LC, LHC} = ConfigDiff,
State0 = parse_file(NewConfigFilePath),
case compute_config_file_version(State0) of
DesiredFileVersion ->
State1 = State0#state{override_global = false,
override_local = true,
override_acls = false},
case catch apply_changes(CC, LC, LHC, State1,
DesiredConfigVersion) of
{ok, Node} = R ->
?WARNING_MSG("remote config reload succeeded", []),
R;
UnknownResult ->
?WARNING_MSG("remote config reload failed! "
"can't apply desired config", []),
{error, Node,
lists:flatten(io_lib:format("~p", [UnknownResult]))}
end;
_ ->
?WARNING_MSG("remote config reload failed! "
"can't compute current config version", []),
{error, Node, io_lib:format("Mismatching config file", [])}
end.
-spec apply_changes(term(), term(), term(), state(), binary()) ->
{ok, node()} | {error, node(), string()}.
apply_changes(ConfigChanges, LocalConfigChanges, LocalHostsChanges,
State, DesiredConfigVersion) ->
ConfigVersion = compute_config_version(get_local_config(),
get_host_local_config()),
?DEBUG("config version: ~p", [ConfigVersion]),
case ConfigVersion of
DesiredConfigVersion ->
ok;
_ ->
exit("Outdated configuration on node; cannot apply new one")
end,
set_opts(State),
reload_config(ConfigChanges),
reload_local_config(LocalConfigChanges),
reload_local_hosts_config(LocalHostsChanges),
{ok, node()}.
reload_config(#compare_result{to_start = CAdd, to_stop = CDel,
to_reload = CChange}) ->
lists:foreach(fun handle_config_change/1, CChange),
lists:foreach(fun handle_config_add/1, CAdd),
lists:foreach(fun handle_config_del/1, CDel).
reload_local_config(#compare_result{to_start = LCAdd, to_stop = LCDel,
to_reload = LCChange}) ->
lists:foreach(fun handle_local_config_change/1, LCChange),
lists:foreach(fun handle_local_config_add/1, LCAdd),
lists:foreach(fun handle_local_config_del/1, LCDel).
reload_local_hosts_config(#compare_result{to_start = LCHAdd, to_stop = LCHDel,
to_reload = LCHChange}) ->
lists:foreach(fun handle_local_hosts_config_change/1, LCHChange),
lists:foreach(fun handle_local_hosts_config_add/1, LCHAdd),
lists:foreach(fun handle_local_hosts_config_del/1, LCHDel).
CONFIG
handle_config_add(#config{key = hosts, value = Hosts}) when is_list(Hosts) ->
lists:foreach(fun(Host) -> add_virtual_host(Host) end, Hosts).
handle_config_del(#config{key = hosts,value = Hosts}) ->
lists:foreach(fun(Host) -> remove_virtual_host(Host) end, Hosts).
handle_config_change({hosts, OldHosts, NewHosts})->
{ToDel, ToAdd} = check_hosts(NewHosts, OldHosts),
lists:foreach(fun remove_virtual_host/1, ToDel),
lists:foreach(fun add_virtual_host/1, ToAdd);
handle_config_change({language, _Old, _New}) ->
ok;
handle_config_change({_Key, _OldValue, _NewValue}) ->
ok.
handle_local_config_add(#local_config{key = riak_server}) ->
mongoose_riak:start();
handle_local_config_add(#local_config{key=Key} = El) ->
case Key of
true ->
ok;
false ->
?WARNING_MSG("local config add ~p option unhandled",[El])
end.
handle_local_config_del(#local_config{key = riak_server}) ->
mongoose_riak:stop();
handle_local_config_del(#local_config{key = node_start}) ->
ok;
handle_local_config_del(#local_config{key=Key} = El) ->
case can_be_ignored(Key) of
true ->
ok;
false ->
?WARNING_MSG("local config change: ~p unhandled",[El])
end.
handle_local_config_change({listen, Old, New}) ->
reload_listeners(compare_listeners(Old, New));
handle_local_config_change({riak_server, _Old, _New}) ->
mongoose_riak:stop(),
mongoose_riak:start(),
ok;
handle_local_config_change({Key, _Old, _New} = El) ->
case can_be_ignored(Key) of
true ->
ok;
false ->
?WARNING_MSG("local config change: ~p unhandled",[El])
end.
handle_local_hosts_config_add({{auth, Host}, _}) ->
ejabberd_auth:start(Host);
handle_local_hosts_config_add({{odbc, Host}, _}) ->
ejabberd_rdbms:start(Host);
handle_local_hosts_config_add({{ldap, _Host}, _}) ->
ignore ldap section
ok;
handle_local_hosts_config_add({{modules, Host}, Modules}) ->
lists:foreach(
fun({Module, Args}) ->
gen_mod:start_module(Host, Module, Args)
end, Modules);
handle_local_hosts_config_add({{Key,_Host}, _} = El) ->
case can_be_ignored(Key) of
true ->
ok;
false ->
?WARNING_MSG("local hosts config add option: ~p unhandled",[El])
end.
handle_local_hosts_config_del({{auth, Host}, Opts}) ->
case lists:keyfind(auth_method, 1, Opts) of
false ->
{auth_method, Val} ->
AuthModules = methods_to_auth_modules(Val),
lists:foreach(fun(M) ->
M:stop(Host)
end, AuthModules)
end;
handle_local_hosts_config_del({{odbc, Host}, _}) ->
ejabberd_rdbms:stop_odbc(Host);
handle_local_hosts_config_del({{ldap, _Host}, _I}) ->
ignore ldap section , only appli
ok;
handle_local_hosts_config_del({{modules, Host}, Modules}) ->
lists:foreach(
fun({Module, _Args}) ->
gen_mod:stop_module(Host, Module)
end, Modules);
handle_local_hosts_config_del({{Key,_}, _} =El) ->
case can_be_ignored(Key) of
true ->
ok;
false ->
?WARNING_MSG("local hosts config delete option: ~p unhandled",[El])
end.
handle_local_hosts_config_change({{odbc,Host}, Old, _}) ->
case lists:keyfind({odbc_server, Host},1 ,Old) of
false ->
ok;
#local_config{} ->
ejabberd_rdbms:stop_odbc(Host)
end,
ejabberd_rdbms:start(Host);
handle_local_hosts_config_change({{auth, Host}, OldVals, _}) ->
case lists:keyfind(auth_method, 1, OldVals) of
false ->
ejabberd_auth:stop(Host);
{auth_method, Val} ->
AuthModules = methods_to_auth_modules(Val),
lists:foreach(fun (M) ->
M:stop(Host)
end, AuthModules)
end,
ejabberd_auth:start(Host);
handle_local_hosts_config_change({{ldap, Host}, _OldConfig, NewConfig}) ->
ok = ejabberd_hooks:run_fold(host_config_update, Host, ok, [Host, ldap, NewConfig]);
handle_local_hosts_config_change({{modules,Host}, OldModules, NewModules}) ->
Res = compare_modules(OldModules, NewModules),
reload_modules(Host, Res);
handle_local_hosts_config_change({{Key,_Host},_Old,_New} = El) ->
case can_be_ignored(Key) of
true ->
ok;
false ->
?WARNING_MSG("local hosts config change option: ~p unhandled",[El])
end.
methods_to_auth_modules(L) when is_list(L) ->
[list_to_atom("ejabberd_auth_" ++ atom_to_list(M)) || M <- L];
methods_to_auth_modules(A) when is_atom(A) ->
methods_to_auth_modules([A]).
compute_config_version(LC, LCH) ->
L0 = lists:filter(mk_node_start_filter(), LC ++ LCH),
L1 = sort_config(L0),
crypto:hash(sha, term_to_binary(L1)).
compute_config_file_version(#state{opts = Opts, hosts = Hosts}) ->
L = sort_config(Opts ++ Hosts),
crypto:hash(sha, term_to_binary(L)).
-spec check_hosts([ejabberd:server()], [ejabberd:server()]) -> {[ejabberd:server()],
[ejabberd:server()]}.
check_hosts(NewHosts, OldHosts) ->
Old = sets:from_list(OldHosts),
New = sets:from_list(NewHosts),
ListToAdd = sets:to_list(sets:subtract(New,Old)),
ListToDel = sets:to_list(sets:subtract(Old,New)),
{ListToDel, ListToAdd}.
-spec add_virtual_host(Host :: ejabberd:server()) -> any().
add_virtual_host(Host) ->
?DEBUG("Register host:~p",[Host]),
ejabberd_local:register_host(Host).
-spec can_be_ignored(Key :: atom()) -> boolean().
can_be_ignored(Key) when is_atom(Key) ->
L = [domain_certfile, s2s],
lists:member(Key,L).
-spec remove_virtual_host(ejabberd:server()) -> any().
remove_virtual_host(Host) ->
?DEBUG("Unregister host :~p", [Host]),
ejabberd_local:unregister_host(Host).
-spec reload_modules(Host :: ejabberd:server(),
ChangedModules :: compare_result()) -> 'ok'.
reload_modules(Host, #compare_result{to_start = Start, to_stop = Stop,
to_reload = Reload} = ChangedModules) ->
?DEBUG("reload modules: ~p", [lager:pr(ChangedModules, ?MODULE)]),
lists:foreach(fun ({M, _}) ->
gen_mod:stop_module(Host, M)
end, Stop),
lists:foreach(fun ({M, Args}) ->
gen_mod:start_module(Host, M, Args)
end, Start),
lists:foreach(fun({M, _, Args}) ->
gen_mod:reload_module(Host, M, Args)
end, Reload).
-spec reload_listeners(ChangedListeners :: compare_result()) -> 'ok'.
reload_listeners(#compare_result{to_start = Add, to_stop = Del,
to_reload = Change} = ChangedListeners) ->
?DEBUG("reload listeners: ~p", [lager:pr(ChangedListeners, ?MODULE)]),
lists:foreach(fun ({{PortIP, Module}, Opts}) ->
ejabberd_listener:delete_listener(PortIP, Module, Opts)
end, Del),
lists:foreach(fun ({{PortIP, Module}, Opts}) ->
ejabberd_listener:add_listener(PortIP, Module, Opts)
end, Add),
lists:foreach(fun ({{PortIP,Module}, OldOpts, NewOpts}) ->
ejabberd_listener:delete_listener(PortIP, Module, OldOpts),
ejabberd_listener:add_listener(PortIP, Module, NewOpts)
end, Change).
-spec compare_modules(term(), term()) -> compare_result().
compare_modules(OldMods, NewMods) ->
compare_terms(OldMods, NewMods, 1, 2).
-spec compare_listeners(term(), term()) -> compare_result().
compare_listeners(OldListeners, NewListeners) ->
compare_terms(map_listeners(OldListeners), map_listeners(NewListeners), 1, 2).
map_listeners(Listeners) ->
lists:map(fun ({PortIP,Module,Opts})->
{{PortIP,Module},Opts}
end, Listeners).
-spec group_host_changes([term()]) -> [{atom(), [term()]}].
group_host_changes(Changes) when is_list(Changes) ->
D = lists:foldl(fun (#local_config{key = {Key, Host}, value = Val}, Dict) ->
BKey = atom_to_binary(Key, utf8),
case get_key_group(BKey,Key) of
Key ->
dict:append({Key,Host}, Val, Dict);
NewKey ->
dict:append({NewKey,Host}, {Key, Val}, Dict)
end
end, dict:new(), Changes),
[{Group, lists:sort(lists:flatten(MaybeDeepList))}
|| {Group, MaybeDeepList} <- dict:to_list(D)].
-spec get_host_local_config() -> [{local_config, {term(), ejabberd:server()}, term()}].
get_host_local_config() ->
mnesia:dirty_match_object({local_config, {'_','_'}, '_'}).
-spec get_local_config() -> [{local_config, term(), term()}].
get_local_config() ->
Keys = lists:filter(fun is_not_host_specific/1,mnesia:dirty_all_keys(local_config)),
lists:flatten(lists:map(fun (Key) ->
mnesia:dirty_read(local_config, Key)
end,
Keys)).
-spec get_global_config() -> [{config, term(), term()}].
get_global_config() ->
mnesia:dirty_match_object(config, {config, '_', '_'}).
-spec is_not_host_specific(atom() | {atom(), ejabberd:server()}) -> boolean().
is_not_host_specific( Key ) when is_atom(Key) ->
true;
is_not_host_specific({Key, Host}) when is_atom(Key), is_binary(Host) ->
false.
-spec categorize_options([term()]) -> {GlobalConfig, LocalConfig, HostsConfig} when
GlobalConfig :: list(),
LocalConfig :: list(),
HostsConfig :: list().
categorize_options(Opts) ->
lists:foldl(fun ({config, _, _} = El, Acc) ->
as_global(El, Acc);
({local_config, {Key, Host}, _} = El, Acc)
when is_atom(Key), is_binary(Host) ->
as_hosts(El, Acc);
({local_config, _, _} = El, Acc) ->
as_local(El, Acc);
({acl, _, _}, R) ->
R;
(R, R2) ->
?ERROR_MSG("not matched ~p", [R]),
R2
end, {[], [], []}, Opts).
as_global(El, {Config, Local, HostLocal}) -> {[El | Config], Local, HostLocal}.
as_local(El, {Config, Local, HostLocal}) -> {Config, [El | Local], HostLocal}.
as_hosts(El, {Config, Local, HostLocal}) -> {Config, Local, [El | HostLocal]}.
-spec get_key_group(binary(), atom()) -> atom().
get_key_group(<<"ldap_", _/binary>>, _) ->
ldap;
get_key_group(<<"odbc_", _/binary>>, _) ->
odbc;
get_key_group(<<"pgsql_", _/binary>>, _) ->
odbc;
get_key_group(<<"auth_", _/binary>>, _) ->
auth;
get_key_group(<<"ext_auth_", _/binary>>, _) ->
auth;
get_key_group(<<"s2s_",_/binary>>, _) ->
s2s;
get_key_group(_, Key) when is_atom(Key)->
Key.
-spec compare_terms(OldTerms :: [tuple()],
NewTerms :: [tuple()],
KeyPos :: non_neg_integer(),
ValuePos :: non_neg_integer()) -> compare_result().
compare_terms(OldTerms, NewTerms, KeyPos, ValuePos)
when is_integer(KeyPos), is_integer(ValuePos) ->
{ToStop, ToReload} = lists:foldl(pa:bind(fun find_modules_to_change/5,
KeyPos, NewTerms, ValuePos),
{[], []}, OldTerms),
ToStart = lists:foldl(pa:bind(fun find_modules_to_start/4,
KeyPos, OldTerms), [], NewTerms),
#compare_result{to_start = ToStart,
to_stop = ToStop,
to_reload = ToReload}.
find_modules_to_start(KeyPos, OldTerms, Element, ToStart) ->
case lists:keyfind(element(KeyPos, Element), KeyPos, OldTerms) of
false -> [ Element | ToStart ];
_ -> ToStart
end.
find_modules_to_change(KeyPos, NewTerms, ValuePos,
Element, {ToStop, ToReload}) ->
case lists:keyfind(element(KeyPos, Element), KeyPos, NewTerms) of
false ->
{ [Element | ToStop], ToReload };
NewElement ->
OldVal = element(ValuePos, Element),
NewVal = element(ValuePos, NewElement),
case OldVal == NewVal of
true ->
{ToStop, ToReload};
false ->
{ToStop,
[ {element(KeyPos, Element), OldVal, NewVal} | ToReload ]}
end
end.
mk_node_start_filter() ->
fun(#local_config{key = node_start}) ->
false;
(_) ->
true
end.
sort_config(Config) when is_list(Config) ->
L = lists:map(fun(ConfigItem) when is_list(ConfigItem) ->
sort_config(ConfigItem);
(ConfigItem) when is_tuple(ConfigItem) ->
sort_config(tuple_to_list(ConfigItem));
(ConfigItem) ->
ConfigItem
end, Config),
lists:sort(L).
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.