_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
c62db1bf6cbed2eb7f8374eb35797f388b4d3338304c2e24dba87d30f093741f
SFML-haskell/SFML
SoundRecorder.hs
module SFML.Audio.SoundRecorder ( module SFML.Utils , SoundRecorderStartCallback , SoundRecorderProcessCallback , SoundRecorderStopCallback , createSoundRecorder , destroy , startRecording , stopRecording , getSampleRate , isSoundRecorderAvailable , setProcessingInterval , getAvailableSoundRecordingDevices , getDefaultSoundRecordingDevice , setSoundRecordingDevice , getSoundRecordingDevice ) where import SFML.Audio.SFSampled import SFML.Audio.SFSoundRecorder import SFML.Audio.Types import SFML.SFException import SFML.SFResource import SFML.System.Time import SFML.Utils import Control.Applicative ((<$>), (<*>)) import Control.Monad ((>=>), forM) import Data.Word (Word16) import Foreign.C.String import Foreign.C.Types import Foreign.Marshal.Alloc (alloca) import Foreign.Marshal.Array (advancePtr) import Foreign.Storable import Foreign.Ptr checkNull :: SoundRecorder -> Maybe SoundRecorder checkNull sr@(SoundRecorder ptr) = if ptr == nullPtr then Nothing else Just sr -- | Type of the callback used when starting a capture. type SoundRecorderStartCallback a = Ptr a -> IO CInt -- | Type of the callback used to process audio data. type SoundRecorderProcessCallback a = Ptr Word16 -> CUInt -> Ptr a -> IO Bool -- | Type of the callback used when stopping a capture. type SoundRecorderStopCallback a = Ptr a -> IO () -- typedef sfBool (*sfSoundRecorderStartCallback)(void*); -- typedef sfBool (*sfSoundRecorderProcessCallback)(const sfInt16*, size_t, void*); -- typedef void (*sfSoundRecorderStopCallback)(void*); -- | Construct a new sound recorder from callback functions. createSoundRecorder :: Ptr (SoundRecorderStartCallback a) -- ^ (onStart) Callback function which will be called when a new capture starts (can be NULL) -> Ptr (SoundRecorderProcessCallback a) -- ^ (onProcess) Callback function which will be called each time there's audio data to process -> Ptr (SoundRecorderStopCallback a) -- ^ (onStop) Callback function which will be called when the current capture stops (can be NULL) -> Ptr a -- ^ Data to pass to the callback function (can be NULL) ^ A new ' SoundRecorder ' object ( ' Nothing ' if failed ) createSoundRecorder c1 c2 c3 d = let err = SFException $ "Failed creating sound recorder: onStart = " ++ show c1 ++ " onProcess = " ++ show c2 ++ " onStop = " ++ show c3 ++ " userData = " ++ show d in sfSoundRecorder_create c1 c2 c3 d >>= return . tagErr err . checkNull foreign import ccall unsafe "sfSoundRecorder_create" sfSoundRecorder_create :: Ptr (SoundRecorderStartCallback a) -> Ptr (SoundRecorderProcessCallback a) -> Ptr (SoundRecorderStopCallback a) -> Ptr a -> IO SoundRecorder -- CSFML_AUDIO_API sfSoundRecorder* sfSoundRecorder_create(sfSoundRecorderStartCallback onStart, sfSoundRecorderProcessCallback onProcess, sfSoundRecorderStopCallback onStop, void* userData); instance SFResource SoundRecorder where # INLINABLE destroy # destroy = sfSoundRecorder_destroy foreign import ccall unsafe "sfSoundRecorder_destroy" sfSoundRecorder_destroy :: SoundRecorder -> IO () CSFML_AUDIO_API void sfSoundRecorder_destroy(sfSoundRecorder * ) ; instance SFSoundRecorder SoundRecorder where # INLINABLE startRecording # startRecording rec rate = ((/=0) . fromIntegral) <$> sfSoundRecorder_start rec (fromIntegral rate) # INLINABLE stopRecording # stopRecording = sfSoundRecorder_stop foreign import ccall unsafe "sfSoundRecorder_start" sfSoundRecorder_start :: SoundRecorder -> CUInt -> IO CInt CSFML_AUDIO_API void sfSoundRecorder_start(sfSoundRecorder * , unsigned int sampleRate ) ; foreign import ccall unsafe "sfSoundRecorder_stop" sfSoundRecorder_stop :: SoundRecorder -> IO () CSFML_AUDIO_API void sfSoundRecorder_stop(sfSoundRecorder * ) ; instance SFSampled SoundRecorder where # INLINABLE getSampleRate # getSampleRate = sfSoundRecorder_getSampleRate >=> return . fromIntegral foreign import ccall unsafe "sfSoundRecorder_getSampleRate" sfSoundRecorder_getSampleRate :: SoundRecorder -> IO CUInt CSFML_AUDIO_API unsigned int sfSoundRecorder_getSampleRate(const sfSoundRecorder * ) ; -- | Check if the system supports audio capture. -- -- This function should always be called before using -- the audio capture features. If it returns false, then any attempt to use ' SoundRecorder ' will fail . isSoundRecorderAvailable :: IO Bool isSoundRecorderAvailable = fmap (toEnum . fromIntegral) sfSoundRecorder_isAvailable foreign import ccall unsafe "sfSoundRecorder_isAvailable" sfSoundRecorder_isAvailable :: IO CInt -- CSFML_AUDIO_API sfBool sfSoundRecorder_isAvailable(void); -- | Set the processing interval. -- -- The processing interval controls the period -- between calls to the onProcessSamples function. You may -- want to use a small interval if you want to process the -- recorded data in real time, for example. -- -- Note: this is only a hint, the actual period may vary. -- So don't rely on this parameter to implement precise timing. -- The default processing interval is 100 ms . setProcessingInterval :: SoundRecorder -> Time -- ^ Processing interval -> IO () setProcessingInterval = sfSoundRecorder_setProcessingInterval foreign import ccall unsafe "sfSoundRecorder_setProcessingInterval" sfSoundRecorder_setProcessingInterval :: SoundRecorder -> Time -> IO () CSFML_AUDIO_API void sfSoundRecorder_setProcessingInterval(sfSoundRecorder * soundRecorder , sfTime interval ) ; -- | Get a list of the names of all availabe audio capture devices. -- -- This function returns an array of strings (null terminated), -- containing the names of all availabe audio capture devices. -- If no devices are available then 'Nothing' is returned. getAvailableSoundRecordingDevices :: IO [String] getAvailableSoundRecordingDevices = alloca $ \pCount -> do pNames <- sfSoundRecorder_getAvailableDevices pCount count <- fromIntegral <$> peek pCount :: IO Int forM [1..count] $ peekCString . advancePtr (castPtr pNames) foreign import ccall unsafe "sfSoundRecorder_getAvailableDevices" sfSoundRecorder_getAvailableDevices :: Ptr CSize -> IO (Ptr CString) CSFML_AUDIO_API const char * * * count ) ; -- | Get the name of the default audio capture device. -- -- This function returns the name of the default audio -- capture device. If none is available, NULL is returned. getDefaultSoundRecordingDevice :: IO String getDefaultSoundRecordingDevice = sfSoundRecorder_getDefaultDevice >>= peekCString foreign import ccall unsafe "sfSoundRecorder_getDefaultDevice" sfSoundRecorder_getDefaultDevice :: IO CString --CSFML_AUDIO_API const char* sfSoundRecorder_getDefaultDevice(); -- | Set the audio capture device. -- -- This function sets the audio capture device to the device -- with the given name. It can be called on the fly (i.e: -- while recording). If you do so while recording and -- opening the device fails, it stops the recording. -- -- Return 'True if it was able to set the requested device, 'False' otherwise. setSoundRecordingDevice :: SoundRecorder -> String -- ^ The name of the audio capture device -> IO Bool setSoundRecordingDevice rec name = withCString name $ \cname -> ((/=0) . fromIntegral) <$> sfSoundRecorder_setDevice rec cname foreign import ccall unsafe "sfSoundRecorder_setDevice" sfSoundRecorder_setDevice :: SoundRecorder -> CString -> IO CInt CSFML_AUDIO_API sfBool sfSoundRecorder_setDevice(sfSoundRecorder * , const char * name ) ; -- | Get the name of the current audio capture device. getSoundRecordingDevice :: SoundRecorder -> IO String getSoundRecordingDevice rec = sfSoundRecorder_getDevice rec >>= peekCString foreign import ccall unsafe "sfSoundRecorder_getDevice" sfSoundRecorder_getDevice :: SoundRecorder -> IO CString CSFML_AUDIO_API const char * sfSoundRecorder_getDevice(sfSoundRecorder * ) ;
null
https://raw.githubusercontent.com/SFML-haskell/SFML/1d1ceee6bc782f4f194853fbd0cc4acb33b86d41/src/SFML/Audio/SoundRecorder.hs
haskell
| Type of the callback used when starting a capture. | Type of the callback used to process audio data. | Type of the callback used when stopping a capture. typedef sfBool (*sfSoundRecorderStartCallback)(void*); typedef sfBool (*sfSoundRecorderProcessCallback)(const sfInt16*, size_t, void*); typedef void (*sfSoundRecorderStopCallback)(void*); | Construct a new sound recorder from callback functions. ^ (onStart) Callback function which will be called when a new capture starts (can be NULL) ^ (onProcess) Callback function which will be called each time there's audio data to process ^ (onStop) Callback function which will be called when the current capture stops (can be NULL) ^ Data to pass to the callback function (can be NULL) CSFML_AUDIO_API sfSoundRecorder* sfSoundRecorder_create(sfSoundRecorderStartCallback onStart, sfSoundRecorderProcessCallback onProcess, sfSoundRecorderStopCallback onStop, void* userData); | Check if the system supports audio capture. This function should always be called before using the audio capture features. If it returns false, then CSFML_AUDIO_API sfBool sfSoundRecorder_isAvailable(void); | Set the processing interval. The processing interval controls the period between calls to the onProcessSamples function. You may want to use a small interval if you want to process the recorded data in real time, for example. Note: this is only a hint, the actual period may vary. So don't rely on this parameter to implement precise timing. ^ Processing interval | Get a list of the names of all availabe audio capture devices. This function returns an array of strings (null terminated), containing the names of all availabe audio capture devices. If no devices are available then 'Nothing' is returned. | Get the name of the default audio capture device. This function returns the name of the default audio capture device. If none is available, NULL is returned. CSFML_AUDIO_API const char* sfSoundRecorder_getDefaultDevice(); | Set the audio capture device. This function sets the audio capture device to the device with the given name. It can be called on the fly (i.e: while recording). If you do so while recording and opening the device fails, it stops the recording. Return 'True if it was able to set the requested device, 'False' otherwise. ^ The name of the audio capture device | Get the name of the current audio capture device.
module SFML.Audio.SoundRecorder ( module SFML.Utils , SoundRecorderStartCallback , SoundRecorderProcessCallback , SoundRecorderStopCallback , createSoundRecorder , destroy , startRecording , stopRecording , getSampleRate , isSoundRecorderAvailable , setProcessingInterval , getAvailableSoundRecordingDevices , getDefaultSoundRecordingDevice , setSoundRecordingDevice , getSoundRecordingDevice ) where import SFML.Audio.SFSampled import SFML.Audio.SFSoundRecorder import SFML.Audio.Types import SFML.SFException import SFML.SFResource import SFML.System.Time import SFML.Utils import Control.Applicative ((<$>), (<*>)) import Control.Monad ((>=>), forM) import Data.Word (Word16) import Foreign.C.String import Foreign.C.Types import Foreign.Marshal.Alloc (alloca) import Foreign.Marshal.Array (advancePtr) import Foreign.Storable import Foreign.Ptr checkNull :: SoundRecorder -> Maybe SoundRecorder checkNull sr@(SoundRecorder ptr) = if ptr == nullPtr then Nothing else Just sr type SoundRecorderStartCallback a = Ptr a -> IO CInt type SoundRecorderProcessCallback a = Ptr Word16 -> CUInt -> Ptr a -> IO Bool type SoundRecorderStopCallback a = Ptr a -> IO () createSoundRecorder ^ A new ' SoundRecorder ' object ( ' Nothing ' if failed ) createSoundRecorder c1 c2 c3 d = let err = SFException $ "Failed creating sound recorder: onStart = " ++ show c1 ++ " onProcess = " ++ show c2 ++ " onStop = " ++ show c3 ++ " userData = " ++ show d in sfSoundRecorder_create c1 c2 c3 d >>= return . tagErr err . checkNull foreign import ccall unsafe "sfSoundRecorder_create" sfSoundRecorder_create :: Ptr (SoundRecorderStartCallback a) -> Ptr (SoundRecorderProcessCallback a) -> Ptr (SoundRecorderStopCallback a) -> Ptr a -> IO SoundRecorder instance SFResource SoundRecorder where # INLINABLE destroy # destroy = sfSoundRecorder_destroy foreign import ccall unsafe "sfSoundRecorder_destroy" sfSoundRecorder_destroy :: SoundRecorder -> IO () CSFML_AUDIO_API void sfSoundRecorder_destroy(sfSoundRecorder * ) ; instance SFSoundRecorder SoundRecorder where # INLINABLE startRecording # startRecording rec rate = ((/=0) . fromIntegral) <$> sfSoundRecorder_start rec (fromIntegral rate) # INLINABLE stopRecording # stopRecording = sfSoundRecorder_stop foreign import ccall unsafe "sfSoundRecorder_start" sfSoundRecorder_start :: SoundRecorder -> CUInt -> IO CInt CSFML_AUDIO_API void sfSoundRecorder_start(sfSoundRecorder * , unsigned int sampleRate ) ; foreign import ccall unsafe "sfSoundRecorder_stop" sfSoundRecorder_stop :: SoundRecorder -> IO () CSFML_AUDIO_API void sfSoundRecorder_stop(sfSoundRecorder * ) ; instance SFSampled SoundRecorder where # INLINABLE getSampleRate # getSampleRate = sfSoundRecorder_getSampleRate >=> return . fromIntegral foreign import ccall unsafe "sfSoundRecorder_getSampleRate" sfSoundRecorder_getSampleRate :: SoundRecorder -> IO CUInt CSFML_AUDIO_API unsigned int sfSoundRecorder_getSampleRate(const sfSoundRecorder * ) ; any attempt to use ' SoundRecorder ' will fail . isSoundRecorderAvailable :: IO Bool isSoundRecorderAvailable = fmap (toEnum . fromIntegral) sfSoundRecorder_isAvailable foreign import ccall unsafe "sfSoundRecorder_isAvailable" sfSoundRecorder_isAvailable :: IO CInt The default processing interval is 100 ms . setProcessingInterval :: SoundRecorder -> IO () setProcessingInterval = sfSoundRecorder_setProcessingInterval foreign import ccall unsafe "sfSoundRecorder_setProcessingInterval" sfSoundRecorder_setProcessingInterval :: SoundRecorder -> Time -> IO () CSFML_AUDIO_API void sfSoundRecorder_setProcessingInterval(sfSoundRecorder * soundRecorder , sfTime interval ) ; getAvailableSoundRecordingDevices :: IO [String] getAvailableSoundRecordingDevices = alloca $ \pCount -> do pNames <- sfSoundRecorder_getAvailableDevices pCount count <- fromIntegral <$> peek pCount :: IO Int forM [1..count] $ peekCString . advancePtr (castPtr pNames) foreign import ccall unsafe "sfSoundRecorder_getAvailableDevices" sfSoundRecorder_getAvailableDevices :: Ptr CSize -> IO (Ptr CString) CSFML_AUDIO_API const char * * * count ) ; getDefaultSoundRecordingDevice :: IO String getDefaultSoundRecordingDevice = sfSoundRecorder_getDefaultDevice >>= peekCString foreign import ccall unsafe "sfSoundRecorder_getDefaultDevice" sfSoundRecorder_getDefaultDevice :: IO CString setSoundRecordingDevice :: SoundRecorder -> IO Bool setSoundRecordingDevice rec name = withCString name $ \cname -> ((/=0) . fromIntegral) <$> sfSoundRecorder_setDevice rec cname foreign import ccall unsafe "sfSoundRecorder_setDevice" sfSoundRecorder_setDevice :: SoundRecorder -> CString -> IO CInt CSFML_AUDIO_API sfBool sfSoundRecorder_setDevice(sfSoundRecorder * , const char * name ) ; getSoundRecordingDevice :: SoundRecorder -> IO String getSoundRecordingDevice rec = sfSoundRecorder_getDevice rec >>= peekCString foreign import ccall unsafe "sfSoundRecorder_getDevice" sfSoundRecorder_getDevice :: SoundRecorder -> IO CString CSFML_AUDIO_API const char * sfSoundRecorder_getDevice(sfSoundRecorder * ) ;
af4553de8c6517ed75e1fb418240ee33bddaef6822ca19a9c89e7d0805acf6e0
Shinmera/3d-matrices
staple.ext.lisp
(asdf:load-system :staple-markdown) (defmethod staple:definition-wanted-p ((_ definitions:setf-expander) page) NIL) #+sbcl (defmethod staple:definition-wanted-p ((_ definitions:source-transform) page) NIL)
null
https://raw.githubusercontent.com/Shinmera/3d-matrices/562540726d3f42adcd4e8c9debaa162189e8f654/staple.ext.lisp
lisp
(asdf:load-system :staple-markdown) (defmethod staple:definition-wanted-p ((_ definitions:setf-expander) page) NIL) #+sbcl (defmethod staple:definition-wanted-p ((_ definitions:source-transform) page) NIL)
ad22c8d603f0c68c6da7bca8044efc0de56cfc744bed96f2fad03f7008472c07
uw-unsat/serval
info.rkt
#lang info (define collection 'multi) (define deps '("rosette" "base" "rackunit-lib" "scribble-lib" "racket-doc")) (define pkg-desc "Serval verification framework") (define version "0.0.1a")
null
https://raw.githubusercontent.com/uw-unsat/serval/be11ecccf03f81b8bd0557acf8385a6a5d4f51ed/info.rkt
racket
#lang info (define collection 'multi) (define deps '("rosette" "base" "rackunit-lib" "scribble-lib" "racket-doc")) (define pkg-desc "Serval verification framework") (define version "0.0.1a")
3afb9afb321986b5371a3274ddd9bd812bb7e5418d9ba227dc8d3fa7097737a9
tschady/advent-of-code
d10.clj
(ns aoc.2018.d10 (:require [aoc.elfscript :as elfscript] [aoc.file-util :as f] [aoc.grid :as grid] [aoc.string-util :as s])) (def input (f/read-lines "2018/d10.txt")) (defn make-pixel [s] (let [[x y dx dy] (s/ints s)] {:x x :y y :dx dx :dy dy})) (defn tick-pixel ([pixel] (tick-pixel 1 pixel)) ([n {:keys [dx dy] :as pixel}] (-> pixel (update-in [:x] + (* n dx)) (update-in [:y] + (* n dy))))) (defn height "Returns the y-axis length spanned by pixels" [pixels] (abs (- (reduce max (map :y pixels)) (reduce min (map :y pixels))))) (defn steps-to-coalesce "Return the number of time ticks required to get bounding box to a reasonable font-height." [pixels] (let [h (height pixels) ddydt (- h (height (map tick-pixel pixels)))] (int (/ h ddydt)))) ;; Find out the y-acceleration of process, use that to determine time ;; required to get readout of correct size (defn part-1 [input] (let [pixels (map make-pixel input) t (steps-to-coalesce pixels)] (->> pixels (map (partial tick-pixel t)) (map (fn [{:keys [x y]}] [[x y] \#])) (into {}) (grid/print-grid-to-array \.) (elfscript/ocr)))) (defn part-2 [input] (steps-to-coalesce (map make-pixel input)))
null
https://raw.githubusercontent.com/tschady/advent-of-code/4d119897230821f545dca5b4cba1f8024372639d/src/aoc/2018/d10.clj
clojure
Find out the y-acceleration of process, use that to determine time required to get readout of correct size
(ns aoc.2018.d10 (:require [aoc.elfscript :as elfscript] [aoc.file-util :as f] [aoc.grid :as grid] [aoc.string-util :as s])) (def input (f/read-lines "2018/d10.txt")) (defn make-pixel [s] (let [[x y dx dy] (s/ints s)] {:x x :y y :dx dx :dy dy})) (defn tick-pixel ([pixel] (tick-pixel 1 pixel)) ([n {:keys [dx dy] :as pixel}] (-> pixel (update-in [:x] + (* n dx)) (update-in [:y] + (* n dy))))) (defn height "Returns the y-axis length spanned by pixels" [pixels] (abs (- (reduce max (map :y pixels)) (reduce min (map :y pixels))))) (defn steps-to-coalesce "Return the number of time ticks required to get bounding box to a reasonable font-height." [pixels] (let [h (height pixels) ddydt (- h (height (map tick-pixel pixels)))] (int (/ h ddydt)))) (defn part-1 [input] (let [pixels (map make-pixel input) t (steps-to-coalesce pixels)] (->> pixels (map (partial tick-pixel t)) (map (fn [{:keys [x y]}] [[x y] \#])) (into {}) (grid/print-grid-to-array \.) (elfscript/ocr)))) (defn part-2 [input] (steps-to-coalesce (map make-pixel input)))
2664dadec4b90baf2a7cb15a8685dc438925a0c0e5812ea6c6aeb2f255a7ba15
pandeiro/jaki
req.cljs
(ns jaki.req (:use [jaki.util :only [clj->js]]) (:require [goog.net.XhrIo :as xhr] [goog.json :as json]) (:refer-clojure :exclude [get])) For some odd reason , goog.json.parse uses eval , which is not allowed in Chrome extensions and is generally evil . So if native JSON support exists ( it 's 2012 ) , ;; use that. (defn- parse-json [s] (if js/JSON (.parse js/JSON s) (json/parse s))) (defn request "Carries out an HTTP request, converting any payload from Clojure map to JSON string, and passes JSON string response to callback as a Clojure map." ([url] (request url nil "GET" nil nil)) ([url callback] (request url callback "GET" nil nil)) ([url callback method] (request url callback method nil nil)) ([url callback method payload] (request url callback method payload nil)) ([url callback method payload headers] (let [do-callback (when (fn? callback) (fn [e] (callback (js->clj (parse-json (.getResponseText (.-target e))) :keywordize-keys true)))) payload (if (or (string? payload) (number? payload) (nil? payload)) payload (json/serialize (if (or (map? payload) (coll? payload)) (clj->js payload) payload))) headers (if (map? headers) (clj->js headers) headers)] (xhr/send url do-callback method payload headers)))) (defn get [url callback] (request url callback)) (defn post ([url] (post url nil nil)) ([url callback] (post url callback nil)) ([url callback payload] (request url callback "POST" payload {:Content-Type "application/json"}))) (defn put ([url] (put url nil nil)) ([url callback] (put url callback nil)) ([url callback payload] (request url callback "PUT" payload {:Content-Type "application/json"}))) (defn delete ([url] (delete url nil)) ([url callback] (request url callback "DELETE")))
null
https://raw.githubusercontent.com/pandeiro/jaki/7eb88b31a4d70af4553bda85a456c1329da88c5f/src/jaki/req.cljs
clojure
use that.
(ns jaki.req (:use [jaki.util :only [clj->js]]) (:require [goog.net.XhrIo :as xhr] [goog.json :as json]) (:refer-clojure :exclude [get])) For some odd reason , goog.json.parse uses eval , which is not allowed in Chrome extensions and is generally evil . So if native JSON support exists ( it 's 2012 ) , (defn- parse-json [s] (if js/JSON (.parse js/JSON s) (json/parse s))) (defn request "Carries out an HTTP request, converting any payload from Clojure map to JSON string, and passes JSON string response to callback as a Clojure map." ([url] (request url nil "GET" nil nil)) ([url callback] (request url callback "GET" nil nil)) ([url callback method] (request url callback method nil nil)) ([url callback method payload] (request url callback method payload nil)) ([url callback method payload headers] (let [do-callback (when (fn? callback) (fn [e] (callback (js->clj (parse-json (.getResponseText (.-target e))) :keywordize-keys true)))) payload (if (or (string? payload) (number? payload) (nil? payload)) payload (json/serialize (if (or (map? payload) (coll? payload)) (clj->js payload) payload))) headers (if (map? headers) (clj->js headers) headers)] (xhr/send url do-callback method payload headers)))) (defn get [url callback] (request url callback)) (defn post ([url] (post url nil nil)) ([url callback] (post url callback nil)) ([url callback payload] (request url callback "POST" payload {:Content-Type "application/json"}))) (defn put ([url] (put url nil nil)) ([url callback] (put url callback nil)) ([url callback payload] (request url callback "PUT" payload {:Content-Type "application/json"}))) (defn delete ([url] (delete url nil)) ([url callback] (request url callback "DELETE")))
13f44017ca8c8dd8c1d51900eb440740c44a44dd2b09c7b2ca41dc0284c7d77d
cburgmer/buildviz
csv_test.clj
(ns buildviz.util.csv-test (:require [buildviz.util.csv :refer :all] [clj-time [coerce :as tc] [core :as t]] [clojure.test :refer :all])) (def a-datetime (t/from-time-zone (t/date-time 1986 10 14 4 3 27 456) (t/default-time-zone))) (deftest CSV (testing "export" (is (= "col 1,col 2" (export ["col 1", "col 2"]))) (is (= "col 1" (export ["col 1"]))) (is (= ",col 2" (export [nil, "col 2"]))) (is (= "" (export []))) (is (= "\"col,1\"" (export ["col,1"]))) (is (= "\"col\"\"1\"" (export ["col\"1"]))) (is (= "\"col,\"\"1\"" (export ["col,\"1"]))) (is (= "col 1,\"col,2\",col3" (export ["col 1", "col,2", "col3"])))) (testing "format-timestamp" (is (= "1986-10-14 04:03:27" (format-timestamp (tc/to-long a-datetime))))) (testing "format-duration" (is (= "1.00000000" (format-duration (* 24 60 60 1000)))) (is (= 1 (Math/round (* 24. 60 60 1000 (Float/parseFloat (format-duration 1))))))))
null
https://raw.githubusercontent.com/cburgmer/buildviz/396f4f854e306acf08ac04b7a084dea9b2a606c6/test/buildviz/util/csv_test.clj
clojure
(ns buildviz.util.csv-test (:require [buildviz.util.csv :refer :all] [clj-time [coerce :as tc] [core :as t]] [clojure.test :refer :all])) (def a-datetime (t/from-time-zone (t/date-time 1986 10 14 4 3 27 456) (t/default-time-zone))) (deftest CSV (testing "export" (is (= "col 1,col 2" (export ["col 1", "col 2"]))) (is (= "col 1" (export ["col 1"]))) (is (= ",col 2" (export [nil, "col 2"]))) (is (= "" (export []))) (is (= "\"col,1\"" (export ["col,1"]))) (is (= "\"col\"\"1\"" (export ["col\"1"]))) (is (= "\"col,\"\"1\"" (export ["col,\"1"]))) (is (= "col 1,\"col,2\",col3" (export ["col 1", "col,2", "col3"])))) (testing "format-timestamp" (is (= "1986-10-14 04:03:27" (format-timestamp (tc/to-long a-datetime))))) (testing "format-duration" (is (= "1.00000000" (format-duration (* 24 60 60 1000)))) (is (= 1 (Math/round (* 24. 60 60 1000 (Float/parseFloat (format-duration 1))))))))
3b301d27370e5dc208c697e13e4078659bc8af668f7ec11d0bb74b4feb16a510
josefs/Gradualizer
bc_pass.erl
-module(bc_pass). -compile([export_all, nowarn_export_all]). bc1() -> << <<X:4, Y:4>> || X <- [$a, $b], <<Y:4>> <= <<"xy">> >>. -spec bc2(binary()) -> binary(). bc2(Bin) -> << <<X:4, Y:4>> || X <- binary_to_list(<<"ab">>), <<Y:4>> <= Bin >>. -spec bc3(any()) -> binary(). bc3(Bin) -> << <<X:4, Y:4>> || X <- [$a, $b], <<Y:4>> <= Bin >>. bc4() -> << (list_to_binary(X)) || X <- ["apa", "bepa"], is_list(X) >>. bc5() -> << (ipv4_to_binary(IP)) || IP <- [{192, 168, 0, 1}, {127, 0, 0, 1}] >>. bc6() -> << (unusually_sized_bitstring(X)) || <<X>> <= <<"abc">> >>. bc7(X) -> << (union_of_bitstrings(P)) || P <- [is_integer(X), is_float(X)] >>. -spec bc8(number()) -> <<_:42, _:_*16>>. bc8(X) -> << (union_of_bitstrings(P)) || P <- [is_integer(X), is_float(X)] >>. bc9(N) -> << <<B/bitstring>> || B <- union_of_lists(N) >>. bc10(Str) -> << <<B:2/bytes>> || <<B:4/bytes>> <= list_to_binary(Str) >>. -spec bc11(integer()) -> bitstring(). bc11(N) -> << <<B/bitstring>> || B <- union_of_lists(N), N > 0 >>. %% Returns fixed size binary -spec ipv4_to_binary({byte(), byte(), byte(), byte()}) -> <<_:32>>. ipv4_to_binary({A, B, C, D}) -> <<A, B, C, D>>. %% Returns a bitstring of a fixed size plus a multiple of some size -spec unusually_sized_bitstring(integer()) -> <<_:17, _:_*3>>. unusually_sized_bitstring($a) -> <<1:17, 3:3>>; unusually_sized_bitstring($b) -> <<2:17, 3:6>>; unusually_sized_bitstring(N) -> <<3:17, N:9>>. %% Returns a union of bitstring types -spec union_of_bitstrings(boolean()) -> <<_:42>> | <<_:_*16>>. union_of_bitstrings(true) -> <<0:42>>; union_of_bitstrings(false) -> <<"xyz"/utf16-little>>. %% Returns a union of lists of some bitstring type -spec union_of_lists(integer()) -> [<<_:_*3>>] | [<<_:_*16>>]. union_of_lists(N) when N > 42 -> [<<>>, <<N/utf16>>]; union_of_lists(N) -> [<<42:3>>, <<N:9>>]. -spec integer_default(binary()) -> non_neg_integer(). integer_default(B) -> <<A>> = B, A. -spec integer_unsigned(binary()) -> non_neg_integer(). integer_unsigned(B) -> <<A/unsigned>> = B, A. -spec integer_signed(binary()) -> integer(). integer_signed(B) -> <<A/signed>> = B, A. -spec expr_vs_pat_default() -> non_neg_integer(). expr_vs_pat_default() -> <<A>> = <<-1>>, A. -spec expr_vs_pat_unsigned() -> non_neg_integer(). expr_vs_pat_unsigned() -> <<A/unsigned>> = <<-1>>, A. -spec expr_vs_pat_signed() -> integer(). expr_vs_pat_signed() -> <<A/signed>> = <<-1>>, A.
null
https://raw.githubusercontent.com/josefs/Gradualizer/00d907accacfc29a3241dc42c1cd6d00f7e3ca37/test/should_pass/bc_pass.erl
erlang
Returns fixed size binary Returns a bitstring of a fixed size plus a multiple of some size Returns a union of bitstring types Returns a union of lists of some bitstring type
-module(bc_pass). -compile([export_all, nowarn_export_all]). bc1() -> << <<X:4, Y:4>> || X <- [$a, $b], <<Y:4>> <= <<"xy">> >>. -spec bc2(binary()) -> binary(). bc2(Bin) -> << <<X:4, Y:4>> || X <- binary_to_list(<<"ab">>), <<Y:4>> <= Bin >>. -spec bc3(any()) -> binary(). bc3(Bin) -> << <<X:4, Y:4>> || X <- [$a, $b], <<Y:4>> <= Bin >>. bc4() -> << (list_to_binary(X)) || X <- ["apa", "bepa"], is_list(X) >>. bc5() -> << (ipv4_to_binary(IP)) || IP <- [{192, 168, 0, 1}, {127, 0, 0, 1}] >>. bc6() -> << (unusually_sized_bitstring(X)) || <<X>> <= <<"abc">> >>. bc7(X) -> << (union_of_bitstrings(P)) || P <- [is_integer(X), is_float(X)] >>. -spec bc8(number()) -> <<_:42, _:_*16>>. bc8(X) -> << (union_of_bitstrings(P)) || P <- [is_integer(X), is_float(X)] >>. bc9(N) -> << <<B/bitstring>> || B <- union_of_lists(N) >>. bc10(Str) -> << <<B:2/bytes>> || <<B:4/bytes>> <= list_to_binary(Str) >>. -spec bc11(integer()) -> bitstring(). bc11(N) -> << <<B/bitstring>> || B <- union_of_lists(N), N > 0 >>. -spec ipv4_to_binary({byte(), byte(), byte(), byte()}) -> <<_:32>>. ipv4_to_binary({A, B, C, D}) -> <<A, B, C, D>>. -spec unusually_sized_bitstring(integer()) -> <<_:17, _:_*3>>. unusually_sized_bitstring($a) -> <<1:17, 3:3>>; unusually_sized_bitstring($b) -> <<2:17, 3:6>>; unusually_sized_bitstring(N) -> <<3:17, N:9>>. -spec union_of_bitstrings(boolean()) -> <<_:42>> | <<_:_*16>>. union_of_bitstrings(true) -> <<0:42>>; union_of_bitstrings(false) -> <<"xyz"/utf16-little>>. -spec union_of_lists(integer()) -> [<<_:_*3>>] | [<<_:_*16>>]. union_of_lists(N) when N > 42 -> [<<>>, <<N/utf16>>]; union_of_lists(N) -> [<<42:3>>, <<N:9>>]. -spec integer_default(binary()) -> non_neg_integer(). integer_default(B) -> <<A>> = B, A. -spec integer_unsigned(binary()) -> non_neg_integer(). integer_unsigned(B) -> <<A/unsigned>> = B, A. -spec integer_signed(binary()) -> integer(). integer_signed(B) -> <<A/signed>> = B, A. -spec expr_vs_pat_default() -> non_neg_integer(). expr_vs_pat_default() -> <<A>> = <<-1>>, A. -spec expr_vs_pat_unsigned() -> non_neg_integer(). expr_vs_pat_unsigned() -> <<A/unsigned>> = <<-1>>, A. -spec expr_vs_pat_signed() -> integer(). expr_vs_pat_signed() -> <<A/signed>> = <<-1>>, A.
9f426aee5c3498e2c770cbdbb1b227b3329726e9f8b458601215dc71cf71d226
HaskellCNOrg/snap-web
ReplySplicesTest.hs
{-# LANGUAGE OverloadedStrings #-} module Views.ReplySplicesTest (tests) where import Data.Bson (ObjectId) import Data.Time import System.IO.Unsafe (unsafePerformIO) import Test.Framework (Test, testGroup) import Test.Framework.Providers.HUnit (testCase) import Test.HUnit (Assertion, (@?=)) import Models.Reply import Views.ReplySplices tests :: Test tests = testGroup "Test.Views.ReplySplices.splitReplies" [ testCase "just empty" $ (@?=) (splitReplies []) [] , testCase "reply without children" testReplyWithoutChildren , testCase "all children reply" testReplyAllChildren , testCase "reply with children" testReplyWithChildren ] -- | All replies which have no children replies -- testReplyWithoutChildren :: Assertion testReplyWithoutChildren = let rs = justReply in (@?=) (splitReplies rs) (g rs) where g = map (\ r -> (r, [])) -- | All children replies -- testReplyAllChildren :: Assertion testReplyAllChildren = let rs = justChildrenReply in (@?=) (splitReplies rs) [] -- | reply and its children. -- testReplyWithChildren :: Assertion testReplyWithChildren = let rs = justReplyWithChildren in (@?=) (splitReplies rs) [ (reply1, [childrenReply11, childrenReply12]) , (reply2, []) , (reply3, [childrenReply31]) ] --------------------------------------------------------- Test Datas justReply :: [Reply] justReply = [reply1, reply2, reply3] justChildrenReply :: [Reply] justChildrenReply = [childrenReply11, childrenReply12, childrenReply31] justReplyWithChildren :: [Reply] justReplyWithChildren = justReply ++ justChildrenReply reply1 :: Reply reply1 = defaultReply { _replyId = toObjId "12345678901"} reply2 :: Reply reply2 = defaultReply { _replyId = toObjId "12345678902"} reply3 :: Reply reply3 = defaultReply { _replyId = toObjId "12345678903"} childrenReply11 :: Reply childrenReply11 = defaultReply { _replyToReplyId = toObjId "12345678901"} childrenReply12 :: Reply childrenReply12 = defaultReply { _replyToReplyId = toObjId "12345678901"} childrenReply31 :: Reply childrenReply31 = defaultReply { _replyToReplyId = toObjId "12345678903"} defaultReply :: Reply defaultReply = Reply { _replyId = Nothing , _replyToTopicId = read "1234567890" , _replyToReplyId = Nothing , _replyContent = "Dumy comment" , _replyAuthor = read "1234567891" , _replyCreateAt = mockUTCTime } mockUTCTime :: UTCTime mockUTCTime = unsafePerformIO getCurrentTime toObjId :: String -> Maybe ObjectId toObjId = Just . read
null
https://raw.githubusercontent.com/HaskellCNOrg/snap-web/f104fd9b8fc5ae74fc7b8002f0eb3f182a61529e/tests/Views/ReplySplicesTest.hs
haskell
# LANGUAGE OverloadedStrings # | All replies which have no children replies | All children replies | reply and its children. -------------------------------------------------------
module Views.ReplySplicesTest (tests) where import Data.Bson (ObjectId) import Data.Time import System.IO.Unsafe (unsafePerformIO) import Test.Framework (Test, testGroup) import Test.Framework.Providers.HUnit (testCase) import Test.HUnit (Assertion, (@?=)) import Models.Reply import Views.ReplySplices tests :: Test tests = testGroup "Test.Views.ReplySplices.splitReplies" [ testCase "just empty" $ (@?=) (splitReplies []) [] , testCase "reply without children" testReplyWithoutChildren , testCase "all children reply" testReplyAllChildren , testCase "reply with children" testReplyWithChildren ] testReplyWithoutChildren :: Assertion testReplyWithoutChildren = let rs = justReply in (@?=) (splitReplies rs) (g rs) where g = map (\ r -> (r, [])) testReplyAllChildren :: Assertion testReplyAllChildren = let rs = justChildrenReply in (@?=) (splitReplies rs) [] testReplyWithChildren :: Assertion testReplyWithChildren = let rs = justReplyWithChildren in (@?=) (splitReplies rs) [ (reply1, [childrenReply11, childrenReply12]) , (reply2, []) , (reply3, [childrenReply31]) ] Test Datas justReply :: [Reply] justReply = [reply1, reply2, reply3] justChildrenReply :: [Reply] justChildrenReply = [childrenReply11, childrenReply12, childrenReply31] justReplyWithChildren :: [Reply] justReplyWithChildren = justReply ++ justChildrenReply reply1 :: Reply reply1 = defaultReply { _replyId = toObjId "12345678901"} reply2 :: Reply reply2 = defaultReply { _replyId = toObjId "12345678902"} reply3 :: Reply reply3 = defaultReply { _replyId = toObjId "12345678903"} childrenReply11 :: Reply childrenReply11 = defaultReply { _replyToReplyId = toObjId "12345678901"} childrenReply12 :: Reply childrenReply12 = defaultReply { _replyToReplyId = toObjId "12345678901"} childrenReply31 :: Reply childrenReply31 = defaultReply { _replyToReplyId = toObjId "12345678903"} defaultReply :: Reply defaultReply = Reply { _replyId = Nothing , _replyToTopicId = read "1234567890" , _replyToReplyId = Nothing , _replyContent = "Dumy comment" , _replyAuthor = read "1234567891" , _replyCreateAt = mockUTCTime } mockUTCTime :: UTCTime mockUTCTime = unsafePerformIO getCurrentTime toObjId :: String -> Maybe ObjectId toObjId = Just . read
431ae84def7395f03aeb8d4c1b13fc867c166d60109ea6d2b91ccdeb74cadb72
bittide/bittide-hardware
ClockControl.hs
SPDX - FileCopyrightText : 2022 Google LLC -- SPDX - License - Identifier : Apache-2.0 module Bittide.Instances.ClockControl where import Clash.Prelude import Bittide.ClockControl.Callisto import Bittide.Instances.Domains import Bittide.ClockControl config :: ClockControlConfig Basic200 12 config = $(lift (defClockConfig @Basic200)) callisto3 :: Clock Basic200 -> Reset Basic200 -> Enable Basic200 -> -- | Data counts from elastic buffers Vec 3 (Signal Basic200 (DataCount 12)) -> -- | Speed change requested from clock multiplier Signal Basic200 SpeedChange callisto3 clk rst ena dataCounts = callistoClockControl clk rst ena config availableLinkMask dataCounts where -- all links available availableLinkMask = pure $ complement 0
null
https://raw.githubusercontent.com/bittide/bittide-hardware/b44dac8ee0fb14b0c6a94fcbe830fdd8d140bec4/bittide-instances/src/Bittide/Instances/ClockControl.hs
haskell
| Data counts from elastic buffers | Speed change requested from clock multiplier all links available
SPDX - FileCopyrightText : 2022 Google LLC SPDX - License - Identifier : Apache-2.0 module Bittide.Instances.ClockControl where import Clash.Prelude import Bittide.ClockControl.Callisto import Bittide.Instances.Domains import Bittide.ClockControl config :: ClockControlConfig Basic200 12 config = $(lift (defClockConfig @Basic200)) callisto3 :: Clock Basic200 -> Reset Basic200 -> Enable Basic200 -> Vec 3 (Signal Basic200 (DataCount 12)) -> Signal Basic200 SpeedChange callisto3 clk rst ena dataCounts = callistoClockControl clk rst ena config availableLinkMask dataCounts where availableLinkMask = pure $ complement 0
8b9773661a9d24e73d15395868628c849b2ff8684ebca52dd3d2ca489102d527
rtoy/cmucl
mixed-compare.lisp
(defun foo (x y) (< (the single-float x) (the rational y)))
null
https://raw.githubusercontent.com/rtoy/cmucl/9b1abca53598f03a5b39ded4185471a5b8777dea/src/tests/mixed-compare.lisp
lisp
(defun foo (x y) (< (the single-float x) (the rational y)))
04554ef251cc7224d50cabcfec9c2d8ba37455e475b6c91edbdc3418713919ce
alanning/meteor-load-test
http_binding.clj
;; ;; Using rebinding and reporting with The Grinder ;; (ns math.http (:import [net.grinder.script Grinder Test] [net.grinder.plugin.http HTTPRequest]) (:use math.test) (:require [clj-http.client :as http]) ) (let [grinder Grinder/grinder stats (.getStatistics grinder) test (Test. 5 "Rebinding and reporting")] (defn log [& text] (.. grinder (getLogger) (info (apply str text)))) ;; if testing reports an error, let the grinder know about it (defn report [event] (when-not (= (:type event) :pass) (log event) (.. stats getForLastTest (setSuccess false)))) ;; the arity of the instrumented fn changes to match the rebound fn the return value of HTTPRequest must be converted as well (defn instrumented-get [url & _] (let [resp (.. (HTTPRequest.) (GET url))] {:body (.getText resp) :status (.getStatusCode resp)})) (.. test (record instrumented-get)) (fn [] (fn [] ;; rebind the http/get fn to our instrumented fn ;; rebind test reporting to capture errors (binding [wrapped-get instrumented-get clojure.test/report report] ;; delay grinder reporting for test reporting to work (.setDelayReports stats true) (test-operation) (test-error)) ) ) )
null
https://raw.githubusercontent.com/alanning/meteor-load-test/76bb3a2bdc4e6bfb81755606ac18963f088d5751/grinder/http_binding.clj
clojure
Using rebinding and reporting with The Grinder if testing reports an error, let the grinder know about it the arity of the instrumented fn changes to match the rebound fn rebind the http/get fn to our instrumented fn rebind test reporting to capture errors delay grinder reporting for test reporting to work
(ns math.http (:import [net.grinder.script Grinder Test] [net.grinder.plugin.http HTTPRequest]) (:use math.test) (:require [clj-http.client :as http]) ) (let [grinder Grinder/grinder stats (.getStatistics grinder) test (Test. 5 "Rebinding and reporting")] (defn log [& text] (.. grinder (getLogger) (info (apply str text)))) (defn report [event] (when-not (= (:type event) :pass) (log event) (.. stats getForLastTest (setSuccess false)))) the return value of HTTPRequest must be converted as well (defn instrumented-get [url & _] (let [resp (.. (HTTPRequest.) (GET url))] {:body (.getText resp) :status (.getStatusCode resp)})) (.. test (record instrumented-get)) (fn [] (fn [] (binding [wrapped-get instrumented-get clojure.test/report report] (.setDelayReports stats true) (test-operation) (test-error)) ) ) )
e91a61faac5292e08f52efbc663ce913628d9b459c0aca56c0159754ac4fdd65
inaka/elvis_core
elvis_SUITE.erl
-module(elvis_SUITE). -behaviour(ct_suite). -export([all/0, init_per_suite/1, end_per_suite/1, chunk_fold_task/2]). -export([rock_with_empty_map_config/1, rock_with_empty_list_config/1, rock_with_incomplete_config/1, rock_with_list_config/1, rock_with_file_config/1, rock_with_old_config/1, rock_with_rebar_default_config/1, rock_this/1, rock_without_colors/1, rock_with_parsable/1, rock_with_no_output_has_no_output/1, rock_with_non_parsable_file/1, rock_with_errors_has_output/1, rock_without_errors_has_no_output/1, rock_without_errors_and_with_verbose_has_output/1, rock_with_rule_groups/1, rock_this_skipping_files/1, rock_this_not_skipping_files/1, rock_with_umbrella_apps/1, custom_ruleset/1, hrl_ruleset/1, throw_configuration/1, find_file_and_check_src/1, find_file_with_ignore/1, invalid_file/1, to_string/1, chunk_fold/1]). -define(EXCLUDED_FUNS, [module_info, all, test, init_per_suite, end_per_suite, chunk_fold_task]). -type config() :: [{atom(), term()}]. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Common test %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -spec all() -> [atom()]. all() -> Exports = elvis_SUITE:module_info(exports), [F || {F, _} <- Exports, not lists:member(F, ?EXCLUDED_FUNS)]. -spec init_per_suite(config()) -> config(). init_per_suite(Config) -> {ok, _} = application:ensure_all_started(elvis_core), Config. -spec end_per_suite(config()) -> config(). end_per_suite(Config) -> ok = application:stop(elvis_core), Config. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Test Cases %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%% Rocking -spec rock_with_empty_map_config(config()) -> any(). rock_with_empty_map_config(_Config) -> ok = try ok = elvis_core:rock([#{}]), fail catch {invalid_config, _} -> ok end, ok = try ok = elvis_core:rock([#{} || X <- lists:seq(1, 10), X < 1]), fail catch {invalid_config, _} -> ok end. -spec rock_with_empty_list_config(config()) -> any(). rock_with_empty_list_config(_Config) -> ok = try ok = elvis_core:rock([#{}, #{}]), fail catch {invalid_config, _} -> ok end. -spec rock_with_incomplete_config(config()) -> any(). rock_with_incomplete_config(_Config) -> ElvisConfig = [#{src_dirs => ["src"]}], ok = try ok = elvis_core:rock(ElvisConfig), fail catch {invalid_config, _} -> ok end. -spec rock_with_list_config(config()) -> any(). rock_with_list_config(_Config) -> ElvisConfig = [#{src_dirs => ["src"], rules => []}], ok = try ok = elvis_core:rock(ElvisConfig) catch {invalid_config, _} -> fail end. -spec rock_with_file_config(config()) -> ok. rock_with_file_config(_Config) -> ConfigPath = "../../config/elvis.config", ElvisConfig = elvis_config:from_file(ConfigPath), Fun = fun() -> elvis_core:rock(ElvisConfig) end, Expected = "# \\.\\./\\.\\./_build/test/lib/elvis_core/test/" ++ "examples/.*\\.erl.*FAIL", [_ | _] = check_some_line_output(Fun, Expected, fun matches_regex/2), ok. -spec rock_with_old_config(config()) -> ok. rock_with_old_config(_Config) -> ConfigPath = "../../config/old/elvis.config", ElvisConfig = elvis_config:from_file(ConfigPath), ok = try ok = elvis_core:rock(ElvisConfig) catch {invalid_config, _} -> fail end, ConfigPath1 = "../../config/old/elvis-test.config", ElvisConfig1 = elvis_config:from_file(ConfigPath1), ok = try ok = elvis_core:rock(ElvisConfig1) catch {invalid_config, _} -> fail end, ConfigPath2 = "../../config/old/elvis-test-rule-config-list.config", ElvisConfig2 = elvis_config:from_file(ConfigPath2), ok = try ok = elvis_core:rock(ElvisConfig2) catch {invalid_config, _} -> fail end. -spec rock_with_rebar_default_config(config()) -> ok. rock_with_rebar_default_config(_Config) -> {ok, _} = file:copy("../../config/rebar.config", "rebar.config"), ElvisConfig = elvis_config:from_rebar("rebar.config"), [#{name := line_length}] = try {fail, Results} = elvis_core:rock(ElvisConfig), [Rule || #{rules := [Rule]} <- Results] after file:delete("rebar.config") end, ok. -spec rock_this(config()) -> ok. rock_this(_Config) -> ElvisConfig = elvis_test_utils:config(), ok = elvis_core:rock_this(elvis_core, ElvisConfig), ok = try {fail, _} = elvis_core:rock_this("bla.erl", ElvisConfig) catch _:{enoent, "bla.erl"} -> ok end, Path = "../../_build/test/lib/elvis_core/test/examples/fail_line_length.erl", {fail, _} = elvis_core:rock_this(Path, ElvisConfig), ok. -spec rock_without_colors(config()) -> ok. rock_without_colors(_Config) -> ElvisConfig = elvis_test_utils:config(), Fun = fun() -> elvis_core:rock(ElvisConfig) end, Expected = "\\e.*?m", ok = try check_some_line_output(Fun, Expected, fun matches_regex/2) of Result -> ct:fail("Unexpected result ~p", [Result]) catch _:{badmatch, []} -> ok end. -spec rock_with_parsable(config()) -> ok. rock_with_parsable(_Config) -> {ok, Default} = application:get_env(elvis_core, output_format), application:set_env(elvis_core, output_format, parsable), ElvisConfig = elvis_test_utils:config(), Fun = fun() -> elvis_core:rock(ElvisConfig) end, Expected = ".*\\.erl:\\d:[a-zA-Z0-9_]+:.*", ok = try check_some_line_output(Fun, Expected, fun matches_regex/2) of Result -> io:format("~p~n", [Result]) catch _:{badmatch, []} -> ct:fail("Unexpected result ~p") after application:set_env(elvis_core, output_format, Default) end. rock_with_non_parsable_file(_Config) -> ElvisConfig = elvis_test_utils:config(), Path = "../../_build/test/lib/elvis_core/test/non_compilable_examples/fail_non_parsable_file.erl", try elvis_core:rock_this(Path, ElvisConfig) catch {fail, {error, {badmatch, _}}} -> ok end. -spec rock_with_no_output_has_no_output(config()) -> ok. rock_with_no_output_has_no_output(_Config) -> application:set_env(elvis_core, no_output, true), ElvisConfig = elvis_test_utils:config(), Fun = fun() -> elvis_core:rock(ElvisConfig) end, [] = get_output(Fun), application:unset_env(elvis_core, no_output), ok. -spec rock_with_errors_has_output(config()) -> ok. rock_with_errors_has_output(_Config) -> ElvisConfig = elvis_test_utils:config(), Fun = fun() -> elvis_core:rock(ElvisConfig) end, Expected = "FAIL", [_ | _] = check_some_line_output(Fun, Expected, fun matches_regex/2), ok. -spec rock_without_errors_has_no_output(config()) -> ok. rock_without_errors_has_no_output(_Config) -> ConfigPath = "../../config/test.pass.config", ElvisConfig = elvis_config:from_file(ConfigPath), Fun = fun() -> elvis_core:rock(ElvisConfig) end, Output = get_output(Fun), %% This is related to the test case `rock_with_non_parsable_file`, %% which will print an error to the standard output %% and CT will capture it. %% Thus, we remove it from the list of captures before doing the actual check RemoveSearchPattern = "fail_non_parsable_file.erl", ct:pal("Output=~p~n", [Output]), [] = lists:filter(fun(String) -> string:find(String, RemoveSearchPattern) == nomatch end, Output), ok. -spec rock_without_errors_and_with_verbose_has_output(config()) -> ok. rock_without_errors_and_with_verbose_has_output(_Config) -> application:set_env(elvis_core, verbose, true), ElvisConfig = elvis_test_utils:config(), Fun = fun() -> elvis_core:rock(ElvisConfig) end, Expected = "OK", [_ | _] = check_some_line_output(Fun, Expected, fun matches_regex/2), application:unset_env(elvis_core, verbose), ok. -spec rock_with_rule_groups(Config :: config()) -> ok. rock_with_rule_groups(_Config) -> % elvis_config will load default elvis_core rules for every % rule_group in the config. RulesGroupConfig = [#{dirs => ["src"], filter => "*.erl", ruleset => erl_files}, #{dirs => ["include"], filter => "*.erl", ruleset => hrl_files}, #{dirs => ["_build/test/lib/elvis_core/ebin"], filter => "*.beam", ruleset => beam_files}, #{dirs => ["."], filter => "rebar.config", ruleset => rebar_config}, #{dirs => ["."], filter => "elvis.config", ruleset => elvis_config}], ok = try ok = elvis_core:rock(RulesGroupConfig) catch {invalid_config, _} -> fail end, % Override default elvis_core rules without ruleset should fail. OverrideFailConfig = [#{dirs => ["src"], rules => [{elvis_text_style, line_length, #{limit => 90}}, {elvis_style, state_record_and_type, disable}]}], ok = try _ = elvis_core:rock(OverrideFailConfig), fail catch {invalid_config, _} -> ok end, % Override default elvis_core rules. OverrideConfig = [#{dirs => ["src"], filter => "*.erl", ruleset => erl_files, rules => I like 90 chars per line . {elvis_text_style, no_tabs, disable}]}, % I like tabs so disable this rule. #{dirs => ["."], filter => "rebar.config", ruleset => rebar_config}, #{dirs => ["."], filter => "elvis.config", ruleset => elvis_config}], ok = try ok = elvis_core:rock(OverrideConfig) catch {invalid_config, _} -> fail end. -spec rock_this_skipping_files(Config :: config()) -> ok. rock_this_skipping_files(_Config) -> meck:new(elvis_file, [passthrough]), Dirs = ["../../_build/test/lib/elvis_core/test/examples"], [File] = elvis_file:find_files(Dirs, "small.erl"), Path = elvis_file:path(File), ConfigPath = "../../config/elvis-test-pa.config", ElvisConfig = elvis_config:from_file(ConfigPath), ok = elvis_core:rock_this(Path, ElvisConfig), 0 = meck:num_calls(elvis_file, load_file_data, '_'), meck:unload(elvis_file), ok. -spec rock_this_not_skipping_files(Config :: config()) -> ok. rock_this_not_skipping_files(_Config) -> meck:new(elvis_file, [passthrough]), Dirs = ["../../_build/test/lib/elvis_core/test/examples"], [File] = elvis_file:find_files(Dirs, "small.erl"), Path = elvis_file:path(File), ElvisConfig = elvis_test_utils:config(), ok = elvis_core:rock_this(Path, ElvisConfig), 1 = meck:num_calls(elvis_file, load_file_data, '_'), meck:unload(elvis_file), ok. -spec rock_with_umbrella_apps(config()) -> ok. rock_with_umbrella_apps(_Config) -> ElvisUmbrellaConfigFile = "../../config/elvis-umbrella.config", ElvisConfig = elvis_config:from_file(ElvisUmbrellaConfigFile), {fail, [#{file := "../../_build/test/lib/elvis_core/test/dirs/test/dir_test.erl"}, #{file := "../../_build/test/lib/elvis_core/test/dirs/src/dirs_src.erl"}, #{file := "../../_build/test/lib/elvis_core/test/dirs/apps/app2/test/dirs_apps_app2_test.erl"}, #{file := "../../_build/test/lib/elvis_core/test/dirs/apps/app2/src/dirs_apps_app2_src.erl"}, #{file := "../../_build/test/lib/elvis_core/test/dirs/apps/app1/test/dirs_apps_app1_test.erl"}, #{file := "../../_build/test/lib/elvis_core/test/dirs/apps/app1/src/dirs_apps_app1_src.erl"}]} = elvis_core:rock(ElvisConfig), ok. %%%%%%%%%%%%%%% Utils -spec custom_ruleset(config()) -> any(). custom_ruleset(_Config) -> ConfigPath = "../../config/elvis-test-custom-ruleset.config", ElvisConfig = elvis_config:from_file(ConfigPath), [[{elvis_text_style, no_tabs}]] = elvis_config:rules(ElvisConfig), %% read unknown ruleset configuration to ensure rulesets from %% previous load do not stick around ConfigPathMissing = "../../config/elvis-test-unknown-ruleset.config", ElvisConfigMissing = elvis_config:from_file(ConfigPathMissing), [[]] = elvis_config:rules(ElvisConfigMissing), ok. -spec hrl_ruleset(config()) -> any(). hrl_ruleset(_Config) -> ConfigPath = "../../config/elvis-test-hrl-files.config", ElvisConfig = elvis_config:from_file(ConfigPath), {fail, [#{file := "../../_build/test/lib/elvis_core/test/examples/test-good.hrl", rules := []}, #{file := "../../_build/test/lib/elvis_core/test/examples/test-bad.hrl", rules := [#{name := line_length}]}]} = elvis_core:rock(ElvisConfig), ok. -spec throw_configuration(config()) -> any(). throw_configuration(_Config) -> Filename = "./elvis.config", ok = file:write_file(Filename, <<"-">>), ok = try _ = elvis_config:from_file(Filename), fail catch _ -> ok after file:delete(Filename) end. -spec find_file_and_check_src(config()) -> any(). find_file_and_check_src(_Config) -> Dirs = ["../../test/examples"], [] = elvis_file:find_files(Dirs, "doesnt_exist.erl"), [File] = elvis_file:find_files(Dirs, "small.erl"), {<<"-module(small).", LineBreak/binary>>, _} = elvis_file:src(File), LineBreak = case os:type() of {unix, _} -> <<"\n">>; {win32, _} -> <<"\r\n">> end, {error, enoent} = elvis_file:src(#{path => "doesnt_exist.erl"}). -spec find_file_with_ignore(config()) -> any(). find_file_with_ignore(_Config) -> Dirs = ["../../test/examples"], Filter = "find_test*.erl", Ignore = elvis_config:ignore(#{ignore => [find_test1]}), Files = [_, _] = elvis_file:find_files(Dirs, Filter), [_, _] = elvis_file:filter_files(Files, Dirs, Filter, []), [#{path := "../../test/examples/find_test2.erl"}] = elvis_file:filter_files(Files, Dirs, Filter, Ignore). -spec invalid_file(config()) -> any(). invalid_file(_Config) -> ok = try {error, _} = elvis_file:src(#{}), fail catch {invalid_file, #{}} -> ok end. -spec to_string(config()) -> any(). to_string(_Config) -> "1" = elvis_utils:to_str(1), "hello" = elvis_utils:to_str(<<"hello">>), "atom" = elvis_utils:to_str(atom). -spec chunk_fold(config()) -> any(). chunk_fold(_Config) -> Multiplier = 10, List = lists:seq(1, 10), {ok, Value} = elvis_task:chunk_fold({?MODULE, chunk_fold_task}, fun(Elem, Acc) -> {ok, Acc + Elem} end, 0, [Multiplier], lists:seq(1, 10), 10), Value = lists:sum( lists:map(fun(E) -> E * Multiplier end, List)), {error, {error, undef}} = elvis_task:chunk_fold({?MODULE, chunk_fold_task_do_not_exist}, fun(Elem, Acc) -> {ok, Acc + Elem} end, 0, [Multiplier], lists:seq(1, 10), 10). -spec chunk_fold_task(integer(), integer()) -> {ok, integer()}. chunk_fold_task(Elem, Multiplier) -> {ok, Elem * Multiplier}. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Private %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% check_some_line_output(Fun, Expected, FilterFun) -> _ = ct:capture_start(), _ = Fun(), _ = ct:capture_stop(), Lines = ct:capture_get([]), ListFun = fun(Line) -> FilterFun(Line, Expected) end, [_ | _] = lists:filter(ListFun, Lines). get_output(Fun) -> _ = ct:capture_start(), _ = Fun(), _ = ct:capture_stop(), ct:capture_get([]). matches_regex(Result, Regex) -> case re:run(Result, Regex) of {match, _} -> true; nomatch -> false end.
null
https://raw.githubusercontent.com/inaka/elvis_core/3aad6aecb71f89dc67811a40c97ef2faab679f77/test/elvis_SUITE.erl
erlang
Common test Test Cases This is related to the test case `rock_with_non_parsable_file`, which will print an error to the standard output and CT will capture it. Thus, we remove it from the list of captures before doing the actual check elvis_config will load default elvis_core rules for every rule_group in the config. Override default elvis_core rules without ruleset should fail. Override default elvis_core rules. I like tabs so disable this rule. read unknown ruleset configuration to ensure rulesets from previous load do not stick around Private
-module(elvis_SUITE). -behaviour(ct_suite). -export([all/0, init_per_suite/1, end_per_suite/1, chunk_fold_task/2]). -export([rock_with_empty_map_config/1, rock_with_empty_list_config/1, rock_with_incomplete_config/1, rock_with_list_config/1, rock_with_file_config/1, rock_with_old_config/1, rock_with_rebar_default_config/1, rock_this/1, rock_without_colors/1, rock_with_parsable/1, rock_with_no_output_has_no_output/1, rock_with_non_parsable_file/1, rock_with_errors_has_output/1, rock_without_errors_has_no_output/1, rock_without_errors_and_with_verbose_has_output/1, rock_with_rule_groups/1, rock_this_skipping_files/1, rock_this_not_skipping_files/1, rock_with_umbrella_apps/1, custom_ruleset/1, hrl_ruleset/1, throw_configuration/1, find_file_and_check_src/1, find_file_with_ignore/1, invalid_file/1, to_string/1, chunk_fold/1]). -define(EXCLUDED_FUNS, [module_info, all, test, init_per_suite, end_per_suite, chunk_fold_task]). -type config() :: [{atom(), term()}]. -spec all() -> [atom()]. all() -> Exports = elvis_SUITE:module_info(exports), [F || {F, _} <- Exports, not lists:member(F, ?EXCLUDED_FUNS)]. -spec init_per_suite(config()) -> config(). init_per_suite(Config) -> {ok, _} = application:ensure_all_started(elvis_core), Config. -spec end_per_suite(config()) -> config(). end_per_suite(Config) -> ok = application:stop(elvis_core), Config. Rocking -spec rock_with_empty_map_config(config()) -> any(). rock_with_empty_map_config(_Config) -> ok = try ok = elvis_core:rock([#{}]), fail catch {invalid_config, _} -> ok end, ok = try ok = elvis_core:rock([#{} || X <- lists:seq(1, 10), X < 1]), fail catch {invalid_config, _} -> ok end. -spec rock_with_empty_list_config(config()) -> any(). rock_with_empty_list_config(_Config) -> ok = try ok = elvis_core:rock([#{}, #{}]), fail catch {invalid_config, _} -> ok end. -spec rock_with_incomplete_config(config()) -> any(). rock_with_incomplete_config(_Config) -> ElvisConfig = [#{src_dirs => ["src"]}], ok = try ok = elvis_core:rock(ElvisConfig), fail catch {invalid_config, _} -> ok end. -spec rock_with_list_config(config()) -> any(). rock_with_list_config(_Config) -> ElvisConfig = [#{src_dirs => ["src"], rules => []}], ok = try ok = elvis_core:rock(ElvisConfig) catch {invalid_config, _} -> fail end. -spec rock_with_file_config(config()) -> ok. rock_with_file_config(_Config) -> ConfigPath = "../../config/elvis.config", ElvisConfig = elvis_config:from_file(ConfigPath), Fun = fun() -> elvis_core:rock(ElvisConfig) end, Expected = "# \\.\\./\\.\\./_build/test/lib/elvis_core/test/" ++ "examples/.*\\.erl.*FAIL", [_ | _] = check_some_line_output(Fun, Expected, fun matches_regex/2), ok. -spec rock_with_old_config(config()) -> ok. rock_with_old_config(_Config) -> ConfigPath = "../../config/old/elvis.config", ElvisConfig = elvis_config:from_file(ConfigPath), ok = try ok = elvis_core:rock(ElvisConfig) catch {invalid_config, _} -> fail end, ConfigPath1 = "../../config/old/elvis-test.config", ElvisConfig1 = elvis_config:from_file(ConfigPath1), ok = try ok = elvis_core:rock(ElvisConfig1) catch {invalid_config, _} -> fail end, ConfigPath2 = "../../config/old/elvis-test-rule-config-list.config", ElvisConfig2 = elvis_config:from_file(ConfigPath2), ok = try ok = elvis_core:rock(ElvisConfig2) catch {invalid_config, _} -> fail end. -spec rock_with_rebar_default_config(config()) -> ok. rock_with_rebar_default_config(_Config) -> {ok, _} = file:copy("../../config/rebar.config", "rebar.config"), ElvisConfig = elvis_config:from_rebar("rebar.config"), [#{name := line_length}] = try {fail, Results} = elvis_core:rock(ElvisConfig), [Rule || #{rules := [Rule]} <- Results] after file:delete("rebar.config") end, ok. -spec rock_this(config()) -> ok. rock_this(_Config) -> ElvisConfig = elvis_test_utils:config(), ok = elvis_core:rock_this(elvis_core, ElvisConfig), ok = try {fail, _} = elvis_core:rock_this("bla.erl", ElvisConfig) catch _:{enoent, "bla.erl"} -> ok end, Path = "../../_build/test/lib/elvis_core/test/examples/fail_line_length.erl", {fail, _} = elvis_core:rock_this(Path, ElvisConfig), ok. -spec rock_without_colors(config()) -> ok. rock_without_colors(_Config) -> ElvisConfig = elvis_test_utils:config(), Fun = fun() -> elvis_core:rock(ElvisConfig) end, Expected = "\\e.*?m", ok = try check_some_line_output(Fun, Expected, fun matches_regex/2) of Result -> ct:fail("Unexpected result ~p", [Result]) catch _:{badmatch, []} -> ok end. -spec rock_with_parsable(config()) -> ok. rock_with_parsable(_Config) -> {ok, Default} = application:get_env(elvis_core, output_format), application:set_env(elvis_core, output_format, parsable), ElvisConfig = elvis_test_utils:config(), Fun = fun() -> elvis_core:rock(ElvisConfig) end, Expected = ".*\\.erl:\\d:[a-zA-Z0-9_]+:.*", ok = try check_some_line_output(Fun, Expected, fun matches_regex/2) of Result -> io:format("~p~n", [Result]) catch _:{badmatch, []} -> ct:fail("Unexpected result ~p") after application:set_env(elvis_core, output_format, Default) end. rock_with_non_parsable_file(_Config) -> ElvisConfig = elvis_test_utils:config(), Path = "../../_build/test/lib/elvis_core/test/non_compilable_examples/fail_non_parsable_file.erl", try elvis_core:rock_this(Path, ElvisConfig) catch {fail, {error, {badmatch, _}}} -> ok end. -spec rock_with_no_output_has_no_output(config()) -> ok. rock_with_no_output_has_no_output(_Config) -> application:set_env(elvis_core, no_output, true), ElvisConfig = elvis_test_utils:config(), Fun = fun() -> elvis_core:rock(ElvisConfig) end, [] = get_output(Fun), application:unset_env(elvis_core, no_output), ok. -spec rock_with_errors_has_output(config()) -> ok. rock_with_errors_has_output(_Config) -> ElvisConfig = elvis_test_utils:config(), Fun = fun() -> elvis_core:rock(ElvisConfig) end, Expected = "FAIL", [_ | _] = check_some_line_output(Fun, Expected, fun matches_regex/2), ok. -spec rock_without_errors_has_no_output(config()) -> ok. rock_without_errors_has_no_output(_Config) -> ConfigPath = "../../config/test.pass.config", ElvisConfig = elvis_config:from_file(ConfigPath), Fun = fun() -> elvis_core:rock(ElvisConfig) end, Output = get_output(Fun), RemoveSearchPattern = "fail_non_parsable_file.erl", ct:pal("Output=~p~n", [Output]), [] = lists:filter(fun(String) -> string:find(String, RemoveSearchPattern) == nomatch end, Output), ok. -spec rock_without_errors_and_with_verbose_has_output(config()) -> ok. rock_without_errors_and_with_verbose_has_output(_Config) -> application:set_env(elvis_core, verbose, true), ElvisConfig = elvis_test_utils:config(), Fun = fun() -> elvis_core:rock(ElvisConfig) end, Expected = "OK", [_ | _] = check_some_line_output(Fun, Expected, fun matches_regex/2), application:unset_env(elvis_core, verbose), ok. -spec rock_with_rule_groups(Config :: config()) -> ok. rock_with_rule_groups(_Config) -> RulesGroupConfig = [#{dirs => ["src"], filter => "*.erl", ruleset => erl_files}, #{dirs => ["include"], filter => "*.erl", ruleset => hrl_files}, #{dirs => ["_build/test/lib/elvis_core/ebin"], filter => "*.beam", ruleset => beam_files}, #{dirs => ["."], filter => "rebar.config", ruleset => rebar_config}, #{dirs => ["."], filter => "elvis.config", ruleset => elvis_config}], ok = try ok = elvis_core:rock(RulesGroupConfig) catch {invalid_config, _} -> fail end, OverrideFailConfig = [#{dirs => ["src"], rules => [{elvis_text_style, line_length, #{limit => 90}}, {elvis_style, state_record_and_type, disable}]}], ok = try _ = elvis_core:rock(OverrideFailConfig), fail catch {invalid_config, _} -> ok end, OverrideConfig = [#{dirs => ["src"], filter => "*.erl", ruleset => erl_files, rules => I like 90 chars per line . #{dirs => ["."], filter => "rebar.config", ruleset => rebar_config}, #{dirs => ["."], filter => "elvis.config", ruleset => elvis_config}], ok = try ok = elvis_core:rock(OverrideConfig) catch {invalid_config, _} -> fail end. -spec rock_this_skipping_files(Config :: config()) -> ok. rock_this_skipping_files(_Config) -> meck:new(elvis_file, [passthrough]), Dirs = ["../../_build/test/lib/elvis_core/test/examples"], [File] = elvis_file:find_files(Dirs, "small.erl"), Path = elvis_file:path(File), ConfigPath = "../../config/elvis-test-pa.config", ElvisConfig = elvis_config:from_file(ConfigPath), ok = elvis_core:rock_this(Path, ElvisConfig), 0 = meck:num_calls(elvis_file, load_file_data, '_'), meck:unload(elvis_file), ok. -spec rock_this_not_skipping_files(Config :: config()) -> ok. rock_this_not_skipping_files(_Config) -> meck:new(elvis_file, [passthrough]), Dirs = ["../../_build/test/lib/elvis_core/test/examples"], [File] = elvis_file:find_files(Dirs, "small.erl"), Path = elvis_file:path(File), ElvisConfig = elvis_test_utils:config(), ok = elvis_core:rock_this(Path, ElvisConfig), 1 = meck:num_calls(elvis_file, load_file_data, '_'), meck:unload(elvis_file), ok. -spec rock_with_umbrella_apps(config()) -> ok. rock_with_umbrella_apps(_Config) -> ElvisUmbrellaConfigFile = "../../config/elvis-umbrella.config", ElvisConfig = elvis_config:from_file(ElvisUmbrellaConfigFile), {fail, [#{file := "../../_build/test/lib/elvis_core/test/dirs/test/dir_test.erl"}, #{file := "../../_build/test/lib/elvis_core/test/dirs/src/dirs_src.erl"}, #{file := "../../_build/test/lib/elvis_core/test/dirs/apps/app2/test/dirs_apps_app2_test.erl"}, #{file := "../../_build/test/lib/elvis_core/test/dirs/apps/app2/src/dirs_apps_app2_src.erl"}, #{file := "../../_build/test/lib/elvis_core/test/dirs/apps/app1/test/dirs_apps_app1_test.erl"}, #{file := "../../_build/test/lib/elvis_core/test/dirs/apps/app1/src/dirs_apps_app1_src.erl"}]} = elvis_core:rock(ElvisConfig), ok. Utils -spec custom_ruleset(config()) -> any(). custom_ruleset(_Config) -> ConfigPath = "../../config/elvis-test-custom-ruleset.config", ElvisConfig = elvis_config:from_file(ConfigPath), [[{elvis_text_style, no_tabs}]] = elvis_config:rules(ElvisConfig), ConfigPathMissing = "../../config/elvis-test-unknown-ruleset.config", ElvisConfigMissing = elvis_config:from_file(ConfigPathMissing), [[]] = elvis_config:rules(ElvisConfigMissing), ok. -spec hrl_ruleset(config()) -> any(). hrl_ruleset(_Config) -> ConfigPath = "../../config/elvis-test-hrl-files.config", ElvisConfig = elvis_config:from_file(ConfigPath), {fail, [#{file := "../../_build/test/lib/elvis_core/test/examples/test-good.hrl", rules := []}, #{file := "../../_build/test/lib/elvis_core/test/examples/test-bad.hrl", rules := [#{name := line_length}]}]} = elvis_core:rock(ElvisConfig), ok. -spec throw_configuration(config()) -> any(). throw_configuration(_Config) -> Filename = "./elvis.config", ok = file:write_file(Filename, <<"-">>), ok = try _ = elvis_config:from_file(Filename), fail catch _ -> ok after file:delete(Filename) end. -spec find_file_and_check_src(config()) -> any(). find_file_and_check_src(_Config) -> Dirs = ["../../test/examples"], [] = elvis_file:find_files(Dirs, "doesnt_exist.erl"), [File] = elvis_file:find_files(Dirs, "small.erl"), {<<"-module(small).", LineBreak/binary>>, _} = elvis_file:src(File), LineBreak = case os:type() of {unix, _} -> <<"\n">>; {win32, _} -> <<"\r\n">> end, {error, enoent} = elvis_file:src(#{path => "doesnt_exist.erl"}). -spec find_file_with_ignore(config()) -> any(). find_file_with_ignore(_Config) -> Dirs = ["../../test/examples"], Filter = "find_test*.erl", Ignore = elvis_config:ignore(#{ignore => [find_test1]}), Files = [_, _] = elvis_file:find_files(Dirs, Filter), [_, _] = elvis_file:filter_files(Files, Dirs, Filter, []), [#{path := "../../test/examples/find_test2.erl"}] = elvis_file:filter_files(Files, Dirs, Filter, Ignore). -spec invalid_file(config()) -> any(). invalid_file(_Config) -> ok = try {error, _} = elvis_file:src(#{}), fail catch {invalid_file, #{}} -> ok end. -spec to_string(config()) -> any(). to_string(_Config) -> "1" = elvis_utils:to_str(1), "hello" = elvis_utils:to_str(<<"hello">>), "atom" = elvis_utils:to_str(atom). -spec chunk_fold(config()) -> any(). chunk_fold(_Config) -> Multiplier = 10, List = lists:seq(1, 10), {ok, Value} = elvis_task:chunk_fold({?MODULE, chunk_fold_task}, fun(Elem, Acc) -> {ok, Acc + Elem} end, 0, [Multiplier], lists:seq(1, 10), 10), Value = lists:sum( lists:map(fun(E) -> E * Multiplier end, List)), {error, {error, undef}} = elvis_task:chunk_fold({?MODULE, chunk_fold_task_do_not_exist}, fun(Elem, Acc) -> {ok, Acc + Elem} end, 0, [Multiplier], lists:seq(1, 10), 10). -spec chunk_fold_task(integer(), integer()) -> {ok, integer()}. chunk_fold_task(Elem, Multiplier) -> {ok, Elem * Multiplier}. check_some_line_output(Fun, Expected, FilterFun) -> _ = ct:capture_start(), _ = Fun(), _ = ct:capture_stop(), Lines = ct:capture_get([]), ListFun = fun(Line) -> FilterFun(Line, Expected) end, [_ | _] = lists:filter(ListFun, Lines). get_output(Fun) -> _ = ct:capture_start(), _ = Fun(), _ = ct:capture_stop(), ct:capture_get([]). matches_regex(Result, Regex) -> case re:run(Result, Regex) of {match, _} -> true; nomatch -> false end.
8532da979f4dfc30e27c523965e8d1b6ff51e5c535f53b1fb165d0a861ab7042
rbkmoney/cds
cds_storage_riak.erl
-module(cds_storage_riak). -behaviour(cds_storage). -export([start/1]). -export([put/5]). -export([get/2]). -export([update/5]). -export([delete/2]). -export([search_by_index_value/5]). -export([search_by_index_range/6]). -export([get_keys/3]). -include_lib("riakc/include/riakc.hrl"). -define(DEFAULT_POOLER_TIMEOUT, {1, sec}). % milliseconds -define(DEFAULT_TIMEOUT, 5000). -type storage_params() :: #{ conn_params := conn_params(), timeout => pos_integer(), pool_params => pool_params() }. -type conn_params() :: #{ host := string(), port := pos_integer(), options => client_options() }. -type pool_params() :: #{ max_count => non_neg_integer(), init_count => non_neg_integer(), cull_interval => pooler_time_interval(), max_age => pooler_time_interval(), member_start_timeout => pooler_time_interval(), pool_timeout => pooler_time_interval() }. -type pooler_time_interval() :: {non_neg_integer(), min | sec | ms | mu}. -define(DEFAULT_POOL_PARAMS, #{ max_count => 10, init_count => 10, cull_interval => {0, min}, pool_timeout => ?DEFAULT_POOLER_TIMEOUT }). -define(DEFAULT_CLIENT_OPTS, [ {connect_timeout, 5000} ]). %% %% cds_storage behaviour %% -type namespace() :: cds_storage:namespace(). -type data() :: cds_storage:data(). -type metadata() :: cds_storage:metadata(). -type indexes() :: cds_storage:indexes(). -type index_id() :: cds_storage:index_id(). -type index_value() :: cds_storage:index_value(). -type limit() :: cds_storage:limit(). -spec start([namespace()]) -> ok. start(NSlist) -> _ = start_pool(get_storage_params()), lists:foreach(fun set_bucket/1, NSlist). -spec put(namespace(), key(), data(), metadata(), indexes()) -> ok. put(NS, Key, Data, Meta, Indexes) -> Obj = prepare_object(NS, Key, Data, Meta, Indexes), case batch_put([[Obj]]) of ok -> ok; {error, Reason} -> error(Reason) end. -spec get(namespace(), key()) -> {ok, {data(), metadata(), indexes()}} | {error, not_found}. get(NS, Key) -> case get_(NS, Key) of {ok, DataObj} -> Data = riakc_obj:get_value(DataObj), Meta = get_metadata(DataObj), Indexes = get_indexes(DataObj), {ok, {Data, Meta, Indexes}}; Error -> Error end. -spec update(namespace(), key(), data(), metadata(), indexes()) -> ok | {error, not_found}. update(NS, Key, Data, Meta, Indexes) -> case get_(NS, Key) of {ok, Obj} -> update_(Obj, Data, Meta, Indexes); Error -> Error end. -spec delete(namespace(), key()) -> ok | {error, not_found}. delete(NS, Key) -> case batch_delete([[NS, Key]]) of ok -> ok; {error, Reason} -> error(Reason) end. -spec search_by_index_value( namespace(), index_id(), index_value(), limit(), continuation() ) -> {ok, {[key()], continuation()}}. search_by_index_value(NS, IndexName, IndexValue, Limit, Continuation) -> Result = get_index_eq( NS, IndexName, IndexValue, construct_index_query_options(Limit, Continuation) ), prepare_index_result(Result). -spec search_by_index_range( namespace(), index_id(), StartValue :: index_value(), EndValue :: index_value(), limit(), continuation() ) -> {ok, {[key()], continuation()}}. search_by_index_range(NS, IndexName, StartValue, EndValue, Limit, Continuation) -> Result = get_index_range( NS, IndexName, StartValue, EndValue, construct_index_query_options(Limit, Continuation) ), prepare_index_result(Result). -spec get_keys(namespace(), limit(), continuation()) -> {ok, {[key()], continuation()}}. get_keys(NS, Limit, Continuation) -> Result = get_index_eq( NS, <<"$bucket">>, <<"_">>, construct_index_query_options(Limit, Continuation) ), prepare_index_result(Result). %% Internal %% -spec get_storage_params() -> storage_params(). get_storage_params() -> genlib_app:env(cds, cds_storage_riak). get_default_timeout() -> Params = get_storage_params(), {timeout, genlib_map:get(timeout, Params, ?DEFAULT_TIMEOUT)}. get_pool_timeout() -> Params = get_storage_params(), PoolParams = genlib_map:get(pool_params, Params, ?DEFAULT_POOL_PARAMS), genlib_map:get(pool_timeout, PoolParams, ?DEFAULT_POOLER_TIMEOUT). -spec start_pool(storage_params()) -> ok | no_return(). start_pool(#{conn_params := ConnParams = #{host := Host, port := Port}} = StorageParams) -> PoolParams = maps:get(pool_params, StorageParams, ?DEFAULT_POOL_PARAMS), ClientOpts = maps:get(options, ConnParams, ?DEFAULT_CLIENT_OPTS), PoolConfig = [ {name, riak}, {start_mfa, {riakc_pb_socket, start_link, [Host, Port, ClientOpts]}} ] ++ maps:to_list(PoolParams), {ok, _Pid} = pooler:new_pool(PoolConfig), ok. get_(Bucket, Key) -> case batch_get([[Bucket, Key]]) of {ok, [Obj]} -> {ok, Obj}; {error, notfound} -> {error, not_found}; {error, Reason} -> error(Reason) end. update_(Obj0, Data, Meta, Indexes) -> Obj1 = riakc_obj:update_value(Obj0, Data), Obj2 = set_metadata(Obj1, Meta), Obj3 = set_indexes(Obj2, Indexes), case batch_put([[Obj3]]) of ok -> ok; {error, Reason} -> error(Reason) end. set_bucket(Bucket) -> batch_request(set_bucket, [[Bucket, [{allow_mult, false}]]], ok). batch_get(Args) -> batch_request(get, Args, []). batch_put(Args) -> batch_request(put, Args, ok). batch_delete(Args) -> batch_request(delete, Args, ok). get_index_range(Bucket, Index, StartKey, EndKey, Opts) -> batch_request(get_index_range, [[Bucket, Index, StartKey, EndKey, Opts]], []). get_index_eq(Bucket, Index, Key, Opts) -> batch_request(get_index_eq, [[Bucket, Index, Key, Opts]], []). batch_request(Method, Args, Acc) -> Client = pooler_take_member(), try Result = batch_request(Method, Client, Args, Acc), _ = pooler:return_member(riak, Client, get_client_status(Result)), Result catch Class:Exception:Stacktrace -> _ = pooler:return_member(riak, Client, fail), erlang:raise(Class, Exception, Stacktrace) end. get_client_status(ok) -> ok; get_client_status({ok, _}) -> ok; get_client_status({error, notfound}) -> ok; get_client_status(_Error) -> fail. pooler_take_member() -> case pooler:take_member(riak, get_pool_timeout()) of error_no_members -> throw({pool_error, no_members}); Client -> Client end. batch_request(Method, Client, [Args | Rest], Acc) -> case apply(riakc_pb_socket, Method, [Client | Args]) of ok when Acc =:= ok -> batch_request(Method, Client, Rest, Acc); {ok, Response} when is_list(Acc) -> batch_request(Method, Client, Rest, [Response | Acc]); Error -> Error end; batch_request(_Method, _Client, [], ok) -> ok; batch_request(_Method, _Client, [], Acc) -> {ok, lists:reverse(Acc)}. -spec prepare_index_result({ok, index_results()} | {error, Reason :: term()}) -> {ok, {[key()], continuation()}} | no_return(). prepare_index_result(Result) -> case Result of {ok, [#index_results_v1{keys = Keys, continuation = Continuation}]} when Keys =/= undefined -> {ok, {Keys, Continuation}}; {ok, _} -> {ok, {[], undefined}}; {error, Error} -> error(Error) end. construct_index_query_options(Limit, Continuation) -> prepare_options([{max_results, Limit}, {continuation, Continuation}, get_default_timeout()]). prepare_options(Opts) -> [Item || {_, V} = Item <- Opts, V =/= undefined]. prepare_object(NS, Key, Data, Meta, Indexes) -> case riakc_obj:new(NS, Key, Data) of Error = {error, _} -> error(Error); Obj0 -> Obj1 = set_metadata(Obj0, Meta), set_indexes(Obj1, Indexes) end. -spec set_indexes(riakc_obj(), indexes()) -> riakc_obj(). set_indexes(Obj, Indexes) -> MD1 = riakc_obj:get_update_metadata(Obj), MD2 = riakc_obj:set_secondary_index( MD1, [{Index, [Value]} || {Index, Value} <- Indexes] ), riakc_obj:update_metadata(Obj, MD2). -spec get_indexes(riakc_obj()) -> indexes(). get_indexes(Obj) -> MD = riakc_obj:get_metadata(Obj), Indexes = riakc_obj:get_secondary_indexes(MD), [{Index, Value} || {Index, [Value]} <- Indexes]. -spec set_metadata(riakc_obj(), metadata()) -> riakc_obj(). set_metadata(Obj, Meta) when is_binary(Meta) -> MD0 = riakc_obj:get_update_metadata(Obj), MD1 = riakc_obj:set_user_metadata_entry(MD0, {<<"encrypted-application-metadata">>, Meta}), riakc_obj:update_metadata(Obj, MD1); set_metadata(Obj, undefined) -> MD0 = riakc_obj:get_update_metadata(Obj), MD1 = riakc_obj:delete_user_metadata_entry(MD0, <<"encrypted-application-metadata">>), riakc_obj:update_metadata(Obj, MD1). -spec get_metadata(riakc_obj()) -> metadata(). get_metadata(Obj) -> MD = riakc_obj:get_update_metadata(Obj), case riakc_obj:get_user_metadata_entry(MD, <<"encrypted-application-metadata">>) of Meta when is_binary(Meta) -> Meta; notfound -> undefined end.
null
https://raw.githubusercontent.com/rbkmoney/cds/e5024a06a65a3195f9a677fcbd5b383ffea8c1e4/apps/cds/src/cds_storage_riak.erl
erlang
milliseconds cds_storage behaviour
-module(cds_storage_riak). -behaviour(cds_storage). -export([start/1]). -export([put/5]). -export([get/2]). -export([update/5]). -export([delete/2]). -export([search_by_index_value/5]). -export([search_by_index_range/6]). -export([get_keys/3]). -include_lib("riakc/include/riakc.hrl"). -define(DEFAULT_POOLER_TIMEOUT, {1, sec}). -define(DEFAULT_TIMEOUT, 5000). -type storage_params() :: #{ conn_params := conn_params(), timeout => pos_integer(), pool_params => pool_params() }. -type conn_params() :: #{ host := string(), port := pos_integer(), options => client_options() }. -type pool_params() :: #{ max_count => non_neg_integer(), init_count => non_neg_integer(), cull_interval => pooler_time_interval(), max_age => pooler_time_interval(), member_start_timeout => pooler_time_interval(), pool_timeout => pooler_time_interval() }. -type pooler_time_interval() :: {non_neg_integer(), min | sec | ms | mu}. -define(DEFAULT_POOL_PARAMS, #{ max_count => 10, init_count => 10, cull_interval => {0, min}, pool_timeout => ?DEFAULT_POOLER_TIMEOUT }). -define(DEFAULT_CLIENT_OPTS, [ {connect_timeout, 5000} ]). -type namespace() :: cds_storage:namespace(). -type data() :: cds_storage:data(). -type metadata() :: cds_storage:metadata(). -type indexes() :: cds_storage:indexes(). -type index_id() :: cds_storage:index_id(). -type index_value() :: cds_storage:index_value(). -type limit() :: cds_storage:limit(). -spec start([namespace()]) -> ok. start(NSlist) -> _ = start_pool(get_storage_params()), lists:foreach(fun set_bucket/1, NSlist). -spec put(namespace(), key(), data(), metadata(), indexes()) -> ok. put(NS, Key, Data, Meta, Indexes) -> Obj = prepare_object(NS, Key, Data, Meta, Indexes), case batch_put([[Obj]]) of ok -> ok; {error, Reason} -> error(Reason) end. -spec get(namespace(), key()) -> {ok, {data(), metadata(), indexes()}} | {error, not_found}. get(NS, Key) -> case get_(NS, Key) of {ok, DataObj} -> Data = riakc_obj:get_value(DataObj), Meta = get_metadata(DataObj), Indexes = get_indexes(DataObj), {ok, {Data, Meta, Indexes}}; Error -> Error end. -spec update(namespace(), key(), data(), metadata(), indexes()) -> ok | {error, not_found}. update(NS, Key, Data, Meta, Indexes) -> case get_(NS, Key) of {ok, Obj} -> update_(Obj, Data, Meta, Indexes); Error -> Error end. -spec delete(namespace(), key()) -> ok | {error, not_found}. delete(NS, Key) -> case batch_delete([[NS, Key]]) of ok -> ok; {error, Reason} -> error(Reason) end. -spec search_by_index_value( namespace(), index_id(), index_value(), limit(), continuation() ) -> {ok, {[key()], continuation()}}. search_by_index_value(NS, IndexName, IndexValue, Limit, Continuation) -> Result = get_index_eq( NS, IndexName, IndexValue, construct_index_query_options(Limit, Continuation) ), prepare_index_result(Result). -spec search_by_index_range( namespace(), index_id(), StartValue :: index_value(), EndValue :: index_value(), limit(), continuation() ) -> {ok, {[key()], continuation()}}. search_by_index_range(NS, IndexName, StartValue, EndValue, Limit, Continuation) -> Result = get_index_range( NS, IndexName, StartValue, EndValue, construct_index_query_options(Limit, Continuation) ), prepare_index_result(Result). -spec get_keys(namespace(), limit(), continuation()) -> {ok, {[key()], continuation()}}. get_keys(NS, Limit, Continuation) -> Result = get_index_eq( NS, <<"$bucket">>, <<"_">>, construct_index_query_options(Limit, Continuation) ), prepare_index_result(Result). Internal -spec get_storage_params() -> storage_params(). get_storage_params() -> genlib_app:env(cds, cds_storage_riak). get_default_timeout() -> Params = get_storage_params(), {timeout, genlib_map:get(timeout, Params, ?DEFAULT_TIMEOUT)}. get_pool_timeout() -> Params = get_storage_params(), PoolParams = genlib_map:get(pool_params, Params, ?DEFAULT_POOL_PARAMS), genlib_map:get(pool_timeout, PoolParams, ?DEFAULT_POOLER_TIMEOUT). -spec start_pool(storage_params()) -> ok | no_return(). start_pool(#{conn_params := ConnParams = #{host := Host, port := Port}} = StorageParams) -> PoolParams = maps:get(pool_params, StorageParams, ?DEFAULT_POOL_PARAMS), ClientOpts = maps:get(options, ConnParams, ?DEFAULT_CLIENT_OPTS), PoolConfig = [ {name, riak}, {start_mfa, {riakc_pb_socket, start_link, [Host, Port, ClientOpts]}} ] ++ maps:to_list(PoolParams), {ok, _Pid} = pooler:new_pool(PoolConfig), ok. get_(Bucket, Key) -> case batch_get([[Bucket, Key]]) of {ok, [Obj]} -> {ok, Obj}; {error, notfound} -> {error, not_found}; {error, Reason} -> error(Reason) end. update_(Obj0, Data, Meta, Indexes) -> Obj1 = riakc_obj:update_value(Obj0, Data), Obj2 = set_metadata(Obj1, Meta), Obj3 = set_indexes(Obj2, Indexes), case batch_put([[Obj3]]) of ok -> ok; {error, Reason} -> error(Reason) end. set_bucket(Bucket) -> batch_request(set_bucket, [[Bucket, [{allow_mult, false}]]], ok). batch_get(Args) -> batch_request(get, Args, []). batch_put(Args) -> batch_request(put, Args, ok). batch_delete(Args) -> batch_request(delete, Args, ok). get_index_range(Bucket, Index, StartKey, EndKey, Opts) -> batch_request(get_index_range, [[Bucket, Index, StartKey, EndKey, Opts]], []). get_index_eq(Bucket, Index, Key, Opts) -> batch_request(get_index_eq, [[Bucket, Index, Key, Opts]], []). batch_request(Method, Args, Acc) -> Client = pooler_take_member(), try Result = batch_request(Method, Client, Args, Acc), _ = pooler:return_member(riak, Client, get_client_status(Result)), Result catch Class:Exception:Stacktrace -> _ = pooler:return_member(riak, Client, fail), erlang:raise(Class, Exception, Stacktrace) end. get_client_status(ok) -> ok; get_client_status({ok, _}) -> ok; get_client_status({error, notfound}) -> ok; get_client_status(_Error) -> fail. pooler_take_member() -> case pooler:take_member(riak, get_pool_timeout()) of error_no_members -> throw({pool_error, no_members}); Client -> Client end. batch_request(Method, Client, [Args | Rest], Acc) -> case apply(riakc_pb_socket, Method, [Client | Args]) of ok when Acc =:= ok -> batch_request(Method, Client, Rest, Acc); {ok, Response} when is_list(Acc) -> batch_request(Method, Client, Rest, [Response | Acc]); Error -> Error end; batch_request(_Method, _Client, [], ok) -> ok; batch_request(_Method, _Client, [], Acc) -> {ok, lists:reverse(Acc)}. -spec prepare_index_result({ok, index_results()} | {error, Reason :: term()}) -> {ok, {[key()], continuation()}} | no_return(). prepare_index_result(Result) -> case Result of {ok, [#index_results_v1{keys = Keys, continuation = Continuation}]} when Keys =/= undefined -> {ok, {Keys, Continuation}}; {ok, _} -> {ok, {[], undefined}}; {error, Error} -> error(Error) end. construct_index_query_options(Limit, Continuation) -> prepare_options([{max_results, Limit}, {continuation, Continuation}, get_default_timeout()]). prepare_options(Opts) -> [Item || {_, V} = Item <- Opts, V =/= undefined]. prepare_object(NS, Key, Data, Meta, Indexes) -> case riakc_obj:new(NS, Key, Data) of Error = {error, _} -> error(Error); Obj0 -> Obj1 = set_metadata(Obj0, Meta), set_indexes(Obj1, Indexes) end. -spec set_indexes(riakc_obj(), indexes()) -> riakc_obj(). set_indexes(Obj, Indexes) -> MD1 = riakc_obj:get_update_metadata(Obj), MD2 = riakc_obj:set_secondary_index( MD1, [{Index, [Value]} || {Index, Value} <- Indexes] ), riakc_obj:update_metadata(Obj, MD2). -spec get_indexes(riakc_obj()) -> indexes(). get_indexes(Obj) -> MD = riakc_obj:get_metadata(Obj), Indexes = riakc_obj:get_secondary_indexes(MD), [{Index, Value} || {Index, [Value]} <- Indexes]. -spec set_metadata(riakc_obj(), metadata()) -> riakc_obj(). set_metadata(Obj, Meta) when is_binary(Meta) -> MD0 = riakc_obj:get_update_metadata(Obj), MD1 = riakc_obj:set_user_metadata_entry(MD0, {<<"encrypted-application-metadata">>, Meta}), riakc_obj:update_metadata(Obj, MD1); set_metadata(Obj, undefined) -> MD0 = riakc_obj:get_update_metadata(Obj), MD1 = riakc_obj:delete_user_metadata_entry(MD0, <<"encrypted-application-metadata">>), riakc_obj:update_metadata(Obj, MD1). -spec get_metadata(riakc_obj()) -> metadata(). get_metadata(Obj) -> MD = riakc_obj:get_update_metadata(Obj), case riakc_obj:get_user_metadata_entry(MD, <<"encrypted-application-metadata">>) of Meta when is_binary(Meta) -> Meta; notfound -> undefined end.
71a00c6e0353279cc03abe4ba995dc1059747d31d9d264ae4ee776bed401bb0d
nathell/solitaire
subs.cljs
(ns solitaire.subs (:require [re-frame.core :as rf] [solitaire.board :as board])) (rf/reg-sub ::board (fn [db _] (:board db))) (rf/reg-sub ::board-dimensions :<- [::board] (fn [board _] (board/dimensions board))) (rf/reg-sub ::field (fn [db [_ x y]] ;; Your task is to add a new key to the output ;; of this subscription: `:selected?`, containing ;; a boolean value that tells us whether the peg ;; is selected (highlighted). ;; ;; Remember that `db` will now contain `:selected-field`. ;; ;; Look at how the views in `solitaire.views` have changed. ;; We subscribe to this subscription in each `field-view`; ;; `field-view` passes it to `field-peg`, which assigns a ;; CSS class when the peg is selected. {:x x :y y :type (get-in db [:board y x])})) (rf/reg-sub ::status (fn [db _] (:status db))) (rf/reg-sub ::pegs-count :<- [::board] (fn [board _] (board/count-pegs board)))
null
https://raw.githubusercontent.com/nathell/solitaire/02c951d7886aa391b2cea6b49fc6d892dd9c0fa4/exercises/ex_03/subs.cljs
clojure
Your task is to add a new key to the output of this subscription: `:selected?`, containing a boolean value that tells us whether the peg is selected (highlighted). Remember that `db` will now contain `:selected-field`. Look at how the views in `solitaire.views` have changed. We subscribe to this subscription in each `field-view`; `field-view` passes it to `field-peg`, which assigns a CSS class when the peg is selected.
(ns solitaire.subs (:require [re-frame.core :as rf] [solitaire.board :as board])) (rf/reg-sub ::board (fn [db _] (:board db))) (rf/reg-sub ::board-dimensions :<- [::board] (fn [board _] (board/dimensions board))) (rf/reg-sub ::field (fn [db [_ x y]] {:x x :y y :type (get-in db [:board y x])})) (rf/reg-sub ::status (fn [db _] (:status db))) (rf/reg-sub ::pegs-count :<- [::board] (fn [board _] (board/count-pegs board)))
91d3ddce3784d7261006911e2769ae86a756b39f9ac1fa7528e720a9bae77ab1
threatgrid/ctia
vulnerability_test.clj
(ns ctia.entity.vulnerability-test (:require [cheshire.core :as json] [clj-momo.test-helpers.core :as mth] [clojure.test :refer [deftest is join-fixtures use-fixtures]] [clojure.tools.reader.edn :as edn] [ctia.entity.vulnerability :as sut] [ctia.entity.vulnerability.cpe :as cpe] [ctia.test-helpers [access-control :refer [access-control-test]] [auth :refer [all-capabilities]] [core :as helpers :refer [GET]] [crud :refer [entity-crud-test]] [aggregate :refer [test-metric-routes]] [es :as es-helpers] [fake-whoami-service :as whoami-helpers] [http :refer [app->APIHandlerServices]] [store :refer [test-for-each-store-with-app]]] [ctim.examples.vulnerabilities :refer [new-vulnerability-maximal new-vulnerability-minimal]])) (use-fixtures :once (join-fixtures [mth/fixture-schema-validation whoami-helpers/fixture-server])) (deftest test-vulnerability-routes (test-for-each-store-with-app (fn [app] (helpers/set-capabilities! app "foouser" ["foogroup"] "user" all-capabilities) (whoami-helpers/set-whoami-response app "45c1f5e3f05d0" "foouser" "foogroup" "user") (entity-crud-test (into sut/vulnerability-entity {:app app :example new-vulnerability-maximal :headers {:Authorization "45c1f5e3f05d0"}}))))) (deftest test-vulnerability-routes-access-control (access-control-test "vulnerability" new-vulnerability-minimal true true test-for-each-store-with-app)) (deftest test-vulnerability-metric-routes (test-metric-routes (into sut/vulnerability-entity {:entity-minimal new-vulnerability-minimal :enumerable-fields sut/vulnerability-enumerable-fields :date-fields sut/vulnerability-histogram-fields}))) (deftest test-build-configurations-query (is (= (sut/build-configurations-query (map cpe/->cpe-match ["cpe:2.3:o:juniper:advanced_threat_prevention:*:*:*:*:*:*:*:*" "cpe:2.3:h:juniper:atp400:-:*:*:*:*:*:*:*"])) "configurations.nodes.cpe_match.cpe23Uri:cpe\\:2.3\\:o\\:juniper\\:advanced_threat_prevention* OR configurations.nodes.children.cpe_match.cpe23Uri:cpe\\:2.3\\:o\\:juniper\\:advanced_threat_prevention* OR configurations.nodes.cpe_match.cpe23Uri:cpe\\:2.3\\:h\\:juniper\\:atp400* OR configurations.nodes.children.cpe_match.cpe23Uri:cpe\\:2.3\\:h\\:juniper\\:atp400*"))) (deftest search-by-cpe-match-strings-test (helpers/fixture-ctia-with-app (fn [app] (helpers/set-capabilities! app "foouser" ["foogroup"] "user" all-capabilities) (whoami-helpers/set-whoami-response app "45c1f5e3f05d0" "foouser" "foogroup" "user") (let [{{get-store :get-store} :StoreService} (app->APIHandlerServices app) {{conn :conn} :state :as store} (get-store :vulnerability) _ (es-helpers/load-file-bulk app conn "./test/data/indices/sample-vulnerability-150.json") _ (Thread/sleep 1000) cpe-match-strings ["cpe:2.3:h:juniper:ex8200\\/vc_\\(xre\\):-:*:*:*:*:*:*:*" "cpe:2.3:o:juniper:junos:14.1x53:*:*:*:*:*:*:*"] vulnerability-ids (sut/vulnerability-ids-affected-by-cpe-matches {:cpe-matches (map cpe/->cpe-match cpe-match-strings) :store store}) response (GET app "/ctia/vulnerability/cpe_match_strings" :query-params {:cpe23_match_strings cpe-match-strings} :headers {:Authorization "45c1f5e3f05d0"})] (is (not (realized? vulnerability-ids))) (is (= 200 (:status response))) (is (= #{"CVE-2018-0007" "CVE-2018-0024" "CVE-2018-0031"} (set (map :title (edn/read-string (:body response)))))))))) (deftest cpe-match-strings-paging-test (helpers/fixture-ctia-with-app (fn [app] (helpers/set-capabilities! app "foouser" ["foogroup"] "user" all-capabilities) (whoami-helpers/set-whoami-response app "45c1f5e3f05d0" "foouser" "foogroup" "user") (let [{{get-store :get-store} :StoreService} (app->APIHandlerServices app) {{conn :conn} :state} (get-store :vulnerability) _ (es-helpers/load-file-bulk app conn "./test/data/indices/sample-cpe-250.json") _ (Thread/sleep 1000) cpe-match-strings ["cpe:2.3:a:microsoft:edge:-:*:*:*:*:*:*:*"] results (loop [acc [] x-sort nil x-total-hits []] (let [{parsed-body :parsed-body {:strs [X-Sort X-Total-Hits]} :headers} (GET app "/ctia/vulnerability/cpe_match_strings" :query-params (if x-sort {:cpe23_match_strings cpe-match-strings "search_after" x-sort} {:cpe23_match_strings cpe-match-strings}) :headers {:Authorization "45c1f5e3f05d0"})] (if-let [next-x-sort (first (json/decode X-Sort))] (recur (concat acc parsed-body) next-x-sort (conj x-total-hits X-Total-Hits)) {:body (concat acc parsed-body) :x-total-hits (conj x-total-hits X-Total-Hits)})))] (is (= 250 (count (:body results))) "Should retrieve all the results.") (is (= ["100" "100" "50" "0"] (:x-total-hits results)) "Should retrieve three pages of data with a default page size of 100")))))
null
https://raw.githubusercontent.com/threatgrid/ctia/5e3644cb0b340465fdf43cab7176140d44855df9/test/ctia/entity/vulnerability_test.clj
clojure
(ns ctia.entity.vulnerability-test (:require [cheshire.core :as json] [clj-momo.test-helpers.core :as mth] [clojure.test :refer [deftest is join-fixtures use-fixtures]] [clojure.tools.reader.edn :as edn] [ctia.entity.vulnerability :as sut] [ctia.entity.vulnerability.cpe :as cpe] [ctia.test-helpers [access-control :refer [access-control-test]] [auth :refer [all-capabilities]] [core :as helpers :refer [GET]] [crud :refer [entity-crud-test]] [aggregate :refer [test-metric-routes]] [es :as es-helpers] [fake-whoami-service :as whoami-helpers] [http :refer [app->APIHandlerServices]] [store :refer [test-for-each-store-with-app]]] [ctim.examples.vulnerabilities :refer [new-vulnerability-maximal new-vulnerability-minimal]])) (use-fixtures :once (join-fixtures [mth/fixture-schema-validation whoami-helpers/fixture-server])) (deftest test-vulnerability-routes (test-for-each-store-with-app (fn [app] (helpers/set-capabilities! app "foouser" ["foogroup"] "user" all-capabilities) (whoami-helpers/set-whoami-response app "45c1f5e3f05d0" "foouser" "foogroup" "user") (entity-crud-test (into sut/vulnerability-entity {:app app :example new-vulnerability-maximal :headers {:Authorization "45c1f5e3f05d0"}}))))) (deftest test-vulnerability-routes-access-control (access-control-test "vulnerability" new-vulnerability-minimal true true test-for-each-store-with-app)) (deftest test-vulnerability-metric-routes (test-metric-routes (into sut/vulnerability-entity {:entity-minimal new-vulnerability-minimal :enumerable-fields sut/vulnerability-enumerable-fields :date-fields sut/vulnerability-histogram-fields}))) (deftest test-build-configurations-query (is (= (sut/build-configurations-query (map cpe/->cpe-match ["cpe:2.3:o:juniper:advanced_threat_prevention:*:*:*:*:*:*:*:*" "cpe:2.3:h:juniper:atp400:-:*:*:*:*:*:*:*"])) "configurations.nodes.cpe_match.cpe23Uri:cpe\\:2.3\\:o\\:juniper\\:advanced_threat_prevention* OR configurations.nodes.children.cpe_match.cpe23Uri:cpe\\:2.3\\:o\\:juniper\\:advanced_threat_prevention* OR configurations.nodes.cpe_match.cpe23Uri:cpe\\:2.3\\:h\\:juniper\\:atp400* OR configurations.nodes.children.cpe_match.cpe23Uri:cpe\\:2.3\\:h\\:juniper\\:atp400*"))) (deftest search-by-cpe-match-strings-test (helpers/fixture-ctia-with-app (fn [app] (helpers/set-capabilities! app "foouser" ["foogroup"] "user" all-capabilities) (whoami-helpers/set-whoami-response app "45c1f5e3f05d0" "foouser" "foogroup" "user") (let [{{get-store :get-store} :StoreService} (app->APIHandlerServices app) {{conn :conn} :state :as store} (get-store :vulnerability) _ (es-helpers/load-file-bulk app conn "./test/data/indices/sample-vulnerability-150.json") _ (Thread/sleep 1000) cpe-match-strings ["cpe:2.3:h:juniper:ex8200\\/vc_\\(xre\\):-:*:*:*:*:*:*:*" "cpe:2.3:o:juniper:junos:14.1x53:*:*:*:*:*:*:*"] vulnerability-ids (sut/vulnerability-ids-affected-by-cpe-matches {:cpe-matches (map cpe/->cpe-match cpe-match-strings) :store store}) response (GET app "/ctia/vulnerability/cpe_match_strings" :query-params {:cpe23_match_strings cpe-match-strings} :headers {:Authorization "45c1f5e3f05d0"})] (is (not (realized? vulnerability-ids))) (is (= 200 (:status response))) (is (= #{"CVE-2018-0007" "CVE-2018-0024" "CVE-2018-0031"} (set (map :title (edn/read-string (:body response)))))))))) (deftest cpe-match-strings-paging-test (helpers/fixture-ctia-with-app (fn [app] (helpers/set-capabilities! app "foouser" ["foogroup"] "user" all-capabilities) (whoami-helpers/set-whoami-response app "45c1f5e3f05d0" "foouser" "foogroup" "user") (let [{{get-store :get-store} :StoreService} (app->APIHandlerServices app) {{conn :conn} :state} (get-store :vulnerability) _ (es-helpers/load-file-bulk app conn "./test/data/indices/sample-cpe-250.json") _ (Thread/sleep 1000) cpe-match-strings ["cpe:2.3:a:microsoft:edge:-:*:*:*:*:*:*:*"] results (loop [acc [] x-sort nil x-total-hits []] (let [{parsed-body :parsed-body {:strs [X-Sort X-Total-Hits]} :headers} (GET app "/ctia/vulnerability/cpe_match_strings" :query-params (if x-sort {:cpe23_match_strings cpe-match-strings "search_after" x-sort} {:cpe23_match_strings cpe-match-strings}) :headers {:Authorization "45c1f5e3f05d0"})] (if-let [next-x-sort (first (json/decode X-Sort))] (recur (concat acc parsed-body) next-x-sort (conj x-total-hits X-Total-Hits)) {:body (concat acc parsed-body) :x-total-hits (conj x-total-hits X-Total-Hits)})))] (is (= 250 (count (:body results))) "Should retrieve all the results.") (is (= ["100" "100" "50" "0"] (:x-total-hits results)) "Should retrieve three pages of data with a default page size of 100")))))
5cce259848f670a71bb41492f5a8ee14c2c61672bd892187112bf29ae71f7e6a
ArulselvanMadhavan/haskell-first-principles
Addition.hs
module Addition where import Test.Hspec import Test.QuickCheck sayHello :: IO () sayHello = putStrLn "Hello" genBool :: Gen Bool genBool = choose (False, True) genBool' :: Gen Bool genBool' = elements [False, True] genOrdering :: Gen Ordering genOrdering = elements [LT, EQ, GT] genChar :: Gen Char genChar = elements ['a'..'z'] genTuple :: (Arbitrary a, Arbitrary b) => Gen (a, b) genTuple = do a <- arbitrary b <- arbitrary return (a, b) genThreeple :: (Arbitrary a, Arbitrary b, Arbitrary c) => Gen (a, b, c) genThreeple = do a <- arbitrary b <- arbitrary c <- arbitrary return (a, b, c) genEither :: (Arbitrary a, Arbitrary b) => Gen (Either a b) genEither = do a <- arbitrary b <- arbitrary elements [Left a, Right b] genMaybe :: Arbitrary a => Gen (Maybe a) genMaybe = do a <- arbitrary elements [Nothing, Just a] genMaybe' :: Arbitrary a => Gen (Maybe a) genMaybe' = do a <- arbitrary frequency [(1, return Nothing), (3, return (Just a))] dividedBy :: Integral a => a -> a -> (a, a) dividedBy num denom = go num denom 0 where go n d count | n < d = (count, n) | otherwise = go (n - d) d (count + 1) main :: IO () main = hspec $ do describe "Addition" $ do it "1 + 1 is greater than 1 " $ do (1 + 1) > 1 `shouldBe` True it "2 + 2 is equal to 4" $ do (2 + 2) `shouldBe` 4 describe "dividedBy" $ do it "4 divided By 2 should be 2" $ do (dividedBy 4 2) `shouldBe` (2, 0) it "x + 1 is always\ \greater than x" $ do property $ \x -> x + 1 > (x :: Int)
null
https://raw.githubusercontent.com/ArulselvanMadhavan/haskell-first-principles/06e0c71c502848c8e75c8109dd49c0954d815bba/chapter14/src/Addition.hs
haskell
module Addition where import Test.Hspec import Test.QuickCheck sayHello :: IO () sayHello = putStrLn "Hello" genBool :: Gen Bool genBool = choose (False, True) genBool' :: Gen Bool genBool' = elements [False, True] genOrdering :: Gen Ordering genOrdering = elements [LT, EQ, GT] genChar :: Gen Char genChar = elements ['a'..'z'] genTuple :: (Arbitrary a, Arbitrary b) => Gen (a, b) genTuple = do a <- arbitrary b <- arbitrary return (a, b) genThreeple :: (Arbitrary a, Arbitrary b, Arbitrary c) => Gen (a, b, c) genThreeple = do a <- arbitrary b <- arbitrary c <- arbitrary return (a, b, c) genEither :: (Arbitrary a, Arbitrary b) => Gen (Either a b) genEither = do a <- arbitrary b <- arbitrary elements [Left a, Right b] genMaybe :: Arbitrary a => Gen (Maybe a) genMaybe = do a <- arbitrary elements [Nothing, Just a] genMaybe' :: Arbitrary a => Gen (Maybe a) genMaybe' = do a <- arbitrary frequency [(1, return Nothing), (3, return (Just a))] dividedBy :: Integral a => a -> a -> (a, a) dividedBy num denom = go num denom 0 where go n d count | n < d = (count, n) | otherwise = go (n - d) d (count + 1) main :: IO () main = hspec $ do describe "Addition" $ do it "1 + 1 is greater than 1 " $ do (1 + 1) > 1 `shouldBe` True it "2 + 2 is equal to 4" $ do (2 + 2) `shouldBe` 4 describe "dividedBy" $ do it "4 divided By 2 should be 2" $ do (dividedBy 4 2) `shouldBe` (2, 0) it "x + 1 is always\ \greater than x" $ do property $ \x -> x + 1 > (x :: Int)
64fd243088c8b9fc8354a060e8aeb7bc6eec0a37cac154854eb3645b385cb3e0
TyOverby/mono
bonsai_web_ui_notifications.mli
open! Core open! Bonsai_web (** This is a notifications component that provides pretty and user-friendly(ish) notifications, with automatic fade-out & dismissal after a time span. *) type t val create * default = 15s -> ?dismiss_errors_automatically:bool Value.t (** default = false *) -> Source_code_position.t -> t Computation.t (** [add_error] will create a notification with [text] in primary focus and [error] pretty printed in small font (if provided). *) val add_error : ?error:Error.t -> t -> text:string -> unit Ui_effect.t (** [add_success] creates a notification with only [text] in primary focus. *) val add_success : t -> text:string -> unit Ui_effect.t module Notification_style : sig module type S = sig * These CSS classes are applied to the notifications that are generated by [ to_vdom ] . To customise the color of these notifications , set the [ background - color ] attribute to your desired color . [to_vdom]. To customise the color of these notifications, set the [background-color] attribute to your desired color. *) val error : string val success : string end type t = (module S) end * [ to_vdom ] constructs the vdom necessary to display these notifications . The styling required to display these notifications is handled for you via ppx_css . required to display these notifications is handled for you via ppx_css. *) val to_vdom : ?notification_style:Notification_style.t -> ?notification_extra_attr:Vdom.Attr.t -> t -> Vdom.Node.t
null
https://raw.githubusercontent.com/TyOverby/mono/7666c0328d194bf9a569fb65babc0486f2aaa40d/vendor/janestreet-bonsai/web_ui/notifications/src/bonsai_web_ui_notifications.mli
ocaml
* This is a notifications component that provides pretty and user-friendly(ish) notifications, with automatic fade-out & dismissal after a time span. * default = false * [add_error] will create a notification with [text] in primary focus and [error] pretty printed in small font (if provided). * [add_success] creates a notification with only [text] in primary focus.
open! Core open! Bonsai_web type t val create * default = 15s -> Source_code_position.t -> t Computation.t val add_error : ?error:Error.t -> t -> text:string -> unit Ui_effect.t val add_success : t -> text:string -> unit Ui_effect.t module Notification_style : sig module type S = sig * These CSS classes are applied to the notifications that are generated by [ to_vdom ] . To customise the color of these notifications , set the [ background - color ] attribute to your desired color . [to_vdom]. To customise the color of these notifications, set the [background-color] attribute to your desired color. *) val error : string val success : string end type t = (module S) end * [ to_vdom ] constructs the vdom necessary to display these notifications . The styling required to display these notifications is handled for you via ppx_css . required to display these notifications is handled for you via ppx_css. *) val to_vdom : ?notification_style:Notification_style.t -> ?notification_extra_attr:Vdom.Attr.t -> t -> Vdom.Node.t
4780f53c6f0c99cb41a2be51db4da8ce0dda4d589a39369eeb5c9c81044276bd
ept/compsci
tick3.ml
ML ASSESSED EXERCISES . TICK 3 SUBMISSION FROM M.A. KLEPPMANN Estimated time to complete : 20 mins . Actual time : 25 mins . ( not including extra work for Tick 3(asterisk ) ) (not including extra work for Tick 3(asterisk)) *) Note that in all three solutions , it is assumed that any list presented as an argument is of adequate length . Match exceptions are not caught . presented as an argument is of adequate length. Match exceptions are not caught. *) PROBLEM 1 . A function last(x ) that returns the last element of the list x. last ( ... ): time O(n ) and space O(1 ) ( tail - recursive ) hd(rev ( ... ) ): complexity of rev ( ) is significant , probably time O(n ) and space O(n ) ( implementation - dependent ) last(...): time O(n) and space O(1) (tail-recursive) hd(rev(...)): complexity of rev() is significant, probably time O(n) and space O(n) (implementation-dependent) *) fun last([x]) = x | last(y::z) = last(z); PROBLEM 2 . A function butLast(x ) that returns a list containing all elements of x but the last . butLast ( ... ): time O(n ) and space O(n ) rev(tl(rev ( ... ) ) ): probably time O(n ) and space O(n ) ( implementation - dependent ) PROBLEM 2. A function butLast(x) that returns a list containing all elements of x but the last. butLast(...): time O(n) and space O(n) rev(tl(rev(...))): probably time O(n) and space O(n) (implementation-dependent) *) fun butLast([x]) = [] | butLast(h::t) = h::butLast(t); PROBLEM 3 . A function nth(x , n ) that returns the n'th element of the list x. ( The head is counted as n=0 ) (The head is counted as n=0) *) fun nth(h::t, n) = if n=0 then h else nth(t, n-1); (****************************************************************************) (* EXTRA STUFF FOR TICK 3(asterisk) *) (* Function choose(k,xs) returns a list containing all possible k-element lists that can be drawn from xs, ignoring the order of list elements. Definitely not the most efficient solution, but it works. *) fun choose(k,x) = let fun ch(i, pre, s) = if (not(null(s))) andalso (i > 0) then ch(i-1, pre@[hd(s)], tl(s)) @ ch(i, pre, tl(s)) else if i = 0 then [pre] else [] in ch(k, [], x) end;
null
https://raw.githubusercontent.com/ept/compsci/ed666bb4cf52ac2af5c2d13894870bdc23dca237/ml/tick3.ml
ocaml
************************************************************************** EXTRA STUFF FOR TICK 3(asterisk) Function choose(k,xs) returns a list containing all possible k-element lists that can be drawn from xs, ignoring the order of list elements. Definitely not the most efficient solution, but it works.
ML ASSESSED EXERCISES . TICK 3 SUBMISSION FROM M.A. KLEPPMANN Estimated time to complete : 20 mins . Actual time : 25 mins . ( not including extra work for Tick 3(asterisk ) ) (not including extra work for Tick 3(asterisk)) *) Note that in all three solutions , it is assumed that any list presented as an argument is of adequate length . Match exceptions are not caught . presented as an argument is of adequate length. Match exceptions are not caught. *) PROBLEM 1 . A function last(x ) that returns the last element of the list x. last ( ... ): time O(n ) and space O(1 ) ( tail - recursive ) hd(rev ( ... ) ): complexity of rev ( ) is significant , probably time O(n ) and space O(n ) ( implementation - dependent ) last(...): time O(n) and space O(1) (tail-recursive) hd(rev(...)): complexity of rev() is significant, probably time O(n) and space O(n) (implementation-dependent) *) fun last([x]) = x | last(y::z) = last(z); PROBLEM 2 . A function butLast(x ) that returns a list containing all elements of x but the last . butLast ( ... ): time O(n ) and space O(n ) rev(tl(rev ( ... ) ) ): probably time O(n ) and space O(n ) ( implementation - dependent ) PROBLEM 2. A function butLast(x) that returns a list containing all elements of x but the last. butLast(...): time O(n) and space O(n) rev(tl(rev(...))): probably time O(n) and space O(n) (implementation-dependent) *) fun butLast([x]) = [] | butLast(h::t) = h::butLast(t); PROBLEM 3 . A function nth(x , n ) that returns the n'th element of the list x. ( The head is counted as n=0 ) (The head is counted as n=0) *) fun nth(h::t, n) = if n=0 then h else nth(t, n-1); fun choose(k,x) = let fun ch(i, pre, s) = if (not(null(s))) andalso (i > 0) then ch(i-1, pre@[hd(s)], tl(s)) @ ch(i, pre, tl(s)) else if i = 0 then [pre] else [] in ch(k, [], x) end;
89c6694d9a63aa96b4b7ade02a8a32f5304567d4c2f1eded9a85b2c899ad8cac
exoscale/seql
core.clj
(ns seql.core "Namespace kept for backward compatibility" (:require [seql.query :as query] [seql.env :as env] [seql.mutation :as mutation] [seql.listener :as listener])) (def ^:deprecated query "use `seql.query/execute`" #'query/execute) (def ^:deprecated mutate! "use `seql.mutation/mutate!`" #'mutation/mutate!) (defn ^:deprecated add-listener! "use `seql.listener/add-listener`" ([env mutation handler] (env/update-schema env listener/add-listener mutation mutation handler)) ([env mutation key handler] (env/update-schema env listener/add-listener mutation key handler))) (defn ^:deprecated remove-listener! "use `seql.listener/remove-listener`" ([env mutation] (env/update-schema env listener/remove-listener mutation mutation)) ([env mutation key] (env/update-schema env listener/remove-listener mutation key)))
null
https://raw.githubusercontent.com/exoscale/seql/7142132a5c364baf201936052095589489320e99/src/seql/core.clj
clojure
(ns seql.core "Namespace kept for backward compatibility" (:require [seql.query :as query] [seql.env :as env] [seql.mutation :as mutation] [seql.listener :as listener])) (def ^:deprecated query "use `seql.query/execute`" #'query/execute) (def ^:deprecated mutate! "use `seql.mutation/mutate!`" #'mutation/mutate!) (defn ^:deprecated add-listener! "use `seql.listener/add-listener`" ([env mutation handler] (env/update-schema env listener/add-listener mutation mutation handler)) ([env mutation key handler] (env/update-schema env listener/add-listener mutation key handler))) (defn ^:deprecated remove-listener! "use `seql.listener/remove-listener`" ([env mutation] (env/update-schema env listener/remove-listener mutation mutation)) ([env mutation key] (env/update-schema env listener/remove-listener mutation key)))
184060ab9238cad151f4a3a5a0bd43cdafba7739b7ad3ee56de588e36e924300
EwenG/replique
server.clj
(ns replique.server (:require [clojure.main :as m] [replique.utils :as utils] [replique.http :as http] [replique.tooling-msg :as tooling-msg]) (:import [java.net InetAddress Socket ServerSocket SocketException] [java.util.concurrent.locks ReentrantLock] [java.util.concurrent Executors])) (def ^:dynamic *session* nil) ;; lock protects servers (defonce ^:private lock (ReentrantLock.)) (defonce ^:private servers {}) (defmacro ^:private thread [^String name daemon & body] `(doto (Thread. (fn [] ~@body) ~name) (.setDaemon ~daemon) (.start))) (defn- required "Throw if opts does not contain prop." [opts prop] (when (nil? (get opts prop)) (throw (ex-info (str "Missing required socket server property " prop) opts)))) (defn- validate-opts "Validate server config options" [{:keys [name port accept] :as opts}] (doseq [prop [:name :port :accept]] (required opts prop)) (when (or (not (integer? port)) (not (< -1 port 65535))) (throw (ex-info (str "Invalid socket server port: " port) opts)))) (defn- accept-connection "Start accept function, to be invoked on a client thread, given: conn - client socket name - server name client-id - client identifier in - in stream out - out stream err - err stream accept - accept fn symbol to invoke args - to pass to accept-fn" [^Socket conn name client-id in out err accept args] (try (binding [*in* in *out* out *err* err *session* {:server name :client client-id}] (utils/with-lock lock (alter-var-root #'servers assoc-in [name :sessions client-id] {})) (require (symbol (namespace accept))) (let [accept-fn (resolve accept)] (apply accept-fn args))) (catch SocketException _disconnect) (finally (utils/with-lock lock (alter-var-root #'servers update-in [name :sessions] dissoc client-id)) (.close conn)))) ;; The caller is responsible for catching exceptions (defn send-response [out {:keys [status body content-type encoding]}] (http/send-and-close out status body content-type encoding)) (defn accept-connection-http [in out accept-http-fn] (when-let [request (try (http/read-request in) (catch Exception e (try (tooling-msg/uncaught-exception (Thread/currentThread) e) (http/send-and-close out 500 "Could not read request" "text/plain" "UTF-8") ;; Socket closed (catch Exception e (tooling-msg/uncaught-exception (Thread/currentThread) e))) nil))] (let [callback (partial send-response out)] (let [response (accept-http-fn request callback)] (if (instance? java.util.concurrent.Future response) ;; Response is sent asynchronously nil (let [{:keys [status body content-type encoding]} response] (try (http/send-and-close out status body content-type encoding) ;; Socket closed (catch Exception e (tooling-msg/uncaught-exception (Thread/currentThread) e))))))))) (defn make-http-reader [first-char in] (let [arr (byte-array 1) _ (aset arr 0 (byte first-char)) prepend-in (java.io.ByteArrayInputStream. arr)] (-> (java.io.SequenceInputStream. prepend-in in) (java.io.InputStreamReader.) (java.io.BufferedReader.)))) (defn start-server "Start a socket server given the specified opts: :address Host or address, string, defaults to loopback address :port Port, integer, required :name Name, required :accept Namespaced symbol of the accept function to invoke, required :args Vector of args to pass to accept function :bind-err Bind *err* to socket out stream?, defaults to true :server-daemon Is server thread a daemon?, defaults to true :client-daemon Are client threads daemons?, defaults to true Returns server socket." [opts] (validate-opts opts) (let [{:keys [address port name accept accept-http args bind-err server-daemon client-daemon] :or {bind-err true server-daemon true client-daemon true}} opts address (InetAddress/getByName address) ;; nil returns loopback socket (ServerSocket. port 0 address) _ (require (symbol (namespace accept-http))) accept-http-fn (resolve accept-http)] (utils/with-lock lock (alter-var-root #'servers assoc name {:name name, :socket socket, :sessions {}})) (thread (str "Clojure Server " name) server-daemon (try (loop [client-counter 0] (recur (when (not (.isClosed socket)) (try (let [conn (.accept socket) in (.getInputStream conn) out (.getOutputStream conn) client-id (str client-counter)] (let [first-char (.read in)] If the first char is \G , we assume the input stream contains an HTTP GET ;; request If the first char is \P , we assume the input stream contains an HTTP POST ;; request (case first-char ;; \G 71 (let [;; unread the char because it is part of the HTTP request in (make-http-reader first-char in)] (accept-connection-http in out accept-http-fn) client-counter) ;; \P 80 (let [;; unread the char because it is part of the HTTP request in (make-http-reader first-char in)] (accept-connection-http in out accept-http-fn) client-counter) (let [in (clojure.lang.LineNumberingPushbackReader. (java.io.InputStreamReader. in)) out (java.io.BufferedWriter. (java.io.OutputStreamWriter. out))] ;; Don't unread the char since the client sent a fake init char (thread (str "Clojure Connection " name " " client-id) client-daemon (accept-connection conn name client-id in out (if bind-err out *err*) accept args)) (inc client-counter))))) (catch SocketException _disconnect))))) (finally (utils/with-lock lock (alter-var-root #'servers dissoc name))))) socket))
null
https://raw.githubusercontent.com/EwenG/replique/45719ec95f463107f4c4ca79b7f83a7882b450cb/src/replique/server.clj
clojure
lock protects servers The caller is responsible for catching exceptions Socket closed Response is sent asynchronously Socket closed nil returns loopback request request \G unread the char because it is part of the HTTP request \P unread the char because it is part of the HTTP request Don't unread the char since the client sent a fake init char
(ns replique.server (:require [clojure.main :as m] [replique.utils :as utils] [replique.http :as http] [replique.tooling-msg :as tooling-msg]) (:import [java.net InetAddress Socket ServerSocket SocketException] [java.util.concurrent.locks ReentrantLock] [java.util.concurrent Executors])) (def ^:dynamic *session* nil) (defonce ^:private lock (ReentrantLock.)) (defonce ^:private servers {}) (defmacro ^:private thread [^String name daemon & body] `(doto (Thread. (fn [] ~@body) ~name) (.setDaemon ~daemon) (.start))) (defn- required "Throw if opts does not contain prop." [opts prop] (when (nil? (get opts prop)) (throw (ex-info (str "Missing required socket server property " prop) opts)))) (defn- validate-opts "Validate server config options" [{:keys [name port accept] :as opts}] (doseq [prop [:name :port :accept]] (required opts prop)) (when (or (not (integer? port)) (not (< -1 port 65535))) (throw (ex-info (str "Invalid socket server port: " port) opts)))) (defn- accept-connection "Start accept function, to be invoked on a client thread, given: conn - client socket name - server name client-id - client identifier in - in stream out - out stream err - err stream accept - accept fn symbol to invoke args - to pass to accept-fn" [^Socket conn name client-id in out err accept args] (try (binding [*in* in *out* out *err* err *session* {:server name :client client-id}] (utils/with-lock lock (alter-var-root #'servers assoc-in [name :sessions client-id] {})) (require (symbol (namespace accept))) (let [accept-fn (resolve accept)] (apply accept-fn args))) (catch SocketException _disconnect) (finally (utils/with-lock lock (alter-var-root #'servers update-in [name :sessions] dissoc client-id)) (.close conn)))) (defn send-response [out {:keys [status body content-type encoding]}] (http/send-and-close out status body content-type encoding)) (defn accept-connection-http [in out accept-http-fn] (when-let [request (try (http/read-request in) (catch Exception e (try (tooling-msg/uncaught-exception (Thread/currentThread) e) (http/send-and-close out 500 "Could not read request" "text/plain" "UTF-8") (catch Exception e (tooling-msg/uncaught-exception (Thread/currentThread) e))) nil))] (let [callback (partial send-response out)] (let [response (accept-http-fn request callback)] (if (instance? java.util.concurrent.Future response) nil (let [{:keys [status body content-type encoding]} response] (try (http/send-and-close out status body content-type encoding) (catch Exception e (tooling-msg/uncaught-exception (Thread/currentThread) e))))))))) (defn make-http-reader [first-char in] (let [arr (byte-array 1) _ (aset arr 0 (byte first-char)) prepend-in (java.io.ByteArrayInputStream. arr)] (-> (java.io.SequenceInputStream. prepend-in in) (java.io.InputStreamReader.) (java.io.BufferedReader.)))) (defn start-server "Start a socket server given the specified opts: :address Host or address, string, defaults to loopback address :port Port, integer, required :name Name, required :accept Namespaced symbol of the accept function to invoke, required :args Vector of args to pass to accept function :bind-err Bind *err* to socket out stream?, defaults to true :server-daemon Is server thread a daemon?, defaults to true :client-daemon Are client threads daemons?, defaults to true Returns server socket." [opts] (validate-opts opts) (let [{:keys [address port name accept accept-http args bind-err server-daemon client-daemon] :or {bind-err true server-daemon true client-daemon true}} opts socket (ServerSocket. port 0 address) _ (require (symbol (namespace accept-http))) accept-http-fn (resolve accept-http)] (utils/with-lock lock (alter-var-root #'servers assoc name {:name name, :socket socket, :sessions {}})) (thread (str "Clojure Server " name) server-daemon (try (loop [client-counter 0] (recur (when (not (.isClosed socket)) (try (let [conn (.accept socket) in (.getInputStream conn) out (.getOutputStream conn) client-id (str client-counter)] (let [first-char (.read in)] If the first char is \G , we assume the input stream contains an HTTP GET If the first char is \P , we assume the input stream contains an HTTP POST (case first-char in (make-http-reader first-char in)] (accept-connection-http in out accept-http-fn) client-counter) in (make-http-reader first-char in)] (accept-connection-http in out accept-http-fn) client-counter) (let [in (clojure.lang.LineNumberingPushbackReader. (java.io.InputStreamReader. in)) out (java.io.BufferedWriter. (java.io.OutputStreamWriter. out))] (thread (str "Clojure Connection " name " " client-id) client-daemon (accept-connection conn name client-id in out (if bind-err out *err*) accept args)) (inc client-counter))))) (catch SocketException _disconnect))))) (finally (utils/with-lock lock (alter-var-root #'servers dissoc name))))) socket))
ce8b0d34a13dc8177b81c1d71fc304056bc56ddef8a643d4d83ee7dc312ae04c
tisnik/clojure-examples
core_test.clj
; ( C ) Copyright 2015 , 2020 ; ; 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 seesaw10.core-test (:require [clojure.test :refer :all] [seesaw10.core :refer :all])) (deftest a-test (testing "FIXME, I fail." (is (= 0 1))))
null
https://raw.githubusercontent.com/tisnik/clojure-examples/984af4a3e20d994b4f4989678ee1330e409fdae3/seesaw10/test/seesaw10/core_test.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 2015 , 2020 -v10.html (ns seesaw10.core-test (:require [clojure.test :refer :all] [seesaw10.core :refer :all])) (deftest a-test (testing "FIXME, I fail." (is (= 0 1))))
c541b9bc65e3d81726fe054fe4ddf2fe180314a506964a184da8984c8c92137d
jeffshrager/biobike
logic-comparison-doc.lisp
-*- Package : bbi ; mode : lisp ; base : 10 ; Syntax : Common - Lisp ; -*- (in-package :bbi) ;;; +=========================================================================+ | Copyright ( c ) 2002 , 2003 , 2004 JP , , | ;;; | | ;;; | 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. | ;;; +=========================================================================+ Author : JP , and . (eval-when (:compile-toplevel :load-toplevel :execute) (import '( com.biobike.help:document-module com.biobike.help:document-function) :bbi)) (DOCUMENT-MODULE flow-logic "Functions dealing with program flow and logical choices" (:keywords :logic :predicate :true :false) (:display-modes :bbl) (:submodules logical-comparison logical-connectives loops-and-conditional-execution other-logic-functions) #.`(:FUNCTIONS apply-function repeat-function if-false if-true for-each true? both either raise-error)) (DOCUMENT-MODULE logical-comparison "Properties of genes and proteins" (:keywords :compare :greater :less) (:display-modes :bbl) (:toplevel? nil) #.`(:FUNCTIONS true? same all-same all-true any-true all-false any-false > >= = < <= greater-than less-than not)) (DOCUMENT-MODULE logical-connectives "Properties of genes and proteins" (:keywords :compare :greater :less) (:display-modes :bbl) (:toplevel? nil) #.`(:FUNCTIONS both neither and or) (:SEE-ALSO (:module other-logic-functions)) ) (DOCUMENT-MODULE loops-and-conditional-execution "Iteration and control over the flow of logic" (:keywords :if :condition :branch :loop :iteration :iterative) (:display-modes :bbl) (:toplevel? nil) #.`(:FUNCTIONS when unless if-false if-true loop for-each apply-function Condition Case typecase return return-from when-value-of)) (DOCUMENT-MODULE other-logic-functions "Alternate functions that might speed execution" (:keywords) (:display-modes :bbl) (:toplevel? nil) #.`(:FUNCTIONS = < <= > >= and or))
null
https://raw.githubusercontent.com/jeffshrager/biobike/5313ec1fe8e82c21430d645e848ecc0386436f57/BioLisp/Doc/bbldf/logic-comparison-doc.lisp
lisp
mode : lisp ; base : 10 ; Syntax : Common - Lisp ; -*- +=========================================================================+ | | | Permission is hereby granted, free of charge, to any person obtaining | | a copy of this software and associated documentation files (the | | without limitation the rights to use, copy, modify, merge, publish, | | the following conditions: | | | | The above copyright notice and this permission notice shall be included | | | | 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 | | TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE | | SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | +=========================================================================+
(in-package :bbi) | Copyright ( c ) 2002 , 2003 , 2004 JP , , | | " Software " ) , to deal in the Software without restriction , including | | distribute , sublicense , and/or sell copies of the Software , and to | | permit persons to whom the Software is furnished to do so , subject to | | in all copies or substantial portions of the Software . | | THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , | | CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT , | Author : JP , and . (eval-when (:compile-toplevel :load-toplevel :execute) (import '( com.biobike.help:document-module com.biobike.help:document-function) :bbi)) (DOCUMENT-MODULE flow-logic "Functions dealing with program flow and logical choices" (:keywords :logic :predicate :true :false) (:display-modes :bbl) (:submodules logical-comparison logical-connectives loops-and-conditional-execution other-logic-functions) #.`(:FUNCTIONS apply-function repeat-function if-false if-true for-each true? both either raise-error)) (DOCUMENT-MODULE logical-comparison "Properties of genes and proteins" (:keywords :compare :greater :less) (:display-modes :bbl) (:toplevel? nil) #.`(:FUNCTIONS true? same all-same all-true any-true all-false any-false > >= = < <= greater-than less-than not)) (DOCUMENT-MODULE logical-connectives "Properties of genes and proteins" (:keywords :compare :greater :less) (:display-modes :bbl) (:toplevel? nil) #.`(:FUNCTIONS both neither and or) (:SEE-ALSO (:module other-logic-functions)) ) (DOCUMENT-MODULE loops-and-conditional-execution "Iteration and control over the flow of logic" (:keywords :if :condition :branch :loop :iteration :iterative) (:display-modes :bbl) (:toplevel? nil) #.`(:FUNCTIONS when unless if-false if-true loop for-each apply-function Condition Case typecase return return-from when-value-of)) (DOCUMENT-MODULE other-logic-functions "Alternate functions that might speed execution" (:keywords) (:display-modes :bbl) (:toplevel? nil) #.`(:FUNCTIONS = < <= > >= and or))
f3f532400e7b5f473d77a0bb6235950931478863dfca05caf286bfb99cde7eab
plumatic/grab-bag
home.cljs
(ns dashboard.home (:require-macros [om-tools.core :refer [defcomponent]] [cljs.core.async.macros :refer [go go-loop]]) (:require [clojure.string :as str] [schema.utils :as utils] [om.core :as om :include-macros true] [om-tools.dom :as dom :include-macros true] [d3-tools.core :as d3] [tubes.core :as t] [dommy.core :as dommy] [cljs.core.async :as async :refer [<!]] [cljs-http.client :as http] [cljs-http.util :as http-util] [cljs-request.core :as cljs-request] [schema.core :as s])) (defn fetch-full-data [] (http/request {:uri "/data" :headers {"Content-Type" "application/edn"} :method :get})) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Components (defn setup-scale [scale minx maxx miny maxy] (-> scale (.domain #js [minx maxx]) (.range #js [miny maxy]))) (def +colors+ ["#EA5506" "#2CA9E1" "#9DB200" "coral" "olive" "black" "chartreuse" "darkblue" "aqua" "gray" "hotpink"]) (defn path-str [data xscale yscale] (when (seq data) (str "M " (str/join "L " (for [[x y] data] (str (xscale x) " " (yscale y) " ")))))) (defn last-full-datum [data] (let [[last-ts :as last-datum] (last data) day-ms 86400000] (if (= last-ts (* day-ms (.floor js/Math (/ (.getTime (js/Date.)) day-ms)))) (->> data (drop-last 1) last) last-datum))) (def d3-time-format* "A copy of d3's time format fn, which isn't exposed." (.multi js/d3.time.format (clj->js [[".%L" #(.getMilliseconds %)] [":%S" #(.getSeconds %)] ["%I:%M" #(.getMinutes %)] ["%I %p" #(.getHours %)] ["%a %d" #(and (not= (.getDay %) 0) (not= (.getDate %) 1))] ["%b %d" #(not= (.getDate %) 1)] ["%B" #(.getMonth %)] ["%Y" (constantly true)]]))) (defn d3-time-format-utc [date] (let [d (js/Date. date)] (d3-time-format* (js/Date. (+ date (* 60 1000 (.getTimezoneOffset (js/Date. date)))))))) (defcomponent timeseries-graph [series owner opts] (init-state [_] {:mouse-pos nil :active? false}) (render-state [_ state] (let [{:keys [mouse-pos active?]} state w (:width opts 800) h (:height opts 400) h-axis-space 30 v-axis-space 30 legend-space 75 ymax (- h v-axis-space) xmax (- w h-axis-space legend-space) all-data (mapcat val series) xscale (let [xs (map first all-data)] (setup-scale (.scale (.-time js/d3)) (apply min xs) (apply max xs) 0 xmax)) yscale (setup-scale (.linear (.-scale js/d3)) 0 (* 1.05 (apply max (map second all-data))) ymax 0) primary-series (some #{:total} (keys series)) focus-x (if mouse-pos (apply min-key #(.abs js/Math (- (first mouse-pos) (xscale %))) (map first all-data)) (->> series vals (map (comp first last-full-datum)) (apply max)))] (dom/div ;; Reactive class names don't work within svg. {:class (if active? "active" "inactive")} (dom/svg {:width w :height h :on-mouse-move (fn [e] (let [{:keys [left top]} (dommy/bounding-client-rect (.-currentTarget e)) cx (- (.-clientX e) left h-axis-space) cy (- (.-clientY e) top)] (om/set-state! owner :active? true) (om/set-state! owner :mouse-pos (when (and (<= 0 cx xmax) (<= 0 cy ymax)) [cx cy])))) :on-mouse-out #(do (om/set-state! owner :mouse-pos nil) (om/set-state! owner :active? false))} (dom/g {:transform (utils/format* "translate(%s,%s)" h-axis-space 0)} (dom/g {:class "rule"} (let [nxticks (/ w 120)] (for [tick (.ticks xscale nxticks) :let [x (xscale tick) formatter (.tickFormat xscale nxticks)]] (dom/g {:class "xrule"} (dom/line {:x1 x :y1 0 :x2 x :y2 ymax}) (dom/text {:x x :y (+ 15 ymax)} (formatter tick))))) (for [tick (.ticks yscale (/ h 50)) :let [y (yscale tick) formatter (.format js/d3 "s")]] (dom/g {:class "yrule"} (dom/line {:x1 0 :y1 y :x2 xmax :y2 y}) (dom/text {:x -3 :y (+ y 5)} (formatter tick))))) (dom/g {:class "xrule"} (dom/text {:class "serieslabel" :x (+ xmax (/ legend-space 2)) :y (+ 15 ymax)} (d3-time-format-utc focus-x))) (for [[i [label data]] (->> series (sort-by #(apply max (map second (second %)))) reverse (map vector (range))) :let [[focus-x focus-y] (first (filter #(= (first %) focus-x) data)) color (+colors+ i)]] (dom/g {:class (if (or (not primary-series) (= label primary-series)) "primary" "secondary")} (dom/path {:class "line" :fill "none" :stroke color :d (path-str data xscale yscale)}) (dom/circle {:class "line" :cx (xscale focus-x) :cy (yscale focus-y) :r 3 :fill color :stroke color :stroke-width 0.5}) (dom/text {:class "serieslabel" :x (+ xmax (/ legend-space 2)) :y (+ 10 (* 45 i))} (name label)) (dom/text {:class "seriespoint" :x (+ xmax (/ legend-space 2)) :y (+ 35 (* 45 i)) :fill color} (let [rounded (.round js/Math focus-y)] (if (< rounded 1000) (str rounded) ((.format js/d3 ".3s") rounded)))))))))))) (defcomponent titled-graph [series owner opts] (render [_] (dom/div {:class "graphtitles"} (dom/h4 (:title opts)) (om/build timeseries-graph series {:opts (dissoc opts :title)})))) (defn grid [& rows] (dom/table (for [row rows] (dom/tr (for [x row] (dom/td x)))))) (defn top-nav-item [text url] (dom/span {:class "topnavitem"} (dom/a {:href url} text) " ")) (defcomponent app [data owner] (render [_] (dom/div {:class "wrapper"} (dom/div {:class "topnav"} (for [k [:retention :notification :experiments :admin]] (top-nav-item (name k) (str "/" (name k)))) (top-nav-item "ranker-comparison" "/admin/ranking-metrics/compare?days=2")) (if (empty? data) (dom/h3 "Loading...") (dom/div {:class "content"} (grid [(om/build titled-graph {:crashes (:hockey-crashes data)} {:opts {:title "hockey crashes" :width 900 :height 200}}) (om/build titled-graph (:real-time-history data) {:opts {:title "real-time user counts" :width 900 :height 200}})]) (apply grid (for [client ["iphone" "web" "android"]] (cons (om/build titled-graph (get-in data [:signups client]) {:opts {:title (str "signups on " client) :width 450 :height 200}}) (for [period [:daily :weekly :monthly]] (om/build titled-graph (get-in data [:active-users client period]) {:opts {:title (str (name period) " active users on " client) :width 450 :height 200}})))))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Public & Export (defn ^:export init [] (let [data (atom {}) target (.-body js/document)] (om/root app data {:target target}) (go-loop [] (reset! data (:body (<! (fetch-full-data)))) (<! (async/timeout (* 1000 60))) (recur))))
null
https://raw.githubusercontent.com/plumatic/grab-bag/a15e943322fbbf6f00790ce5614ba6f90de1a9b5/service/dashboard/src/cljs/dashboard/home.cljs
clojure
Components Reactive class names don't work within svg. Public & Export
(ns dashboard.home (:require-macros [om-tools.core :refer [defcomponent]] [cljs.core.async.macros :refer [go go-loop]]) (:require [clojure.string :as str] [schema.utils :as utils] [om.core :as om :include-macros true] [om-tools.dom :as dom :include-macros true] [d3-tools.core :as d3] [tubes.core :as t] [dommy.core :as dommy] [cljs.core.async :as async :refer [<!]] [cljs-http.client :as http] [cljs-http.util :as http-util] [cljs-request.core :as cljs-request] [schema.core :as s])) (defn fetch-full-data [] (http/request {:uri "/data" :headers {"Content-Type" "application/edn"} :method :get})) (defn setup-scale [scale minx maxx miny maxy] (-> scale (.domain #js [minx maxx]) (.range #js [miny maxy]))) (def +colors+ ["#EA5506" "#2CA9E1" "#9DB200" "coral" "olive" "black" "chartreuse" "darkblue" "aqua" "gray" "hotpink"]) (defn path-str [data xscale yscale] (when (seq data) (str "M " (str/join "L " (for [[x y] data] (str (xscale x) " " (yscale y) " ")))))) (defn last-full-datum [data] (let [[last-ts :as last-datum] (last data) day-ms 86400000] (if (= last-ts (* day-ms (.floor js/Math (/ (.getTime (js/Date.)) day-ms)))) (->> data (drop-last 1) last) last-datum))) (def d3-time-format* "A copy of d3's time format fn, which isn't exposed." (.multi js/d3.time.format (clj->js [[".%L" #(.getMilliseconds %)] [":%S" #(.getSeconds %)] ["%I:%M" #(.getMinutes %)] ["%I %p" #(.getHours %)] ["%a %d" #(and (not= (.getDay %) 0) (not= (.getDate %) 1))] ["%b %d" #(not= (.getDate %) 1)] ["%B" #(.getMonth %)] ["%Y" (constantly true)]]))) (defn d3-time-format-utc [date] (let [d (js/Date. date)] (d3-time-format* (js/Date. (+ date (* 60 1000 (.getTimezoneOffset (js/Date. date)))))))) (defcomponent timeseries-graph [series owner opts] (init-state [_] {:mouse-pos nil :active? false}) (render-state [_ state] (let [{:keys [mouse-pos active?]} state w (:width opts 800) h (:height opts 400) h-axis-space 30 v-axis-space 30 legend-space 75 ymax (- h v-axis-space) xmax (- w h-axis-space legend-space) all-data (mapcat val series) xscale (let [xs (map first all-data)] (setup-scale (.scale (.-time js/d3)) (apply min xs) (apply max xs) 0 xmax)) yscale (setup-scale (.linear (.-scale js/d3)) 0 (* 1.05 (apply max (map second all-data))) ymax 0) primary-series (some #{:total} (keys series)) focus-x (if mouse-pos (apply min-key #(.abs js/Math (- (first mouse-pos) (xscale %))) (map first all-data)) (->> series vals (map (comp first last-full-datum)) (apply max)))] (dom/div {:class (if active? "active" "inactive")} (dom/svg {:width w :height h :on-mouse-move (fn [e] (let [{:keys [left top]} (dommy/bounding-client-rect (.-currentTarget e)) cx (- (.-clientX e) left h-axis-space) cy (- (.-clientY e) top)] (om/set-state! owner :active? true) (om/set-state! owner :mouse-pos (when (and (<= 0 cx xmax) (<= 0 cy ymax)) [cx cy])))) :on-mouse-out #(do (om/set-state! owner :mouse-pos nil) (om/set-state! owner :active? false))} (dom/g {:transform (utils/format* "translate(%s,%s)" h-axis-space 0)} (dom/g {:class "rule"} (let [nxticks (/ w 120)] (for [tick (.ticks xscale nxticks) :let [x (xscale tick) formatter (.tickFormat xscale nxticks)]] (dom/g {:class "xrule"} (dom/line {:x1 x :y1 0 :x2 x :y2 ymax}) (dom/text {:x x :y (+ 15 ymax)} (formatter tick))))) (for [tick (.ticks yscale (/ h 50)) :let [y (yscale tick) formatter (.format js/d3 "s")]] (dom/g {:class "yrule"} (dom/line {:x1 0 :y1 y :x2 xmax :y2 y}) (dom/text {:x -3 :y (+ y 5)} (formatter tick))))) (dom/g {:class "xrule"} (dom/text {:class "serieslabel" :x (+ xmax (/ legend-space 2)) :y (+ 15 ymax)} (d3-time-format-utc focus-x))) (for [[i [label data]] (->> series (sort-by #(apply max (map second (second %)))) reverse (map vector (range))) :let [[focus-x focus-y] (first (filter #(= (first %) focus-x) data)) color (+colors+ i)]] (dom/g {:class (if (or (not primary-series) (= label primary-series)) "primary" "secondary")} (dom/path {:class "line" :fill "none" :stroke color :d (path-str data xscale yscale)}) (dom/circle {:class "line" :cx (xscale focus-x) :cy (yscale focus-y) :r 3 :fill color :stroke color :stroke-width 0.5}) (dom/text {:class "serieslabel" :x (+ xmax (/ legend-space 2)) :y (+ 10 (* 45 i))} (name label)) (dom/text {:class "seriespoint" :x (+ xmax (/ legend-space 2)) :y (+ 35 (* 45 i)) :fill color} (let [rounded (.round js/Math focus-y)] (if (< rounded 1000) (str rounded) ((.format js/d3 ".3s") rounded)))))))))))) (defcomponent titled-graph [series owner opts] (render [_] (dom/div {:class "graphtitles"} (dom/h4 (:title opts)) (om/build timeseries-graph series {:opts (dissoc opts :title)})))) (defn grid [& rows] (dom/table (for [row rows] (dom/tr (for [x row] (dom/td x)))))) (defn top-nav-item [text url] (dom/span {:class "topnavitem"} (dom/a {:href url} text) " ")) (defcomponent app [data owner] (render [_] (dom/div {:class "wrapper"} (dom/div {:class "topnav"} (for [k [:retention :notification :experiments :admin]] (top-nav-item (name k) (str "/" (name k)))) (top-nav-item "ranker-comparison" "/admin/ranking-metrics/compare?days=2")) (if (empty? data) (dom/h3 "Loading...") (dom/div {:class "content"} (grid [(om/build titled-graph {:crashes (:hockey-crashes data)} {:opts {:title "hockey crashes" :width 900 :height 200}}) (om/build titled-graph (:real-time-history data) {:opts {:title "real-time user counts" :width 900 :height 200}})]) (apply grid (for [client ["iphone" "web" "android"]] (cons (om/build titled-graph (get-in data [:signups client]) {:opts {:title (str "signups on " client) :width 450 :height 200}}) (for [period [:daily :weekly :monthly]] (om/build titled-graph (get-in data [:active-users client period]) {:opts {:title (str (name period) " active users on " client) :width 450 :height 200}})))))))))) (defn ^:export init [] (let [data (atom {}) target (.-body js/document)] (om/root app data {:target target}) (go-loop [] (reset! data (:body (<! (fetch-full-data)))) (<! (async/timeout (* 1000 60))) (recur))))
84327f4275f36d06971e5f6d6423b8da1a5e05aaea6dcfb70bf4be89f94ffc66
master/ejabberd
ejabberd_sm.erl
%%%---------------------------------------------------------------------- File : Author : < > %%% Purpose : Session manager Created : 24 Nov 2002 by < > %%% %%% ejabberd , Copyright ( C ) 2002 - 2012 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_sm). -author(''). -behaviour(gen_server). %% API -export([start_link/0, route/3, open_session/5, close_session/4, check_in_subscription/6, bounce_offline_message/3, disconnect_removed_user/2, get_user_resources/2, set_presence/7, unset_presence/6, close_session_unset_presence/5, dirty_get_sessions_list/0, dirty_get_my_sessions_list/0, get_vh_session_list/1, get_vh_session_number/1, register_iq_handler/4, register_iq_handler/5, unregister_iq_handler/2, force_update_presence/1, connected_users/0, connected_users_number/0, user_resources/2, get_session_pid/3, get_user_info/3, get_user_ip/3, is_existing_resource/3 ]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -include("ejabberd.hrl"). -include("jlib.hrl"). -include("ejabberd_commands.hrl"). -include("mod_privacy.hrl"). -record(session, {sid, usr, us, priority, info}). -record(session_counter, {vhost, count}). -record(state, {}). %% default value for the maximum number of user connections -define(MAX_USER_SESSIONS, infinity). %%==================================================================== %% API %%==================================================================== %%-------------------------------------------------------------------- Function : start_link ( ) - > { ok , Pid } | ignore | { error , Error } %% Description: Starts the server %%-------------------------------------------------------------------- start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). route(From, To, Packet) -> case catch do_route(From, To, Packet) of {'EXIT', Reason} -> ?ERROR_MSG("~p~nwhen processing: ~p", [Reason, {From, To, Packet}]); _ -> ok end. open_session(SID, User, Server, Resource, Info) -> set_session(SID, User, Server, Resource, undefined, Info), mnesia:dirty_update_counter(session_counter, jlib:nameprep(Server), 1), check_for_sessions_to_replace(User, Server, Resource), JID = jlib:make_jid(User, Server, Resource), ejabberd_hooks:run(sm_register_connection_hook, JID#jid.lserver, [SID, JID, Info]). close_session(SID, User, Server, Resource) -> Info = case mnesia:dirty_read({session, SID}) of [] -> []; [#session{info=I}] -> I end, F = fun() -> mnesia:delete({session, SID}), mnesia:dirty_update_counter(session_counter, jlib:nameprep(Server), -1) end, mnesia:sync_dirty(F), JID = jlib:make_jid(User, Server, Resource), ejabberd_hooks:run(sm_remove_connection_hook, JID#jid.lserver, [SID, JID, Info]). check_in_subscription(Acc, User, Server, _JID, _Type, _Reason) -> case ejabberd_auth:is_user_exists(User, Server) of true -> Acc; false -> {stop, false} end. bounce_offline_message(From, To, Packet) -> Err = jlib:make_error_reply(Packet, ?ERR_SERVICE_UNAVAILABLE), ejabberd_router:route(To, From, Err), stop. disconnect_removed_user(User, Server) -> ejabberd_sm:route(jlib:make_jid("", "", ""), jlib:make_jid(User, Server, ""), {xmlelement, "broadcast", [], [{exit, "User removed"}]}). get_user_resources(User, Server) -> LUser = jlib:nodeprep(User), LServer = jlib:nameprep(Server), US = {LUser, LServer}, case catch mnesia:dirty_index_read(session, US, #session.us) of {'EXIT', _Reason} -> []; Ss -> [element(3, S#session.usr) || S <- clean_session_list(Ss)] end. get_user_ip(User, Server, Resource) -> LUser = jlib:nodeprep(User), LServer = jlib:nameprep(Server), LResource = jlib:resourceprep(Resource), USR = {LUser, LServer, LResource}, case mnesia:dirty_index_read(session, USR, #session.usr) of [] -> undefined; Ss -> Session = lists:max(Ss), proplists:get_value(ip, Session#session.info) end. get_user_info(User, Server, Resource) -> LUser = jlib:nodeprep(User), LServer = jlib:nameprep(Server), LResource = jlib:resourceprep(Resource), USR = {LUser, LServer, LResource}, case mnesia:dirty_index_read(session, USR, #session.usr) of [] -> offline; Ss -> Session = lists:max(Ss), Node = node(element(2, Session#session.sid)), Conn = proplists:get_value(conn, Session#session.info), IP = proplists:get_value(ip, Session#session.info), [{node, Node}, {conn, Conn}, {ip, IP}] end. set_presence(SID, User, Server, Resource, Priority, Presence, Info) -> set_session(SID, User, Server, Resource, Priority, Info), ejabberd_hooks:run(set_presence_hook, jlib:nameprep(Server), [User, Server, Resource, Presence]). unset_presence(SID, User, Server, Resource, Status, Info) -> set_session(SID, User, Server, Resource, undefined, Info), ejabberd_hooks:run(unset_presence_hook, jlib:nameprep(Server), [User, Server, Resource, Status]). close_session_unset_presence(SID, User, Server, Resource, Status) -> close_session(SID, User, Server, Resource), ejabberd_hooks:run(unset_presence_hook, jlib:nameprep(Server), [User, Server, Resource, Status]). get_session_pid(User, Server, Resource) -> LUser = jlib:nodeprep(User), LServer = jlib:nameprep(Server), LResource = jlib:resourceprep(Resource), USR = {LUser, LServer, LResource}, case catch mnesia:dirty_index_read(session, USR, #session.usr) of [#session{sid = {_, Pid}}] -> Pid; _ -> none end. dirty_get_sessions_list() -> mnesia:dirty_select( session, [{#session{usr = '$1', _ = '_'}, [], ['$1']}]). dirty_get_my_sessions_list() -> mnesia:dirty_select( session, [{#session{sid = {'_', '$1'}, _ = '_'}, [{'==', {node, '$1'}, node()}], ['$_']}]). get_vh_session_list(Server) -> LServer = jlib:nameprep(Server), mnesia:dirty_select( session, [{#session{usr = '$1', _ = '_'}, [{'==', {element, 2, '$1'}, LServer}], ['$1']}]). get_vh_session_number(Server) -> LServer = jlib:nameprep(Server), Query = mnesia:dirty_select( session_counter, [{#session_counter{vhost = LServer, count = '$1'}, [], ['$1']}]), case Query of [Count] -> Count; _ -> 0 end. register_iq_handler(Host, XMLNS, Module, Fun) -> ejabberd_sm ! {register_iq_handler, Host, XMLNS, Module, Fun}. register_iq_handler(Host, XMLNS, Module, Fun, Opts) -> ejabberd_sm ! {register_iq_handler, Host, XMLNS, Module, Fun, Opts}. unregister_iq_handler(Host, XMLNS) -> ejabberd_sm ! {unregister_iq_handler, Host, XMLNS}. %%==================================================================== %% gen_server callbacks %%==================================================================== %%-------------------------------------------------------------------- %% Function: init(Args) -> {ok, State} | { ok , State , Timeout } | %% ignore | %% {stop, Reason} %% Description: Initiates the server %%-------------------------------------------------------------------- init([]) -> update_tables(), mnesia:create_table(session, [{ram_copies, [node()]}, {attributes, record_info(fields, session)}]), mnesia:create_table(session_counter, [{ram_copies, [node()]}, {attributes, record_info(fields, session_counter)}]), mnesia:add_table_index(session, usr), mnesia:add_table_index(session, us), mnesia:add_table_copy(session, node(), ram_copies), mnesia:add_table_copy(session_counter, node(), ram_copies), mnesia:subscribe(system), ets:new(sm_iqtable, [named_table]), lists:foreach( fun(Host) -> ejabberd_hooks:add(roster_in_subscription, Host, ejabberd_sm, check_in_subscription, 20), ejabberd_hooks:add(offline_message_hook, Host, ejabberd_sm, bounce_offline_message, 100), ejabberd_hooks:add(remove_user, Host, ejabberd_sm, disconnect_removed_user, 100) end, ?MYHOSTS), ejabberd_commands:register_commands(commands()), {ok, #state{}}. %%-------------------------------------------------------------------- Function : % % handle_call(Request , From , State ) - > { reply , Reply , State } | { reply , Reply , State , Timeout } | { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, Reply, State} | %% {stop, Reason, State} %% Description: Handling call messages %%-------------------------------------------------------------------- handle_call(_Request, _From, State) -> Reply = ok, {reply, Reply, State}. %%-------------------------------------------------------------------- Function : handle_cast(Msg , State ) - > { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, State} %% Description: Handling cast messages %%-------------------------------------------------------------------- handle_cast(_Msg, State) -> {noreply, State}. %%-------------------------------------------------------------------- Function : handle_info(Info , State ) - > { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, State} %% Description: Handling all non call/cast messages %%-------------------------------------------------------------------- handle_info({route, From, To, Packet}, State) -> case catch do_route(From, To, Packet) of {'EXIT', Reason} -> ?ERROR_MSG("~p~nwhen processing: ~p", [Reason, {From, To, Packet}]); _ -> ok end, {noreply, State}; handle_info({mnesia_system_event, {mnesia_down, Node}}, State) -> recount_session_table(Node), {noreply, State}; handle_info({register_iq_handler, Host, XMLNS, Module, Function}, State) -> ets:insert(sm_iqtable, {{XMLNS, Host}, Module, Function}), {noreply, State}; handle_info({register_iq_handler, Host, XMLNS, Module, Function, Opts}, State) -> ets:insert(sm_iqtable, {{XMLNS, Host}, Module, Function, Opts}), {noreply, State}; handle_info({unregister_iq_handler, Host, XMLNS}, State) -> case ets:lookup(sm_iqtable, {XMLNS, Host}) of [{_, Module, Function, Opts}] -> gen_iq_handler:stop_iq_handler(Module, Function, Opts); _ -> ok end, ets:delete(sm_iqtable, {XMLNS, Host}), {noreply, State}; handle_info(_Info, State) -> {noreply, State}. %%-------------------------------------------------------------------- %% Function: terminate(Reason, State) -> void() %% Description: This function is called by a gen_server when it is about to %% terminate. It should be the opposite of Module:init/1 and do any necessary %% cleaning up. When it returns, the gen_server terminates with Reason. %% The return value is ignored. %%-------------------------------------------------------------------- terminate(_Reason, _State) -> ejabberd_commands:unregister_commands(commands()), ok. %%-------------------------------------------------------------------- Func : code_change(OldVsn , State , Extra ) - > { ok , NewState } %% Description: Convert process state when code is changed %%-------------------------------------------------------------------- code_change(_OldVsn, State, _Extra) -> {ok, State}. %%-------------------------------------------------------------------- Internal functions %%-------------------------------------------------------------------- set_session(SID, User, Server, Resource, Priority, Info) -> LUser = jlib:nodeprep(User), LServer = jlib:nameprep(Server), LResource = jlib:resourceprep(Resource), US = {LUser, LServer}, USR = {LUser, LServer, LResource}, F = fun() -> mnesia:write(#session{sid = SID, usr = USR, us = US, priority = Priority, info = Info}) end, mnesia:sync_dirty(F). Recalculates alive sessions when goes down and updates session and session_counter tables recount_session_table(Node) -> F = fun() -> Es = mnesia:select( session, [{#session{sid = {'_', '$1'}, _ = '_'}, [{'==', {node, '$1'}, Node}], ['$_']}]), lists:foreach(fun(E) -> mnesia:delete({session, E#session.sid}) end, Es), %% reset session_counter table with active sessions mnesia:clear_table(session_counter), lists:foreach(fun(Server) -> LServer = jlib:nameprep(Server), Hs = mnesia:select(session, [{#session{usr = '$1', _ = '_'}, [{'==', {element, 2, '$1'}, LServer}], ['$1']}]), mnesia:write( #session_counter{vhost = LServer, count = length(Hs)}) end, ?MYHOSTS) end, mnesia:async_dirty(F). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% do_route(From, To, Packet) -> ?DEBUG("session manager~n\tfrom ~p~n\tto ~p~n\tpacket ~P~n", [From, To, Packet, 8]), #jid{user = User, server = Server, luser = LUser, lserver = LServer, lresource = LResource} = To, {xmlelement, Name, Attrs, _Els} = Packet, case LResource of "" -> case Name of "presence" -> {Pass, _Subsc} = case xml:get_attr_s("type", Attrs) of "subscribe" -> Reason = xml:get_path_s( Packet, [{elem, "status"}, cdata]), {is_privacy_allow(From, To, Packet) andalso ejabberd_hooks:run_fold( roster_in_subscription, LServer, false, [User, Server, From, subscribe, Reason]), true}; "subscribed" -> {is_privacy_allow(From, To, Packet) andalso ejabberd_hooks:run_fold( roster_in_subscription, LServer, false, [User, Server, From, subscribed, ""]), true}; "unsubscribe" -> {is_privacy_allow(From, To, Packet) andalso ejabberd_hooks:run_fold( roster_in_subscription, LServer, false, [User, Server, From, unsubscribe, ""]), true}; "unsubscribed" -> {is_privacy_allow(From, To, Packet) andalso ejabberd_hooks:run_fold( roster_in_subscription, LServer, false, [User, Server, From, unsubscribed, ""]), true}; _ -> {true, false} end, if Pass -> PResources = get_user_present_resources( LUser, LServer), lists:foreach( fun({_, R}) -> do_route( From, jlib:jid_replace_resource(To, R), Packet) end, PResources); true -> ok end; "message" -> route_message(From, To, Packet); "iq" -> process_iq(From, To, Packet); "broadcast" -> lists:foreach( fun(R) -> do_route(From, jlib:jid_replace_resource(To, R), Packet) end, get_user_resources(User, Server)); _ -> ok end; _ -> USR = {LUser, LServer, LResource}, case mnesia:dirty_index_read(session, USR, #session.usr) of [] -> case Name of "message" -> route_message(From, To, Packet); "iq" -> case xml:get_attr_s("type", Attrs) of "error" -> ok; "result" -> ok; _ -> Err = jlib:make_error_reply( Packet, ?ERR_SERVICE_UNAVAILABLE), ejabberd_router:route(To, From, Err) end; _ -> ?DEBUG("packet droped~n", []) end; Ss -> Session = lists:max(Ss), Pid = element(2, Session#session.sid), ?DEBUG("sending to process ~p~n", [Pid]), Pid ! {route, From, To, Packet} end end. %% The default list applies to the user as a whole, %% and is processed if there is no active list set %% for the target session/resource to which a stanza is addressed, %% or if there are no current sessions for the user. is_privacy_allow(From, To, Packet) -> User = To#jid.user, Server = To#jid.server, PrivacyList = ejabberd_hooks:run_fold(privacy_get_user_list, Server, #userlist{}, [User, Server]), is_privacy_allow(From, To, Packet, PrivacyList). %% Check if privacy rules allow this delivery %% Function copied from ejabberd_c2s.erl is_privacy_allow(From, To, Packet, PrivacyList) -> User = To#jid.user, Server = To#jid.server, allow == ejabberd_hooks:run_fold( privacy_check_packet, Server, allow, [User, Server, PrivacyList, {From, To, Packet}, in]). route_message(From, To, Packet) -> LUser = To#jid.luser, LServer = To#jid.lserver, PrioRes = get_user_present_resources(LUser, LServer), case catch lists:max(PrioRes) of {Priority, _R} when is_integer(Priority), Priority >= 0 -> lists:foreach( %% Route messages to all priority that equals the max, if %% positive fun({P, R}) when P == Priority -> LResource = jlib:resourceprep(R), USR = {LUser, LServer, LResource}, case mnesia:dirty_index_read(session, USR, #session.usr) of [] -> ok; % Race condition Ss -> Session = lists:max(Ss), Pid = element(2, Session#session.sid), ?DEBUG("sending to process ~p~n", [Pid]), Pid ! {route, From, To, Packet} end; %% Ignore other priority: ({_Prio, _Res}) -> ok end, PrioRes); _ -> case xml:get_tag_attr_s("type", Packet) of "error" -> ok; "groupchat" -> bounce_offline_message(From, To, Packet); "headline" -> bounce_offline_message(From, To, Packet); _ -> case ejabberd_auth:is_user_exists(LUser, LServer) of true -> case is_privacy_allow(From, To, Packet) of true -> ejabberd_hooks:run(offline_message_hook, LServer, [From, To, Packet]); false -> ok end; _ -> Err = jlib:make_error_reply( Packet, ?ERR_SERVICE_UNAVAILABLE), ejabberd_router:route(To, From, Err) end end end. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% clean_session_list(Ss) -> clean_session_list(lists:keysort(#session.usr, Ss), []). clean_session_list([], Res) -> Res; clean_session_list([S], Res) -> [S | Res]; clean_session_list([S1, S2 | Rest], Res) -> if S1#session.usr == S2#session.usr -> if S1#session.sid > S2#session.sid -> clean_session_list([S1 | Rest], Res); true -> clean_session_list([S2 | Rest], Res) end; true -> clean_session_list([S2 | Rest], [S1 | Res]) end. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% get_user_present_resources(LUser, LServer) -> US = {LUser, LServer}, case catch mnesia:dirty_index_read(session, US, #session.us) of {'EXIT', _Reason} -> []; Ss -> [{S#session.priority, element(3, S#session.usr)} || S <- clean_session_list(Ss), is_integer(S#session.priority)] end. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% On new session, check if some existing connections need to be replace check_for_sessions_to_replace(User, Server, Resource) -> LUser = jlib:nodeprep(User), LServer = jlib:nameprep(Server), LResource = jlib:resourceprep(Resource), %% TODO: Depending on how this is executed, there could be an unneeded %% replacement for max_sessions. We need to check this at some point. check_existing_resources(LUser, LServer, LResource), check_max_sessions(LUser, LServer). check_existing_resources(LUser, LServer, LResource) -> SIDs = get_resource_sessions(LUser, LServer, LResource), if SIDs == [] -> ok; true -> %% A connection exist with the same resource. We replace it: MaxSID = lists:max(SIDs), lists:foreach( fun({_, Pid} = S) when S /= MaxSID -> Pid ! replaced; (_) -> ok end, SIDs) end. is_existing_resource(LUser, LServer, LResource) -> [] /= get_resource_sessions(LUser, LServer, LResource). get_resource_sessions(User, Server, Resource) -> USR = {jlib:nodeprep(User), jlib:nameprep(Server), jlib:resourceprep(Resource)}, mnesia:dirty_select( session, [{#session{sid = '$1', usr = USR, _ = '_'}, [], ['$1']}]). check_max_sessions(LUser, LServer) -> If the number of sessions for a given is reached , we replace the %% first one SIDs = mnesia:dirty_select( session, [{#session{sid = '$1', us = {LUser, LServer}, _ = '_'}, [], ['$1']}]), MaxSessions = get_max_user_sessions(LUser, LServer), if length(SIDs) =< MaxSessions -> ok; true -> {_, Pid} = lists:min(SIDs), Pid ! replaced end. %% Get the user_max_session setting This option defines the number of time a given users are allowed to %% log in %% Defaults to infinity get_max_user_sessions(LUser, Host) -> case acl:match_rule( Host, max_user_sessions, jlib:make_jid(LUser, Host, "")) of Max when is_integer(Max) -> Max; infinity -> infinity; _ -> ?MAX_USER_SESSIONS end. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% process_iq(From, To, Packet) -> IQ = jlib:iq_query_info(Packet), case IQ of #iq{xmlns = XMLNS} -> Host = To#jid.lserver, case ets:lookup(sm_iqtable, {XMLNS, Host}) of [{_, Module, Function}] -> ResIQ = Module:Function(From, To, IQ), if ResIQ /= ignore -> ejabberd_router:route(To, From, jlib:iq_to_xml(ResIQ)); true -> ok end; [{_, Module, Function, Opts}] -> gen_iq_handler:handle(Host, Module, Function, Opts, From, To, IQ); [] -> Err = jlib:make_error_reply( Packet, ?ERR_SERVICE_UNAVAILABLE), ejabberd_router:route(To, From, Err) end; reply -> ok; _ -> Err = jlib:make_error_reply(Packet, ?ERR_BAD_REQUEST), ejabberd_router:route(To, From, Err), ok end. force_update_presence({LUser, _LServer} = US) -> case catch mnesia:dirty_index_read(session, US, #session.us) of {'EXIT', _Reason} -> ok; Ss -> lists:foreach(fun(#session{sid = {_, Pid}}) -> Pid ! {force_update_presence, LUser} end, Ss) end. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% ejabberd commands commands() -> [ #ejabberd_commands{name = connected_users, tags = [session], desc = "List all established sessions", module = ?MODULE, function = connected_users, args = [], result = {connected_users, {list, {sessions, string}}}}, #ejabberd_commands{name = connected_users_number, tags = [session, stats], desc = "Get the number of established sessions", module = ?MODULE, function = connected_users_number, args = [], result = {num_sessions, integer}}, #ejabberd_commands{name = user_resources, tags = [session], desc = "List user's connected resources", module = ?MODULE, function = user_resources, args = [{user, string}, {host, string}], result = {resources, {list, {resource, string}}}} ]. connected_users() -> USRs = dirty_get_sessions_list(), SUSRs = lists:sort(USRs), lists:map(fun({U, S, R}) -> [U, $@, S, $/, R] end, SUSRs). connected_users_number() -> length(dirty_get_sessions_list()). user_resources(User, Server) -> Resources = get_user_resources(User, Server), lists:sort(Resources). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Update Mnesia tables update_tables() -> case catch mnesia:table_info(session, attributes) of [ur, user, node] -> mnesia:delete_table(session); [ur, user, pid] -> mnesia:delete_table(session); [usr, us, pid] -> mnesia:delete_table(session); [sid, usr, us, priority] -> mnesia:delete_table(session); [sid, usr, us, priority, info] -> ok; {'EXIT', _} -> ok end, case lists:member(presence, mnesia:system_info(tables)) of true -> mnesia:delete_table(presence); false -> ok end, case lists:member(local_session, mnesia:system_info(tables)) of true -> mnesia:delete_table(local_session); false -> ok end.
null
https://raw.githubusercontent.com/master/ejabberd/9c31874d5a9d1852ece1b8ae70dd4b7e5eef7cf7/src/ejabberd_sm.erl
erlang
---------------------------------------------------------------------- Purpose : Session manager 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 ---------------------------------------------------------------------- API gen_server callbacks default value for the maximum number of user connections ==================================================================== API ==================================================================== -------------------------------------------------------------------- Description: Starts the server -------------------------------------------------------------------- ==================================================================== gen_server callbacks ==================================================================== -------------------------------------------------------------------- Function: init(Args) -> {ok, State} | ignore | {stop, Reason} Description: Initiates the server -------------------------------------------------------------------- -------------------------------------------------------------------- % handle_call(Request , From , State ) - > { reply , Reply , State } | {stop, Reason, Reply, State} | {stop, Reason, State} Description: Handling call messages -------------------------------------------------------------------- -------------------------------------------------------------------- {stop, Reason, State} Description: Handling cast messages -------------------------------------------------------------------- -------------------------------------------------------------------- {stop, Reason, State} Description: Handling all non call/cast messages -------------------------------------------------------------------- -------------------------------------------------------------------- Function: terminate(Reason, State) -> void() Description: This function is called by a gen_server when it is about to terminate. It should be the opposite of Module:init/1 and do any necessary cleaning up. When it returns, the gen_server terminates with Reason. The return value is ignored. -------------------------------------------------------------------- -------------------------------------------------------------------- Description: Convert process state when code is changed -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- reset session_counter table with active sessions The default list applies to the user as a whole, and is processed if there is no active list set for the target session/resource to which a stanza is addressed, or if there are no current sessions for the user. Check if privacy rules allow this delivery Function copied from ejabberd_c2s.erl Route messages to all priority that equals the max, if positive Race condition Ignore other priority: On new session, check if some existing connections need to be replace TODO: Depending on how this is executed, there could be an unneeded replacement for max_sessions. We need to check this at some point. A connection exist with the same resource. We replace it: first one Get the user_max_session setting log in Defaults to infinity ejabberd commands Update Mnesia tables
File : Author : < > Created : 24 Nov 2002 by < > ejabberd , Copyright ( C ) 2002 - 2012 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_sm). -author(''). -behaviour(gen_server). -export([start_link/0, route/3, open_session/5, close_session/4, check_in_subscription/6, bounce_offline_message/3, disconnect_removed_user/2, get_user_resources/2, set_presence/7, unset_presence/6, close_session_unset_presence/5, dirty_get_sessions_list/0, dirty_get_my_sessions_list/0, get_vh_session_list/1, get_vh_session_number/1, register_iq_handler/4, register_iq_handler/5, unregister_iq_handler/2, force_update_presence/1, connected_users/0, connected_users_number/0, user_resources/2, get_session_pid/3, get_user_info/3, get_user_ip/3, is_existing_resource/3 ]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -include("ejabberd.hrl"). -include("jlib.hrl"). -include("ejabberd_commands.hrl"). -include("mod_privacy.hrl"). -record(session, {sid, usr, us, priority, info}). -record(session_counter, {vhost, count}). -record(state, {}). -define(MAX_USER_SESSIONS, infinity). Function : start_link ( ) - > { ok , Pid } | ignore | { error , Error } start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). route(From, To, Packet) -> case catch do_route(From, To, Packet) of {'EXIT', Reason} -> ?ERROR_MSG("~p~nwhen processing: ~p", [Reason, {From, To, Packet}]); _ -> ok end. open_session(SID, User, Server, Resource, Info) -> set_session(SID, User, Server, Resource, undefined, Info), mnesia:dirty_update_counter(session_counter, jlib:nameprep(Server), 1), check_for_sessions_to_replace(User, Server, Resource), JID = jlib:make_jid(User, Server, Resource), ejabberd_hooks:run(sm_register_connection_hook, JID#jid.lserver, [SID, JID, Info]). close_session(SID, User, Server, Resource) -> Info = case mnesia:dirty_read({session, SID}) of [] -> []; [#session{info=I}] -> I end, F = fun() -> mnesia:delete({session, SID}), mnesia:dirty_update_counter(session_counter, jlib:nameprep(Server), -1) end, mnesia:sync_dirty(F), JID = jlib:make_jid(User, Server, Resource), ejabberd_hooks:run(sm_remove_connection_hook, JID#jid.lserver, [SID, JID, Info]). check_in_subscription(Acc, User, Server, _JID, _Type, _Reason) -> case ejabberd_auth:is_user_exists(User, Server) of true -> Acc; false -> {stop, false} end. bounce_offline_message(From, To, Packet) -> Err = jlib:make_error_reply(Packet, ?ERR_SERVICE_UNAVAILABLE), ejabberd_router:route(To, From, Err), stop. disconnect_removed_user(User, Server) -> ejabberd_sm:route(jlib:make_jid("", "", ""), jlib:make_jid(User, Server, ""), {xmlelement, "broadcast", [], [{exit, "User removed"}]}). get_user_resources(User, Server) -> LUser = jlib:nodeprep(User), LServer = jlib:nameprep(Server), US = {LUser, LServer}, case catch mnesia:dirty_index_read(session, US, #session.us) of {'EXIT', _Reason} -> []; Ss -> [element(3, S#session.usr) || S <- clean_session_list(Ss)] end. get_user_ip(User, Server, Resource) -> LUser = jlib:nodeprep(User), LServer = jlib:nameprep(Server), LResource = jlib:resourceprep(Resource), USR = {LUser, LServer, LResource}, case mnesia:dirty_index_read(session, USR, #session.usr) of [] -> undefined; Ss -> Session = lists:max(Ss), proplists:get_value(ip, Session#session.info) end. get_user_info(User, Server, Resource) -> LUser = jlib:nodeprep(User), LServer = jlib:nameprep(Server), LResource = jlib:resourceprep(Resource), USR = {LUser, LServer, LResource}, case mnesia:dirty_index_read(session, USR, #session.usr) of [] -> offline; Ss -> Session = lists:max(Ss), Node = node(element(2, Session#session.sid)), Conn = proplists:get_value(conn, Session#session.info), IP = proplists:get_value(ip, Session#session.info), [{node, Node}, {conn, Conn}, {ip, IP}] end. set_presence(SID, User, Server, Resource, Priority, Presence, Info) -> set_session(SID, User, Server, Resource, Priority, Info), ejabberd_hooks:run(set_presence_hook, jlib:nameprep(Server), [User, Server, Resource, Presence]). unset_presence(SID, User, Server, Resource, Status, Info) -> set_session(SID, User, Server, Resource, undefined, Info), ejabberd_hooks:run(unset_presence_hook, jlib:nameprep(Server), [User, Server, Resource, Status]). close_session_unset_presence(SID, User, Server, Resource, Status) -> close_session(SID, User, Server, Resource), ejabberd_hooks:run(unset_presence_hook, jlib:nameprep(Server), [User, Server, Resource, Status]). get_session_pid(User, Server, Resource) -> LUser = jlib:nodeprep(User), LServer = jlib:nameprep(Server), LResource = jlib:resourceprep(Resource), USR = {LUser, LServer, LResource}, case catch mnesia:dirty_index_read(session, USR, #session.usr) of [#session{sid = {_, Pid}}] -> Pid; _ -> none end. dirty_get_sessions_list() -> mnesia:dirty_select( session, [{#session{usr = '$1', _ = '_'}, [], ['$1']}]). dirty_get_my_sessions_list() -> mnesia:dirty_select( session, [{#session{sid = {'_', '$1'}, _ = '_'}, [{'==', {node, '$1'}, node()}], ['$_']}]). get_vh_session_list(Server) -> LServer = jlib:nameprep(Server), mnesia:dirty_select( session, [{#session{usr = '$1', _ = '_'}, [{'==', {element, 2, '$1'}, LServer}], ['$1']}]). get_vh_session_number(Server) -> LServer = jlib:nameprep(Server), Query = mnesia:dirty_select( session_counter, [{#session_counter{vhost = LServer, count = '$1'}, [], ['$1']}]), case Query of [Count] -> Count; _ -> 0 end. register_iq_handler(Host, XMLNS, Module, Fun) -> ejabberd_sm ! {register_iq_handler, Host, XMLNS, Module, Fun}. register_iq_handler(Host, XMLNS, Module, Fun, Opts) -> ejabberd_sm ! {register_iq_handler, Host, XMLNS, Module, Fun, Opts}. unregister_iq_handler(Host, XMLNS) -> ejabberd_sm ! {unregister_iq_handler, Host, XMLNS}. { ok , State , Timeout } | init([]) -> update_tables(), mnesia:create_table(session, [{ram_copies, [node()]}, {attributes, record_info(fields, session)}]), mnesia:create_table(session_counter, [{ram_copies, [node()]}, {attributes, record_info(fields, session_counter)}]), mnesia:add_table_index(session, usr), mnesia:add_table_index(session, us), mnesia:add_table_copy(session, node(), ram_copies), mnesia:add_table_copy(session_counter, node(), ram_copies), mnesia:subscribe(system), ets:new(sm_iqtable, [named_table]), lists:foreach( fun(Host) -> ejabberd_hooks:add(roster_in_subscription, Host, ejabberd_sm, check_in_subscription, 20), ejabberd_hooks:add(offline_message_hook, Host, ejabberd_sm, bounce_offline_message, 100), ejabberd_hooks:add(remove_user, Host, ejabberd_sm, disconnect_removed_user, 100) end, ?MYHOSTS), ejabberd_commands:register_commands(commands()), {ok, #state{}}. { reply , Reply , State , Timeout } | { noreply , State } | { noreply , State , Timeout } | handle_call(_Request, _From, State) -> Reply = ok, {reply, Reply, State}. Function : handle_cast(Msg , State ) - > { noreply , State } | { noreply , State , Timeout } | handle_cast(_Msg, State) -> {noreply, State}. Function : handle_info(Info , State ) - > { noreply , State } | { noreply , State , Timeout } | handle_info({route, From, To, Packet}, State) -> case catch do_route(From, To, Packet) of {'EXIT', Reason} -> ?ERROR_MSG("~p~nwhen processing: ~p", [Reason, {From, To, Packet}]); _ -> ok end, {noreply, State}; handle_info({mnesia_system_event, {mnesia_down, Node}}, State) -> recount_session_table(Node), {noreply, State}; handle_info({register_iq_handler, Host, XMLNS, Module, Function}, State) -> ets:insert(sm_iqtable, {{XMLNS, Host}, Module, Function}), {noreply, State}; handle_info({register_iq_handler, Host, XMLNS, Module, Function, Opts}, State) -> ets:insert(sm_iqtable, {{XMLNS, Host}, Module, Function, Opts}), {noreply, State}; handle_info({unregister_iq_handler, Host, XMLNS}, State) -> case ets:lookup(sm_iqtable, {XMLNS, Host}) of [{_, Module, Function, Opts}] -> gen_iq_handler:stop_iq_handler(Module, Function, Opts); _ -> ok end, ets:delete(sm_iqtable, {XMLNS, Host}), {noreply, State}; handle_info(_Info, State) -> {noreply, State}. terminate(_Reason, _State) -> ejabberd_commands:unregister_commands(commands()), ok. Func : code_change(OldVsn , State , Extra ) - > { ok , NewState } code_change(_OldVsn, State, _Extra) -> {ok, State}. Internal functions set_session(SID, User, Server, Resource, Priority, Info) -> LUser = jlib:nodeprep(User), LServer = jlib:nameprep(Server), LResource = jlib:resourceprep(Resource), US = {LUser, LServer}, USR = {LUser, LServer, LResource}, F = fun() -> mnesia:write(#session{sid = SID, usr = USR, us = US, priority = Priority, info = Info}) end, mnesia:sync_dirty(F). Recalculates alive sessions when goes down and updates session and session_counter tables recount_session_table(Node) -> F = fun() -> Es = mnesia:select( session, [{#session{sid = {'_', '$1'}, _ = '_'}, [{'==', {node, '$1'}, Node}], ['$_']}]), lists:foreach(fun(E) -> mnesia:delete({session, E#session.sid}) end, Es), mnesia:clear_table(session_counter), lists:foreach(fun(Server) -> LServer = jlib:nameprep(Server), Hs = mnesia:select(session, [{#session{usr = '$1', _ = '_'}, [{'==', {element, 2, '$1'}, LServer}], ['$1']}]), mnesia:write( #session_counter{vhost = LServer, count = length(Hs)}) end, ?MYHOSTS) end, mnesia:async_dirty(F). do_route(From, To, Packet) -> ?DEBUG("session manager~n\tfrom ~p~n\tto ~p~n\tpacket ~P~n", [From, To, Packet, 8]), #jid{user = User, server = Server, luser = LUser, lserver = LServer, lresource = LResource} = To, {xmlelement, Name, Attrs, _Els} = Packet, case LResource of "" -> case Name of "presence" -> {Pass, _Subsc} = case xml:get_attr_s("type", Attrs) of "subscribe" -> Reason = xml:get_path_s( Packet, [{elem, "status"}, cdata]), {is_privacy_allow(From, To, Packet) andalso ejabberd_hooks:run_fold( roster_in_subscription, LServer, false, [User, Server, From, subscribe, Reason]), true}; "subscribed" -> {is_privacy_allow(From, To, Packet) andalso ejabberd_hooks:run_fold( roster_in_subscription, LServer, false, [User, Server, From, subscribed, ""]), true}; "unsubscribe" -> {is_privacy_allow(From, To, Packet) andalso ejabberd_hooks:run_fold( roster_in_subscription, LServer, false, [User, Server, From, unsubscribe, ""]), true}; "unsubscribed" -> {is_privacy_allow(From, To, Packet) andalso ejabberd_hooks:run_fold( roster_in_subscription, LServer, false, [User, Server, From, unsubscribed, ""]), true}; _ -> {true, false} end, if Pass -> PResources = get_user_present_resources( LUser, LServer), lists:foreach( fun({_, R}) -> do_route( From, jlib:jid_replace_resource(To, R), Packet) end, PResources); true -> ok end; "message" -> route_message(From, To, Packet); "iq" -> process_iq(From, To, Packet); "broadcast" -> lists:foreach( fun(R) -> do_route(From, jlib:jid_replace_resource(To, R), Packet) end, get_user_resources(User, Server)); _ -> ok end; _ -> USR = {LUser, LServer, LResource}, case mnesia:dirty_index_read(session, USR, #session.usr) of [] -> case Name of "message" -> route_message(From, To, Packet); "iq" -> case xml:get_attr_s("type", Attrs) of "error" -> ok; "result" -> ok; _ -> Err = jlib:make_error_reply( Packet, ?ERR_SERVICE_UNAVAILABLE), ejabberd_router:route(To, From, Err) end; _ -> ?DEBUG("packet droped~n", []) end; Ss -> Session = lists:max(Ss), Pid = element(2, Session#session.sid), ?DEBUG("sending to process ~p~n", [Pid]), Pid ! {route, From, To, Packet} end end. is_privacy_allow(From, To, Packet) -> User = To#jid.user, Server = To#jid.server, PrivacyList = ejabberd_hooks:run_fold(privacy_get_user_list, Server, #userlist{}, [User, Server]), is_privacy_allow(From, To, Packet, PrivacyList). is_privacy_allow(From, To, Packet, PrivacyList) -> User = To#jid.user, Server = To#jid.server, allow == ejabberd_hooks:run_fold( privacy_check_packet, Server, allow, [User, Server, PrivacyList, {From, To, Packet}, in]). route_message(From, To, Packet) -> LUser = To#jid.luser, LServer = To#jid.lserver, PrioRes = get_user_present_resources(LUser, LServer), case catch lists:max(PrioRes) of {Priority, _R} when is_integer(Priority), Priority >= 0 -> lists:foreach( fun({P, R}) when P == Priority -> LResource = jlib:resourceprep(R), USR = {LUser, LServer, LResource}, case mnesia:dirty_index_read(session, USR, #session.usr) of [] -> Ss -> Session = lists:max(Ss), Pid = element(2, Session#session.sid), ?DEBUG("sending to process ~p~n", [Pid]), Pid ! {route, From, To, Packet} end; ({_Prio, _Res}) -> ok end, PrioRes); _ -> case xml:get_tag_attr_s("type", Packet) of "error" -> ok; "groupchat" -> bounce_offline_message(From, To, Packet); "headline" -> bounce_offline_message(From, To, Packet); _ -> case ejabberd_auth:is_user_exists(LUser, LServer) of true -> case is_privacy_allow(From, To, Packet) of true -> ejabberd_hooks:run(offline_message_hook, LServer, [From, To, Packet]); false -> ok end; _ -> Err = jlib:make_error_reply( Packet, ?ERR_SERVICE_UNAVAILABLE), ejabberd_router:route(To, From, Err) end end end. clean_session_list(Ss) -> clean_session_list(lists:keysort(#session.usr, Ss), []). clean_session_list([], Res) -> Res; clean_session_list([S], Res) -> [S | Res]; clean_session_list([S1, S2 | Rest], Res) -> if S1#session.usr == S2#session.usr -> if S1#session.sid > S2#session.sid -> clean_session_list([S1 | Rest], Res); true -> clean_session_list([S2 | Rest], Res) end; true -> clean_session_list([S2 | Rest], [S1 | Res]) end. get_user_present_resources(LUser, LServer) -> US = {LUser, LServer}, case catch mnesia:dirty_index_read(session, US, #session.us) of {'EXIT', _Reason} -> []; Ss -> [{S#session.priority, element(3, S#session.usr)} || S <- clean_session_list(Ss), is_integer(S#session.priority)] end. check_for_sessions_to_replace(User, Server, Resource) -> LUser = jlib:nodeprep(User), LServer = jlib:nameprep(Server), LResource = jlib:resourceprep(Resource), check_existing_resources(LUser, LServer, LResource), check_max_sessions(LUser, LServer). check_existing_resources(LUser, LServer, LResource) -> SIDs = get_resource_sessions(LUser, LServer, LResource), if SIDs == [] -> ok; true -> MaxSID = lists:max(SIDs), lists:foreach( fun({_, Pid} = S) when S /= MaxSID -> Pid ! replaced; (_) -> ok end, SIDs) end. is_existing_resource(LUser, LServer, LResource) -> [] /= get_resource_sessions(LUser, LServer, LResource). get_resource_sessions(User, Server, Resource) -> USR = {jlib:nodeprep(User), jlib:nameprep(Server), jlib:resourceprep(Resource)}, mnesia:dirty_select( session, [{#session{sid = '$1', usr = USR, _ = '_'}, [], ['$1']}]). check_max_sessions(LUser, LServer) -> If the number of sessions for a given is reached , we replace the SIDs = mnesia:dirty_select( session, [{#session{sid = '$1', us = {LUser, LServer}, _ = '_'}, [], ['$1']}]), MaxSessions = get_max_user_sessions(LUser, LServer), if length(SIDs) =< MaxSessions -> ok; true -> {_, Pid} = lists:min(SIDs), Pid ! replaced end. This option defines the number of time a given users are allowed to get_max_user_sessions(LUser, Host) -> case acl:match_rule( Host, max_user_sessions, jlib:make_jid(LUser, Host, "")) of Max when is_integer(Max) -> Max; infinity -> infinity; _ -> ?MAX_USER_SESSIONS end. process_iq(From, To, Packet) -> IQ = jlib:iq_query_info(Packet), case IQ of #iq{xmlns = XMLNS} -> Host = To#jid.lserver, case ets:lookup(sm_iqtable, {XMLNS, Host}) of [{_, Module, Function}] -> ResIQ = Module:Function(From, To, IQ), if ResIQ /= ignore -> ejabberd_router:route(To, From, jlib:iq_to_xml(ResIQ)); true -> ok end; [{_, Module, Function, Opts}] -> gen_iq_handler:handle(Host, Module, Function, Opts, From, To, IQ); [] -> Err = jlib:make_error_reply( Packet, ?ERR_SERVICE_UNAVAILABLE), ejabberd_router:route(To, From, Err) end; reply -> ok; _ -> Err = jlib:make_error_reply(Packet, ?ERR_BAD_REQUEST), ejabberd_router:route(To, From, Err), ok end. force_update_presence({LUser, _LServer} = US) -> case catch mnesia:dirty_index_read(session, US, #session.us) of {'EXIT', _Reason} -> ok; Ss -> lists:foreach(fun(#session{sid = {_, Pid}}) -> Pid ! {force_update_presence, LUser} end, Ss) end. commands() -> [ #ejabberd_commands{name = connected_users, tags = [session], desc = "List all established sessions", module = ?MODULE, function = connected_users, args = [], result = {connected_users, {list, {sessions, string}}}}, #ejabberd_commands{name = connected_users_number, tags = [session, stats], desc = "Get the number of established sessions", module = ?MODULE, function = connected_users_number, args = [], result = {num_sessions, integer}}, #ejabberd_commands{name = user_resources, tags = [session], desc = "List user's connected resources", module = ?MODULE, function = user_resources, args = [{user, string}, {host, string}], result = {resources, {list, {resource, string}}}} ]. connected_users() -> USRs = dirty_get_sessions_list(), SUSRs = lists:sort(USRs), lists:map(fun({U, S, R}) -> [U, $@, S, $/, R] end, SUSRs). connected_users_number() -> length(dirty_get_sessions_list()). user_resources(User, Server) -> Resources = get_user_resources(User, Server), lists:sort(Resources). update_tables() -> case catch mnesia:table_info(session, attributes) of [ur, user, node] -> mnesia:delete_table(session); [ur, user, pid] -> mnesia:delete_table(session); [usr, us, pid] -> mnesia:delete_table(session); [sid, usr, us, priority] -> mnesia:delete_table(session); [sid, usr, us, priority, info] -> ok; {'EXIT', _} -> ok end, case lists:member(presence, mnesia:system_info(tables)) of true -> mnesia:delete_table(presence); false -> ok end, case lists:member(local_session, mnesia:system_info(tables)) of true -> mnesia:delete_table(local_session); false -> ok end.
4b6bb9d7a644252ed0857c460b3e8850c617f47dbb1ed7d7a0d55cf6a39ce89b
typedclojure/typedclojure
core__defprotocol.clj
Copyright ( c ) , contributors . ;; The use and distribution terms for this software are covered by the ;; Eclipse Public License 1.0 (-1.0.php) ;; which can be found in the file epl-v10.html at the root of this distribution. ;; By using this software in any fashion, you are agreeing to be bound by ;; the terms of this license. ;; You must not remove this notice, or any other, from this software. (ns ^:no-doc typed.clj.ext.clojure.core__defprotocol "Typing rules for clojure.core/defprotocol" (:require [typed.cljc.checker.check-below :as below] [typed.cljc.checker.type-rep :as r] [typed.cljc.checker.utils :as u] [typed.cljc.checker.check.unanalyzed :refer [defuspecial]])) ;;================== ;; clojure.core/defprotocol (defuspecial defuspecial__defprotocol "defuspecial implementation for clojure.core/defprotocol" [expr expected] ;;TODO check arities at least match up with definition ;;TODO give warning if defprotocol is unannotated (assoc expr u/expr-type (below/maybe-check-below (r/ret r/-any) expected)))
null
https://raw.githubusercontent.com/typedclojure/typedclojure/6c697798cef6fa6c936aaa3cbf26ec51f8e7e2ed/typed/lib.clojure/src/typed/clj/ext/clojure/core__defprotocol.clj
clojure
The use and distribution terms for this software are covered by the Eclipse Public License 1.0 (-1.0.php) which can be found in the file epl-v10.html at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software. ================== clojure.core/defprotocol TODO check arities at least match up with definition TODO give warning if defprotocol is unannotated
Copyright ( c ) , contributors . (ns ^:no-doc typed.clj.ext.clojure.core__defprotocol "Typing rules for clojure.core/defprotocol" (:require [typed.cljc.checker.check-below :as below] [typed.cljc.checker.type-rep :as r] [typed.cljc.checker.utils :as u] [typed.cljc.checker.check.unanalyzed :refer [defuspecial]])) (defuspecial defuspecial__defprotocol "defuspecial implementation for clojure.core/defprotocol" [expr expected] (assoc expr u/expr-type (below/maybe-check-below (r/ret r/-any) expected)))
c51ccc5996636aecaf3650403ee00cc79961b2f50cf43a3d6717dd904cba4170
ocaml-ppx/ppx_tools_versioned
ast_convenience_402.ml
open Migrate_parsetree.Ast_402 (* This file is part of the ppx_tools package. It is released *) under the terms of the MIT license ( see LICENSE file ) . Copyright 2013 and LexiFi open Parsetree open Asttypes open Location open Ast_helper module Label = struct type t = string type desc = Nolabel | Labelled of string | Optional of string let explode s = if s = "" then Nolabel else if s.[0] = '?' then Optional (String.sub s 1 (String.length s - 1)) else Labelled s let nolabel = "" let labelled s = s let optional s = "?"^s end module Constant = struct type t = Pconst_integer of string * char option | Pconst_char of char | Pconst_string of string * string option | Pconst_float of string * char option exception Unknown_literal of string * char * Backport Int_literal_converter from ocaml 4.03 - * * #L298 *) module Int_literal_converter = struct let cvt_int_aux str neg of_string = if String.length str = 0 || str.[0] = '-' then of_string str else neg (of_string ("-" ^ str)) let int s = cvt_int_aux s (~-) int_of_string let int32 s = cvt_int_aux s Int32.neg Int32.of_string let int64 s = cvt_int_aux s Int64.neg Int64.of_string let nativeint s = cvt_int_aux s Nativeint.neg Nativeint.of_string end let of_constant = function | Asttypes.Const_int32(i) -> Pconst_integer(Int32.to_string i, Some 'l') | Asttypes.Const_int64(i) -> Pconst_integer(Int64.to_string i, Some 'L') | Asttypes.Const_nativeint(i) -> Pconst_integer(Nativeint.to_string i, Some 'n') | Asttypes.Const_int(i) -> Pconst_integer(string_of_int i, None) | Asttypes.Const_char c -> Pconst_char c | Asttypes.Const_string(s, s_opt) -> Pconst_string(s, s_opt) | Asttypes.Const_float f -> Pconst_float(f, None) let to_constant = function | Pconst_integer(i,Some 'l') -> Asttypes.Const_int32 (Int_literal_converter.int32 i) | Pconst_integer(i,Some 'L') -> Asttypes.Const_int64 (Int_literal_converter.int64 i) | Pconst_integer(i,Some 'n') -> Asttypes.Const_nativeint (Int_literal_converter.nativeint i) | Pconst_integer(i,None) -> Asttypes.Const_int (Int_literal_converter.int i) | Pconst_integer(i,Some c) -> raise (Unknown_literal (i, c)) | Pconst_char c -> Asttypes.Const_char c | Pconst_string(s,d) -> Asttypes.Const_string(s, d) | Pconst_float(f,None) -> Asttypes.Const_float f | Pconst_float(f,Some c) -> raise (Unknown_literal (f, c)) end let may_tuple ?loc tup = function | [] -> None | [x] -> Some x | l -> Some (tup ?loc ?attrs:None l) let lid ?(loc = !default_loc) s = mkloc (Longident.parse s) loc let constr ?loc ?attrs s args = Exp.construct ?loc ?attrs (lid ?loc s) (may_tuple ?loc Exp.tuple args) let nil ?loc ?attrs () = constr ?loc ?attrs "[]" [] let unit ?loc ?attrs () = constr ?loc ?attrs "()" [] let tuple ?loc ?attrs = function | [] -> unit ?loc ?attrs () | [x] -> x | xs -> Exp.tuple ?loc ?attrs xs let cons ?loc ?attrs hd tl = constr ?loc ?attrs "::" [hd; tl] let list ?loc ?attrs l = List.fold_right (cons ?loc ?attrs) l (nil ?loc ?attrs ()) let str ?loc ?attrs s = Exp.constant ?loc ?attrs (Const_string (s, None)) let int ?loc ?attrs x = Exp.constant ?loc ?attrs (Const_int x) let char ?loc ?attrs x = Exp.constant ?loc ?attrs (Const_char x) let float ?loc ?attrs x = Exp.constant ?loc ?attrs (Const_float (string_of_float x)) let record ?loc ?attrs ?over l = Exp.record ?loc ?attrs (List.map (fun (s, e) -> (lid ~loc:e.pexp_loc s, e)) l) over let func ?loc ?attrs l = Exp.function_ ?loc ?attrs (List.map (fun (p, e) -> Exp.case p e) l) let lam ?loc ?attrs ?(label = Label.nolabel) ?default pat exp = Exp.fun_ ?loc ?attrs label default pat exp let app ?loc ?attrs f l = if l = [] then f else Exp.apply ?loc ?attrs f (List.map (fun a -> Label.nolabel, a) l) let evar ?loc ?attrs s = Exp.ident ?loc ?attrs (lid ?loc s) let let_in ?loc ?attrs ?(recursive = false) b body = Exp.let_ ?loc ?attrs (if recursive then Recursive else Nonrecursive) b body let sequence ?loc ?attrs = function | [] -> unit ?loc ?attrs () | hd :: tl -> List.fold_left (fun e1 e2 -> Exp.sequence ?loc ?attrs e1 e2) hd tl let pvar ?(loc = !default_loc) ?attrs s = Pat.var ~loc ?attrs (mkloc s loc) let pconstr ?loc ?attrs s args = Pat.construct ?loc ?attrs (lid ?loc s) (may_tuple ?loc Pat.tuple args) let precord ?loc ?attrs ?(closed = Open) l = Pat.record ?loc ?attrs (List.map (fun (s, e) -> (lid ~loc:e.ppat_loc s, e)) l) closed let pnil ?loc ?attrs () = pconstr ?loc ?attrs "[]" [] let pcons ?loc ?attrs hd tl = pconstr ?loc ?attrs "::" [hd; tl] let punit ?loc ?attrs () = pconstr ?loc ?attrs "()" [] let ptuple ?loc ?attrs = function | [] -> punit ?loc ?attrs () | [x] -> x | xs -> Pat.tuple ?loc ?attrs xs let plist ?loc ?attrs l = List.fold_right (pcons ?loc ?attrs) l (pnil ?loc ?attrs ()) let pstr ?loc ?attrs s = Pat.constant ?loc ?attrs (Const_string (s, None)) let pint ?loc ?attrs x = Pat.constant ?loc ?attrs (Const_int x) let pchar ?loc ?attrs x = Pat.constant ?loc ?attrs (Const_char x) let pfloat ?loc ?attrs x = Pat.constant ?loc ?attrs (Const_float (string_of_float x)) let tconstr ?loc ?attrs c l = Typ.constr ?loc ?attrs (lid ?loc c) l let get_str = function | {pexp_desc=Pexp_constant (Const_string (s, _)); _} -> Some s | _ -> None let get_str_with_quotation_delimiter = function | {pexp_desc=Pexp_constant (Const_string (s, d)); _} -> Some (s, d) | _ -> None let get_lid = function | {pexp_desc=Pexp_ident{txt=id;_};_} -> Some (String.concat "." (Longident.flatten id)) | _ -> None let find_attr s attrs = try Some (snd (List.find (fun (x, _) -> x.txt = s) attrs)) with Not_found -> None let expr_of_payload = function | PStr [{pstr_desc=Pstr_eval(e, _); _}] -> Some e | _ -> None let find_attr_expr s attrs = match find_attr s attrs with | Some e -> expr_of_payload e | None -> None let has_attr s attrs = find_attr s attrs <> None
null
https://raw.githubusercontent.com/ocaml-ppx/ppx_tools_versioned/00a0150cdabfa7f0dad2c5e0e6b32230d22295ca/ast_convenience_402.ml
ocaml
This file is part of the ppx_tools package. It is released
open Migrate_parsetree.Ast_402 under the terms of the MIT license ( see LICENSE file ) . Copyright 2013 and LexiFi open Parsetree open Asttypes open Location open Ast_helper module Label = struct type t = string type desc = Nolabel | Labelled of string | Optional of string let explode s = if s = "" then Nolabel else if s.[0] = '?' then Optional (String.sub s 1 (String.length s - 1)) else Labelled s let nolabel = "" let labelled s = s let optional s = "?"^s end module Constant = struct type t = Pconst_integer of string * char option | Pconst_char of char | Pconst_string of string * string option | Pconst_float of string * char option exception Unknown_literal of string * char * Backport Int_literal_converter from ocaml 4.03 - * * #L298 *) module Int_literal_converter = struct let cvt_int_aux str neg of_string = if String.length str = 0 || str.[0] = '-' then of_string str else neg (of_string ("-" ^ str)) let int s = cvt_int_aux s (~-) int_of_string let int32 s = cvt_int_aux s Int32.neg Int32.of_string let int64 s = cvt_int_aux s Int64.neg Int64.of_string let nativeint s = cvt_int_aux s Nativeint.neg Nativeint.of_string end let of_constant = function | Asttypes.Const_int32(i) -> Pconst_integer(Int32.to_string i, Some 'l') | Asttypes.Const_int64(i) -> Pconst_integer(Int64.to_string i, Some 'L') | Asttypes.Const_nativeint(i) -> Pconst_integer(Nativeint.to_string i, Some 'n') | Asttypes.Const_int(i) -> Pconst_integer(string_of_int i, None) | Asttypes.Const_char c -> Pconst_char c | Asttypes.Const_string(s, s_opt) -> Pconst_string(s, s_opt) | Asttypes.Const_float f -> Pconst_float(f, None) let to_constant = function | Pconst_integer(i,Some 'l') -> Asttypes.Const_int32 (Int_literal_converter.int32 i) | Pconst_integer(i,Some 'L') -> Asttypes.Const_int64 (Int_literal_converter.int64 i) | Pconst_integer(i,Some 'n') -> Asttypes.Const_nativeint (Int_literal_converter.nativeint i) | Pconst_integer(i,None) -> Asttypes.Const_int (Int_literal_converter.int i) | Pconst_integer(i,Some c) -> raise (Unknown_literal (i, c)) | Pconst_char c -> Asttypes.Const_char c | Pconst_string(s,d) -> Asttypes.Const_string(s, d) | Pconst_float(f,None) -> Asttypes.Const_float f | Pconst_float(f,Some c) -> raise (Unknown_literal (f, c)) end let may_tuple ?loc tup = function | [] -> None | [x] -> Some x | l -> Some (tup ?loc ?attrs:None l) let lid ?(loc = !default_loc) s = mkloc (Longident.parse s) loc let constr ?loc ?attrs s args = Exp.construct ?loc ?attrs (lid ?loc s) (may_tuple ?loc Exp.tuple args) let nil ?loc ?attrs () = constr ?loc ?attrs "[]" [] let unit ?loc ?attrs () = constr ?loc ?attrs "()" [] let tuple ?loc ?attrs = function | [] -> unit ?loc ?attrs () | [x] -> x | xs -> Exp.tuple ?loc ?attrs xs let cons ?loc ?attrs hd tl = constr ?loc ?attrs "::" [hd; tl] let list ?loc ?attrs l = List.fold_right (cons ?loc ?attrs) l (nil ?loc ?attrs ()) let str ?loc ?attrs s = Exp.constant ?loc ?attrs (Const_string (s, None)) let int ?loc ?attrs x = Exp.constant ?loc ?attrs (Const_int x) let char ?loc ?attrs x = Exp.constant ?loc ?attrs (Const_char x) let float ?loc ?attrs x = Exp.constant ?loc ?attrs (Const_float (string_of_float x)) let record ?loc ?attrs ?over l = Exp.record ?loc ?attrs (List.map (fun (s, e) -> (lid ~loc:e.pexp_loc s, e)) l) over let func ?loc ?attrs l = Exp.function_ ?loc ?attrs (List.map (fun (p, e) -> Exp.case p e) l) let lam ?loc ?attrs ?(label = Label.nolabel) ?default pat exp = Exp.fun_ ?loc ?attrs label default pat exp let app ?loc ?attrs f l = if l = [] then f else Exp.apply ?loc ?attrs f (List.map (fun a -> Label.nolabel, a) l) let evar ?loc ?attrs s = Exp.ident ?loc ?attrs (lid ?loc s) let let_in ?loc ?attrs ?(recursive = false) b body = Exp.let_ ?loc ?attrs (if recursive then Recursive else Nonrecursive) b body let sequence ?loc ?attrs = function | [] -> unit ?loc ?attrs () | hd :: tl -> List.fold_left (fun e1 e2 -> Exp.sequence ?loc ?attrs e1 e2) hd tl let pvar ?(loc = !default_loc) ?attrs s = Pat.var ~loc ?attrs (mkloc s loc) let pconstr ?loc ?attrs s args = Pat.construct ?loc ?attrs (lid ?loc s) (may_tuple ?loc Pat.tuple args) let precord ?loc ?attrs ?(closed = Open) l = Pat.record ?loc ?attrs (List.map (fun (s, e) -> (lid ~loc:e.ppat_loc s, e)) l) closed let pnil ?loc ?attrs () = pconstr ?loc ?attrs "[]" [] let pcons ?loc ?attrs hd tl = pconstr ?loc ?attrs "::" [hd; tl] let punit ?loc ?attrs () = pconstr ?loc ?attrs "()" [] let ptuple ?loc ?attrs = function | [] -> punit ?loc ?attrs () | [x] -> x | xs -> Pat.tuple ?loc ?attrs xs let plist ?loc ?attrs l = List.fold_right (pcons ?loc ?attrs) l (pnil ?loc ?attrs ()) let pstr ?loc ?attrs s = Pat.constant ?loc ?attrs (Const_string (s, None)) let pint ?loc ?attrs x = Pat.constant ?loc ?attrs (Const_int x) let pchar ?loc ?attrs x = Pat.constant ?loc ?attrs (Const_char x) let pfloat ?loc ?attrs x = Pat.constant ?loc ?attrs (Const_float (string_of_float x)) let tconstr ?loc ?attrs c l = Typ.constr ?loc ?attrs (lid ?loc c) l let get_str = function | {pexp_desc=Pexp_constant (Const_string (s, _)); _} -> Some s | _ -> None let get_str_with_quotation_delimiter = function | {pexp_desc=Pexp_constant (Const_string (s, d)); _} -> Some (s, d) | _ -> None let get_lid = function | {pexp_desc=Pexp_ident{txt=id;_};_} -> Some (String.concat "." (Longident.flatten id)) | _ -> None let find_attr s attrs = try Some (snd (List.find (fun (x, _) -> x.txt = s) attrs)) with Not_found -> None let expr_of_payload = function | PStr [{pstr_desc=Pstr_eval(e, _); _}] -> Some e | _ -> None let find_attr_expr s attrs = match find_attr s attrs with | Some e -> expr_of_payload e | None -> None let has_attr s attrs = find_attr s attrs <> None
2d1c22bed34bb748a1fbd570d2cce678cd93b304256bab42ac067f71eec907b3
uim/uim
ng-key.scm
;;; ng-key.scm: Key definitions and utilities (next generation) ;;; Copyright ( c ) 2005 - 2013 uim Project ;;; ;;; 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 . Neither the name of authors 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 HOLDERS 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 , 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. ;;;; (require "util.scm") ( require - custom " key-custom.scm " ) ; ; FIXME : temporarily disabled ;; ;; modifiers ;; (define valid-modifiers '(mod_None mod_Shift mod_Shift_R mod_Shift_L mod_Control mod_Control_R mod_Control_L mod_Alt mod_Alt_R mod_Alt_L mod_Meta mod_Meta_R mod_Meta_L mod_Super mod_Super_R mod_Super_L mod_Hyper mod_Hyper_R mod_Hyper_L mod_Caps_Lock ;;mod_Shift_Lock ;;mod_Num_Lock ;; pseudo modifiers for meta-event mod_ignore_Shift mod_ignore_Control mod_ignore_Alt mod_ignore_Meta mod_ignore_Super mod_ignore_Hyper)) (define mod_None #x00000000) (define mod_Shift_L #x00000001) (define mod_Shift_R #x00000002) (define mod_Shift #x00000004) (define mod_Control_L #x00000008) (define mod_Control_R #x00000010) (define mod_Control #x00000020) (define mod_Alt_L #x00000040) (define mod_Alt_R #x00000080) (define mod_Alt #x00000100) (define mod_Meta_L #x00000200) (define mod_Meta_R #x00000400) (define mod_Meta #x00000800) (define mod_Super_L #x00001000) (define mod_Super_R #x00002000) (define mod_Super #x00004000) (define mod_Hyper_L #x00008000) (define mod_Hyper_R #x00010000) (define mod_Hyper #x00020000) (define mod_Caps_Lock #x00040000) ;;(define #x00080000) ;;(define #x00100000) (define mod_ignore_Shift #x00200000) (define mod_ignore_Control #x00400000) (define mod_ignore_Alt #x00800000) (define mod_ignore_Meta #x01000000) (define mod_ignore_Super #x02000000) (define mod_ignore_Hyper #x04000000) ;;(define #x08000000) ;; incapable by storage-compact ( define # x10000000 ) ; ; incapable by storage - compact ;;(define #x20000000) ;; incapable by storage-compact ;;(define #x40000000) ;; incapable by storage-compact (define modifier-shift-mask (bitwise-ior mod_Shift_L mod_Shift_R mod_Shift)) (define modifier-control-mask (bitwise-ior mod_Control_L mod_Control_R mod_Control)) (define modifier-alt-mask (bitwise-ior mod_Alt_L mod_Alt_R mod_Alt)) (define modifier-meta-mask (bitwise-ior mod_Meta_L mod_Meta_R mod_Meta)) (define modifier-super-mask (bitwise-ior mod_Super_L mod_Super_R mod_Super)) (define modifier-hyper-mask (bitwise-ior mod_Hyper_L mod_Hyper_R mod_Hyper)) ;; API (define modifier-symbol? (lambda (sym) (and (symbol? sym) (memq sym valid-modifiers)))) ;; API (define modifier-has? (lambda (self other) (= (bitwise-and self other) other))) (define modifier-aggregate (lambda (self flags) (let ((aggregate-mod-group (lambda (self flags mod mod-ignore mod-mask) (let ((self-mods (bitwise-and self mod-mask))) (if (modifier-has? flags mod-ignore) mod-ignore (if (and (modifier-has? flags mod) (not (= self-mods 0))) mod self-mods)))))) (bitwise-ior (aggregate-mod-group self flags mod_Shift mod_ignore_Shift modifier-shift-mask) (aggregate-mod-group self flags mod_Control mod_ignore_Control modifier-control-mask) (aggregate-mod-group self flags mod_Alt mod_ignore_Alt modifier-alt-mask) (aggregate-mod-group self flags mod_Meta mod_ignore_Meta modifier-meta-mask) (aggregate-mod-group self flags mod_Super mod_ignore_Super modifier-super-mask) (aggregate-mod-group self flags mod_Hyper mod_ignore_Hyper modifier-hyper-mask) (bitwise-and self mod_Caps_Lock))))) ;; API (define modifier-match? (lambda (self other) (let* ((aggregated-self (modifier-aggregate self self)) (aggregated-other (modifier-aggregate other aggregated-self))) (= aggregated-self aggregated-other)))) ;; ;; logical keys ;; (define valid-logical-keys '(lkey_VoidSymbol lkey_BackSpace lkey_Tab lkey_Return lkey_Escape lkey_Delete lkey_Home lkey_Left lkey_Up lkey_Right lkey_Down lkey_Page_Up lkey_Page_Down lkey_End lkey_Insert lkey_Shift_L lkey_Shift_R lkey_Control_L lkey_Control_R lkey_Caps_Lock lkey_Meta_L lkey_Meta_R lkey_Alt_L lkey_Alt_R lkey_Super_L lkey_Super_R lkey_Hyper_L lkey_Hyper_R lkey_Multi_key ;; Multi-key character compose lkey_Mode_switch ;; Character set switch Japanese keyboard support lkey_Kanji ;; Kanji, Kanji convert lkey_Muhenkan ;; Cancel Conversion Henkan_Mode Hiragana / Katakana toggle lkey_Zenkaku_Hankaku ;; Zenkaku/Hankaku toggle NICOLA keys lkey_Thumb_Shift_L lkey_Thumb_Shift_R lkey_F1 lkey_F2 lkey_F3 lkey_F4 lkey_F5 lkey_F6 lkey_F7 lkey_F8 lkey_F9 lkey_F10 lkey_F11 lkey_F12 lkey_F13 lkey_F14 lkey_F15 lkey_F16 lkey_F17 lkey_F18 lkey_F19 lkey_F20 lkey_F21 lkey_F22 lkey_F23 lkey_F24 lkey_F25 lkey_F26 lkey_F27 lkey_F28 lkey_F29 lkey_F30 lkey_F31 lkey_F32 lkey_F33 lkey_F34 lkey_F35 ;; ASCII keys lkey_space lkey_exclam lkey_quotedbl lkey_numbersign lkey_dollar lkey_percent lkey_ampersand lkey_apostrophe lkey_parenleft lkey_parenright lkey_asterisk lkey_plus lkey_comma lkey_minus lkey_period lkey_slash lkey_0 lkey_1 lkey_2 lkey_3 lkey_4 lkey_5 lkey_6 lkey_7 lkey_8 lkey_9 lkey_colon lkey_semicolon lkey_less lkey_equal lkey_greater lkey_question lkey_at lkey_A lkey_B lkey_C lkey_D lkey_E lkey_F lkey_G lkey_H lkey_I lkey_J lkey_K lkey_L lkey_M lkey_N lkey_O lkey_P lkey_Q lkey_R lkey_S lkey_T lkey_U lkey_V lkey_W lkey_X lkey_Y lkey_Z lkey_bracketleft lkey_backslash lkey_bracketright lkey_asciicircum lkey_underscore lkey_grave lkey_a lkey_b lkey_c lkey_d lkey_e lkey_f lkey_g lkey_h lkey_i lkey_j lkey_k lkey_l lkey_m lkey_n lkey_o lkey_p lkey_q lkey_r lkey_s lkey_t lkey_u lkey_v lkey_w lkey_x lkey_y lkey_z lkey_braceleft lkey_bar lkey_braceright lkey_asciitilde ;; extended keys lkey_yen ;; dead keys lkey_dead_grave lkey_dead_acute lkey_dead_circumflex lkey_dead_tilde lkey_dead_macron lkey_dead_breve lkey_dead_abovedot lkey_dead_diaeresis lkey_dead_abovering lkey_dead_doubleacute lkey_dead_caron lkey_dead_cedilla lkey_dead_ogonek lkey_dead_iota lkey_dead_voiced_sound lkey_dead_semivoiced_sound lkey_dead_belowdot lkey_dead_hook lkey_dead_horn)) ;; API (define logical-key? (lambda (key) (and (symbol? key) (memq key valid-logical-keys)))) ;; ;; physical key ;; ;; added on demand (define valid-physical-keys '(pkey_VoidSymbol)) ;; API (define physical-key? (lambda (key) (and (symbol? key) (memq key valid-physical-keys)))) ;; API will be replaced with actual one when physical-key.scm loaded (define lkey->pkey (lambda (lkey) #f))
null
https://raw.githubusercontent.com/uim/uim/d1ac9d9315ff8c57c713b502544fef9b3a83b3e5/scm/ng-key.scm
scheme
ng-key.scm: Key definitions and utilities (next generation) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: notice, this list of conditions and the following disclaimer. notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. may be used to endorse or promote products derived from this software without specific prior written permission. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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. ; FIXME : temporarily disabled modifiers mod_Shift_Lock mod_Num_Lock pseudo modifiers for meta-event (define #x00080000) (define #x00100000) (define #x08000000) ;; incapable by storage-compact ; incapable by storage - compact (define #x20000000) ;; incapable by storage-compact (define #x40000000) ;; incapable by storage-compact API API API logical keys Multi-key character compose Character set switch Kanji, Kanji convert Cancel Conversion Zenkaku/Hankaku toggle ASCII keys extended keys dead keys API physical key added on demand API API
Copyright ( c ) 2005 - 2013 uim Project 1 . Redistributions of source code must retain the above copyright 2 . Redistributions in binary form must reproduce the above copyright 3 . Neither the name of authors nor the names of its contributors THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ` ` AS IS '' AND IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT (require "util.scm") (define valid-modifiers '(mod_None mod_Shift mod_Shift_R mod_Shift_L mod_Control mod_Control_R mod_Control_L mod_Alt mod_Alt_R mod_Alt_L mod_Meta mod_Meta_R mod_Meta_L mod_Super mod_Super_R mod_Super_L mod_Hyper mod_Hyper_R mod_Hyper_L mod_Caps_Lock mod_ignore_Shift mod_ignore_Control mod_ignore_Alt mod_ignore_Meta mod_ignore_Super mod_ignore_Hyper)) (define mod_None #x00000000) (define mod_Shift_L #x00000001) (define mod_Shift_R #x00000002) (define mod_Shift #x00000004) (define mod_Control_L #x00000008) (define mod_Control_R #x00000010) (define mod_Control #x00000020) (define mod_Alt_L #x00000040) (define mod_Alt_R #x00000080) (define mod_Alt #x00000100) (define mod_Meta_L #x00000200) (define mod_Meta_R #x00000400) (define mod_Meta #x00000800) (define mod_Super_L #x00001000) (define mod_Super_R #x00002000) (define mod_Super #x00004000) (define mod_Hyper_L #x00008000) (define mod_Hyper_R #x00010000) (define mod_Hyper #x00020000) (define mod_Caps_Lock #x00040000) (define mod_ignore_Shift #x00200000) (define mod_ignore_Control #x00400000) (define mod_ignore_Alt #x00800000) (define mod_ignore_Meta #x01000000) (define mod_ignore_Super #x02000000) (define mod_ignore_Hyper #x04000000) (define modifier-shift-mask (bitwise-ior mod_Shift_L mod_Shift_R mod_Shift)) (define modifier-control-mask (bitwise-ior mod_Control_L mod_Control_R mod_Control)) (define modifier-alt-mask (bitwise-ior mod_Alt_L mod_Alt_R mod_Alt)) (define modifier-meta-mask (bitwise-ior mod_Meta_L mod_Meta_R mod_Meta)) (define modifier-super-mask (bitwise-ior mod_Super_L mod_Super_R mod_Super)) (define modifier-hyper-mask (bitwise-ior mod_Hyper_L mod_Hyper_R mod_Hyper)) (define modifier-symbol? (lambda (sym) (and (symbol? sym) (memq sym valid-modifiers)))) (define modifier-has? (lambda (self other) (= (bitwise-and self other) other))) (define modifier-aggregate (lambda (self flags) (let ((aggregate-mod-group (lambda (self flags mod mod-ignore mod-mask) (let ((self-mods (bitwise-and self mod-mask))) (if (modifier-has? flags mod-ignore) mod-ignore (if (and (modifier-has? flags mod) (not (= self-mods 0))) mod self-mods)))))) (bitwise-ior (aggregate-mod-group self flags mod_Shift mod_ignore_Shift modifier-shift-mask) (aggregate-mod-group self flags mod_Control mod_ignore_Control modifier-control-mask) (aggregate-mod-group self flags mod_Alt mod_ignore_Alt modifier-alt-mask) (aggregate-mod-group self flags mod_Meta mod_ignore_Meta modifier-meta-mask) (aggregate-mod-group self flags mod_Super mod_ignore_Super modifier-super-mask) (aggregate-mod-group self flags mod_Hyper mod_ignore_Hyper modifier-hyper-mask) (bitwise-and self mod_Caps_Lock))))) (define modifier-match? (lambda (self other) (let* ((aggregated-self (modifier-aggregate self self)) (aggregated-other (modifier-aggregate other aggregated-self))) (= aggregated-self aggregated-other)))) (define valid-logical-keys '(lkey_VoidSymbol lkey_BackSpace lkey_Tab lkey_Return lkey_Escape lkey_Delete lkey_Home lkey_Left lkey_Up lkey_Right lkey_Down lkey_Page_Up lkey_Page_Down lkey_End lkey_Insert lkey_Shift_L lkey_Shift_R lkey_Control_L lkey_Control_R lkey_Caps_Lock lkey_Meta_L lkey_Meta_R lkey_Alt_L lkey_Alt_R lkey_Super_L lkey_Super_R lkey_Hyper_L lkey_Hyper_R Japanese keyboard support Henkan_Mode Hiragana / Katakana toggle NICOLA keys lkey_Thumb_Shift_L lkey_Thumb_Shift_R lkey_F1 lkey_F2 lkey_F3 lkey_F4 lkey_F5 lkey_F6 lkey_F7 lkey_F8 lkey_F9 lkey_F10 lkey_F11 lkey_F12 lkey_F13 lkey_F14 lkey_F15 lkey_F16 lkey_F17 lkey_F18 lkey_F19 lkey_F20 lkey_F21 lkey_F22 lkey_F23 lkey_F24 lkey_F25 lkey_F26 lkey_F27 lkey_F28 lkey_F29 lkey_F30 lkey_F31 lkey_F32 lkey_F33 lkey_F34 lkey_F35 lkey_space lkey_exclam lkey_quotedbl lkey_numbersign lkey_dollar lkey_percent lkey_ampersand lkey_apostrophe lkey_parenleft lkey_parenright lkey_asterisk lkey_plus lkey_comma lkey_minus lkey_period lkey_slash lkey_0 lkey_1 lkey_2 lkey_3 lkey_4 lkey_5 lkey_6 lkey_7 lkey_8 lkey_9 lkey_colon lkey_semicolon lkey_less lkey_equal lkey_greater lkey_question lkey_at lkey_A lkey_B lkey_C lkey_D lkey_E lkey_F lkey_G lkey_H lkey_I lkey_J lkey_K lkey_L lkey_M lkey_N lkey_O lkey_P lkey_Q lkey_R lkey_S lkey_T lkey_U lkey_V lkey_W lkey_X lkey_Y lkey_Z lkey_bracketleft lkey_backslash lkey_bracketright lkey_asciicircum lkey_underscore lkey_grave lkey_a lkey_b lkey_c lkey_d lkey_e lkey_f lkey_g lkey_h lkey_i lkey_j lkey_k lkey_l lkey_m lkey_n lkey_o lkey_p lkey_q lkey_r lkey_s lkey_t lkey_u lkey_v lkey_w lkey_x lkey_y lkey_z lkey_braceleft lkey_bar lkey_braceright lkey_asciitilde lkey_yen lkey_dead_grave lkey_dead_acute lkey_dead_circumflex lkey_dead_tilde lkey_dead_macron lkey_dead_breve lkey_dead_abovedot lkey_dead_diaeresis lkey_dead_abovering lkey_dead_doubleacute lkey_dead_caron lkey_dead_cedilla lkey_dead_ogonek lkey_dead_iota lkey_dead_voiced_sound lkey_dead_semivoiced_sound lkey_dead_belowdot lkey_dead_hook lkey_dead_horn)) (define logical-key? (lambda (key) (and (symbol? key) (memq key valid-logical-keys)))) (define valid-physical-keys '(pkey_VoidSymbol)) (define physical-key? (lambda (key) (and (symbol? key) (memq key valid-physical-keys)))) will be replaced with actual one when physical-key.scm loaded (define lkey->pkey (lambda (lkey) #f))
4e1a9bcc44d0a34341064972586e7b254320a7b1786b9a56f90c9d98cac8a6c2
clojure-interop/google-cloud-clients
TransactionRunner.clj
(ns com.google.cloud.spanner.TransactionRunner "An interface for executing a body of work in the context of a read-write transaction, with retries for transaction aborts. See TransactionContext for a description of transaction semantics. TransactionRunner instances are obtained by calling DatabaseClient.readWriteTransaction(). A TransactionRunner instance can only be used for a single invocation of run(TransactionCallable)." (:refer-clojure :only [require comment defn ->]) (:import [com.google.cloud.spanner TransactionRunner])) (defn run "Executes a read-write transaction, with retries as necessary. The work to perform in each transaction attempt is defined by callable, which may return an object as the result of the work. callable will be retried if a transaction attempt aborts; implementations must be prepared to be called more than once. Any writes buffered by callable will only be applied if the transaction commits successfully. Similarly, the value produced by callable will only be returned by this method if the transaction commits successfully. callable is allowed to raise an unchecked exception. Typically this prevents further attempts to execute callable, and the exception will propagate from this method call. However, if a read or query in callable detected that the transaction aborted, callable will be retried even if it raised an exception. callable - `com.google.cloud.spanner.TransactionRunner$TransactionCallable` returns: `<T> T`" ([^TransactionRunner this ^com.google.cloud.spanner.TransactionRunner$TransactionCallable callable] (-> this (.run callable)))) (defn get-commit-timestamp "Returns the timestamp at which the transaction committed. This method may only be called once run(TransactionCallable) has returned normally. returns: `com.google.cloud.Timestamp`" (^com.google.cloud.Timestamp [^TransactionRunner this] (-> this (.getCommitTimestamp)))) (defn allow-nested-transaction "Allows overriding the default behaviour of blocking nested transactions. Note that the client library does not maintain any information regarding the nesting structure. If an outer transaction fails and an inner transaction succeeds, upon retry of the outer transaction, the inner transaction will be re-executed. Use with care when certain that the inner transaction is idempotent. Avoid doing this when accessing the same db. There might be legitimate uses where access need to be made across DBs for instance. E.g. of nesting that is discouraged, see nestedReadWriteTxnThrows nestedReadOnlyTxnThrows, nestedBatchTxnThrows, nestedSingleUseReadTxnThrows returns: this object - `com.google.cloud.spanner.TransactionRunner`" (^com.google.cloud.spanner.TransactionRunner [^TransactionRunner this] (-> this (.allowNestedTransaction))))
null
https://raw.githubusercontent.com/clojure-interop/google-cloud-clients/80852d0496057c22f9cdc86d6f9ffc0fa3cd7904/com.google.cloud.spanner/src/com/google/cloud/spanner/TransactionRunner.clj
clojure
implementations
(ns com.google.cloud.spanner.TransactionRunner "An interface for executing a body of work in the context of a read-write transaction, with retries for transaction aborts. See TransactionContext for a description of transaction semantics. TransactionRunner instances are obtained by calling DatabaseClient.readWriteTransaction(). A TransactionRunner instance can only be used for a single invocation of run(TransactionCallable)." (:refer-clojure :only [require comment defn ->]) (:import [com.google.cloud.spanner TransactionRunner])) (defn run "Executes a read-write transaction, with retries as necessary. The work to perform in each transaction attempt is defined by callable, which may return an object as the result of must be prepared to be called more than once. Any writes buffered by callable will only be applied if the transaction commits successfully. Similarly, the value produced by callable will only be returned by this method if the transaction commits successfully. callable is allowed to raise an unchecked exception. Typically this prevents further attempts to execute callable, and the exception will propagate from this method call. However, if a read or query in callable detected that the transaction aborted, callable will be retried even if it raised an exception. callable - `com.google.cloud.spanner.TransactionRunner$TransactionCallable` returns: `<T> T`" ([^TransactionRunner this ^com.google.cloud.spanner.TransactionRunner$TransactionCallable callable] (-> this (.run callable)))) (defn get-commit-timestamp "Returns the timestamp at which the transaction committed. This method may only be called once run(TransactionCallable) has returned normally. returns: `com.google.cloud.Timestamp`" (^com.google.cloud.Timestamp [^TransactionRunner this] (-> this (.getCommitTimestamp)))) (defn allow-nested-transaction "Allows overriding the default behaviour of blocking nested transactions. Note that the client library does not maintain any information regarding the nesting structure. If an outer transaction fails and an inner transaction succeeds, upon retry of the outer transaction, the inner transaction will be re-executed. Use with care when certain that the inner transaction is idempotent. Avoid doing this when accessing the same db. There might be legitimate uses where access need to be made across DBs for instance. E.g. of nesting that is discouraged, see nestedReadWriteTxnThrows nestedReadOnlyTxnThrows, nestedBatchTxnThrows, nestedSingleUseReadTxnThrows returns: this object - `com.google.cloud.spanner.TransactionRunner`" (^com.google.cloud.spanner.TransactionRunner [^TransactionRunner this] (-> this (.allowNestedTransaction))))
6e1429d0bae1c4994de57895f50d8808cde3f4f91e990c36c79115d18fbefc19
zotonic/zotonic
controller_default_contact.erl
@author author < > YYYY author . %% @doc Example contact-form handler. -module(controller_default_contact). -export([event/2]). -include_lib("zotonic_core/include/zotonic.hrl"). event(#submit{message={contact, []}}, Context) -> Vars = [{mail, z_context:get_q("mail", Context)}, {name, z_context:get_q("name", Context)}, {message, z_context:get_q("message", Context)}], z_email:send_render(z_email:get_admin_email(Context), "_email_contact.tpl", Vars, Context), z_render:update("contact-form", "<p>The form has been submitted! Thank you, we'll get in touch soon.</p>", Context).
null
https://raw.githubusercontent.com/zotonic/zotonic/852f627c28adf6e5212e8ad5383d4af3a2f25e3f/apps/zotonic_mod_zotonic_site_management/priv/skel/blog/src/controllers/controller_default_contact.erl
erlang
@doc Example contact-form handler.
@author author < > YYYY author . -module(controller_default_contact). -export([event/2]). -include_lib("zotonic_core/include/zotonic.hrl"). event(#submit{message={contact, []}}, Context) -> Vars = [{mail, z_context:get_q("mail", Context)}, {name, z_context:get_q("name", Context)}, {message, z_context:get_q("message", Context)}], z_email:send_render(z_email:get_admin_email(Context), "_email_contact.tpl", Vars, Context), z_render:update("contact-form", "<p>The form has been submitted! Thank you, we'll get in touch soon.</p>", Context).
4cbbf6c1b3a164775bc777f4decbbe3c8c2f8e93548a2243970abd289227f9ea
janestreet/memtrace_viewer_with_deps
vdom_based_tests.ml
open! Core_kernel open Bonsai.Let_syntax open Virtual_dom open Proc This test basically just exists because it 's really hard to dispatch events deep into a tree without an intermediate representation . Turns out that Vdom . Node.t is a pretty good intermediate representation . events deep into a tree without an intermediate representation. Turns out that Vdom.Node.t is a pretty good intermediate representation. *) let%expect_test "recursive component" = let module M = struct type t = { label : string ; children : t Int.Map.t } [@@deriving fields] end in let rec tree input path = let%pattern_bind { M.label; children } = input in let%sub children = Bonsai.assoc (module Int) children ~f:(fun index child -> let path = Bonsai.Value.map2 index path ~f:List.cons in let%sub child = Bonsai.lazy_ (lazy (tree child path)) in return @@ let%map child = child and index = index in Vdom.Node.div [] [ Vdom.Node.textf "%d" index; child ]) in let%sub state = Bonsai.state [%here] (module Int) ~default_model:0 in return @@ let%map children = children and label = label and path = path and state, set_state = state in let path_text = String.concat ~sep:"_" ("path" :: List.rev_map path ~f:Int.to_string) in Vdom.Node.div [ Vdom.Attr.id path_text ] (Vdom.Node.textf "%s %d" label state :: Vdom.Node.button [ Vdom.Attr.on_click (fun _ -> set_state (state + 1)) ] [ Vdom.Node.text "+1" ] :: Int.Map.data children) in let var = Bonsai.Var.create { M.label = "hi" ; children = Int.Map.of_alist_exn [ ( 0 , { M.label = "hello" ; children = Int.Map.of_alist_exn [ 99, { M.label = "another"; children = Int.Map.empty } ] } ) ; 1, { M.label = "test"; children = Int.Map.empty } ; 2, { M.label = "foobar"; children = Int.Map.empty } ] } in let value = Bonsai.Var.value var in let handle = Handle.create (Result_spec.vdom Fn.id) (tree value (Bonsai.Value.return [ 0 ])) in Handle.show handle; let before = [%expect.output] in Handle.click_on handle ~get_vdom:Fn.id ~selector:"#path_0_0_99 button"; Handle.show handle; let after = [%expect.output] in Expect_test_patdiff.print_patdiff before after; [%expect {| -1,28 +1,28 <div id="path_0"> hi 0 <button onclick={handler}> +1 </button> <div> 0 <div id="path_0_0"> hello 0 <button onclick={handler}> +1 </button> <div> 99 <div id="path_0_0_99"> -| another 0 +| another 1 <button onclick={handler}> +1 </button> </div> </div> </div> </div> <div> 1 <div id="path_0_1"> test 0 <button onclick={handler}> +1 </button> </div> </div> <div> 2 <div id="path_0_2"> foobar 0 |}] ;;
null
https://raw.githubusercontent.com/janestreet/memtrace_viewer_with_deps/5a9e1f927f5f8333e2d71c8d3ca03a45587422c4/vendor/bonsai/web_test/vdom_based_tests.ml
ocaml
open! Core_kernel open Bonsai.Let_syntax open Virtual_dom open Proc This test basically just exists because it 's really hard to dispatch events deep into a tree without an intermediate representation . Turns out that Vdom . Node.t is a pretty good intermediate representation . events deep into a tree without an intermediate representation. Turns out that Vdom.Node.t is a pretty good intermediate representation. *) let%expect_test "recursive component" = let module M = struct type t = { label : string ; children : t Int.Map.t } [@@deriving fields] end in let rec tree input path = let%pattern_bind { M.label; children } = input in let%sub children = Bonsai.assoc (module Int) children ~f:(fun index child -> let path = Bonsai.Value.map2 index path ~f:List.cons in let%sub child = Bonsai.lazy_ (lazy (tree child path)) in return @@ let%map child = child and index = index in Vdom.Node.div [] [ Vdom.Node.textf "%d" index; child ]) in let%sub state = Bonsai.state [%here] (module Int) ~default_model:0 in return @@ let%map children = children and label = label and path = path and state, set_state = state in let path_text = String.concat ~sep:"_" ("path" :: List.rev_map path ~f:Int.to_string) in Vdom.Node.div [ Vdom.Attr.id path_text ] (Vdom.Node.textf "%s %d" label state :: Vdom.Node.button [ Vdom.Attr.on_click (fun _ -> set_state (state + 1)) ] [ Vdom.Node.text "+1" ] :: Int.Map.data children) in let var = Bonsai.Var.create { M.label = "hi" ; children = Int.Map.of_alist_exn [ ( 0 , { M.label = "hello" ; children = Int.Map.of_alist_exn [ 99, { M.label = "another"; children = Int.Map.empty } ] } ) ; 1, { M.label = "test"; children = Int.Map.empty } ; 2, { M.label = "foobar"; children = Int.Map.empty } ] } in let value = Bonsai.Var.value var in let handle = Handle.create (Result_spec.vdom Fn.id) (tree value (Bonsai.Value.return [ 0 ])) in Handle.show handle; let before = [%expect.output] in Handle.click_on handle ~get_vdom:Fn.id ~selector:"#path_0_0_99 button"; Handle.show handle; let after = [%expect.output] in Expect_test_patdiff.print_patdiff before after; [%expect {| -1,28 +1,28 <div id="path_0"> hi 0 <button onclick={handler}> +1 </button> <div> 0 <div id="path_0_0"> hello 0 <button onclick={handler}> +1 </button> <div> 99 <div id="path_0_0_99"> -| another 0 +| another 1 <button onclick={handler}> +1 </button> </div> </div> </div> </div> <div> 1 <div id="path_0_1"> test 0 <button onclick={handler}> +1 </button> </div> </div> <div> 2 <div id="path_0_2"> foobar 0 |}] ;;
99128574717ea36340e3cff31265528edc89f9f1bffd2dac756a847ed1123345
nuprl/gradual-typing-performance
classes.rkt
#lang typed/racket/base (require typed/racket/class (prefix-in mred: typed/racket/gui) "require-typed-check.rkt" ; benchmark infrastructure "typed-base.rkt" ; replace this with base, after defining interfaces racket/math string-constants) (require/typed/if "region-typed.rkt" "region.rkt") (require/typed/check "make-cards.rkt" [back (Instance mred:Bitmap%)]) (require/typed/check "show-help.rkt" [show-help ((Listof String) String Any -> (-> Any))]) (require/typed "show-scribbling.rkt" [show-scribbling (Module-Path String -> (-> Void))]) (provide pasteboard% table%) (define-type Pasteboard% (Class #:implements mred:Pasteboard% [only-front-selected (-> Void)] [get-all-list (-> (Listof (Instance mred:Snip%)))] [get-full-box (-> (Values Real Real Real Real))] [get-region-box (Region -> (Values Real Real Real Real))] [add-region (-> Region Void)] [remove-region (-> Region Void)] [unhilite-region (Region -> Void)] [hilite-region (-> Region Void)] [set-double-click-action (-> (-> (Instance mred:Snip%) Void) Void)] [set-single-click-action (-> (-> (Instance Card%) Void) Void)] [set-button-action (-> (U 'left 'middle 'right) Symbol Void)] (augment [after-select ((Instance mred:Snip%) Any -> Void)] [on-interactive-move ((Instance mred:Mouse-Event%) -> Void)] [after-interactive-move ((Instance mred:Mouse-Event%) -> Void)]))) ;; utils.rk inlined here (provide shuffle-list) (: shuffle-list (All (X) (-> (Listof X) Natural (Listof X)))) (define shuffle-list (lambda (l c) (if (zero? c) l (let-values ([(a b) (let ([half (floor (/ (length l) 2))]) (values (let: loop : (Listof X) ([l : (Listof X) l][n : Natural half]) (if (zero? n) null (cons (car l) (loop (cdr l) (sub1 n))))) (list-tail l half)))]) (shuffle-list (let loop : (Listof X) ([a : (Listof X) a] [b : (Listof X) b] [l : (Listof X) null]) (cond [(null? a) (append (reverse b) l)] [(null? b) (append (reverse a) l)] [(zero? (random 2)) (loop (cdr a) b (cons (car a) l))] [else (loop a (cdr b) (cons (car b) l))])) (sub1 c)))))) ;; -------------------- ;; constants.rkt inlined here (define ANIMATION-STEPS 5) (define ANIMATION-TIME 0.3) (define PRETTY-CARD-SEP-AMOUNT 5) (define black-color (make-object mred:color% "black")) (define white-brush (send mred:the-brush-list find-or-create-brush "white" 'solid)) (define hilite-brush (send mred:the-brush-list find-or-create-brush black-color 'hilite)) (define black-pen (send mred:the-pen-list find-or-create-pen black-color 1 'solid)) (define dark-gray-pen (send mred:the-pen-list find-or-create-pen "dark gray" 1 'solid)) (define no-pen (send mred:the-pen-list find-or-create-pen black-color 1 'transparent)) (define nice-font (send mred:the-font-list find-or-create-font 12 'decorative 'normal 'bold #f 'default #t)) ;; -------------------------- (: pasteboard% Pasteboard%) (define pasteboard% (class mred:pasteboard% (inherit begin-edit-sequence end-edit-sequence get-admin invalidate-bitmap-cache find-next-selected-snip find-first-snip find-snip set-before set-after add-selected is-selected? no-selected set-selected remove-selected get-snip-location move-to dc-location-to-editor-location set-selection-visible) (define: select-one? : Boolean #t) (define: select-backward? : Boolean #f) (define: raise-to-front? : Boolean #f) (: button-map (Listof (List (U 'left 'middle 'right) Boolean Boolean Boolean))) (define button-map '((left #f #f #t) (middle #t #f #t) (right #f #t #f))) (define: do-on-double-click : (U 'flip ((Instance mred:Snip%) -> Void)) 'flip) (define: do-on-single-click : ((Instance Card%) -> Void) void) (define: selecting? : Boolean #f) (define: dragging? : Boolean #f) (define: bg-click? : Boolean #f) (define: click-base : (Option (Instance Card%)) #f) (define: last-click : Any #f) (define: regions : (Listof Region) null) (: update-region (Region -> Void)) (: get-snip-bounds ((Instance mred:Snip%) -> (Values Real Real Real Real))) (: get-reverse-selected-list (-> (Listof (Instance mred:Snip%)))) (: for-each-selected (-> (-> (Instance Card%) Any) Void)) (: make-overlapping-list (-> (Instance mred:Snip%) (Listof (Instance mred:Snip%)) Any (Listof (Instance mred:Snip%)))) (private* [get-snip-bounds (lambda: ([s : (Instance mred:Snip%)]) (let: ([xbox : (Boxof Real) (box 0)] [ybox : (Boxof Real) (box 0)]) (get-snip-location s xbox ybox #f) (let ([l (unbox xbox)] [t (unbox ybox)]) (get-snip-location s xbox ybox #t) (values l t (unbox xbox) (unbox ybox)))))] [for-each-selected (lambda (f) (let: loop : Void ([snip : (Option (Instance mred:Snip%)) (find-next-selected-snip #f)]) (when snip (let ([snip : (Instance Card%) (cast snip (Instance Card%))]) (f snip) (loop (find-next-selected-snip snip))))))] [make-overlapping-list (lambda ([s : (Instance mred:Snip%)] so-far behind?) (let-values ([(sl st sr sb) (get-snip-bounds s)]) (let: loop : (Listof (Instance mred:Snip%)) ([t : (Option (Instance mred:Snip%)) (find-first-snip)] [so-far : (Listof (Instance mred:Snip%)) so-far] [get? : Boolean (not behind?)]) (cond [(not t) so-far] [(eq? s t) (if behind? (loop (send t next) so-far #t) so-far)] [get? (let ([l (if (and (not (memq t so-far)) (let-values ([(tl tt tr tb) (get-snip-bounds t)]) (and (or (<= sl tl sr) (<= sl tr sr)) (or (<= st tt sb) (<= st tb sb))))) FIXME so-far)]) (loop (send t next) l #t))] [else (loop (send t next) so-far #f)]))))] [get-reverse-selected-list (lambda () (let: loop : (Listof (Instance mred:Snip%)) ([s (find-next-selected-snip #f)] [l : (Listof (Instance mred:Snip%)) null]) (if s (loop (find-next-selected-snip s) (cons s l)) l)))] [shuffle cards to shuffle in back->front order (let* ([permuted-list : (Listof (Instance Card%)) (shuffle-list selected-list 7)] [get-pos (lambda ([s : (Instance mred:Snip%)]) (let ([xb : (Boxof Real) (box 0)] [yb : (Boxof Real) (box 0)]) (get-snip-location s xb yb) (cons (unbox xb) (unbox yb))))] [sel-loc-list ((inst map (Pairof Real Real) (Instance mred:Snip%)) get-pos selected-list)] [perm-loc-list ((inst map (Pairof Real Real) (Instance mred:Snip%)) get-pos permuted-list)]) ((inst for-each (Instance Card%) (Pairof Real Real) (Pairof Real Real)) (lambda ([s : (Instance Card%)] [start-pos : (Pairof Real Real)] [end-pos : (Pairof Real Real)]) (let* ([sx : Real (car start-pos)] [sy : Real (cdr start-pos)] [ex : Real (car end-pos)] [ey : Real (cdr end-pos)] [steps (max 1 (floor (/ 50 (length selected-list))))]) (let: loop : Void ([i : Integer 1]) (unless (> i steps) (let ([x (+ sx (* (/ i steps) (- ex sx)))] [y (+ sy (* (/ i steps) (- ey sy)))]) (move-to s x y) (mred:flush-display) (loop (add1 i))))))) permuted-list perm-loc-list sel-loc-list) (let loop ([l permuted-list]) (unless (null? l) (set-before (car l) #f) (loop (cdr l)))) (no-selected)))] [update-region (lambda (region) (let-values ([(sx sy sw sh) (get-region-box region)]) (invalidate-bitmap-cache sx sy sw sh)))]) (public* [only-front-selected (lambda () (let: loop : Void ([s : (Option (Instance mred:Snip%)) (find-next-selected-snip #f)] [ok : (Option (Instance mred:Snip%)) (find-first-snip)]) (when s (if (eq? s ok) (loop (find-next-selected-snip s) (send (assert ok) next)) (let: loop ([s : (Instance mred:Snip%) s] [l : (Listof (Instance mred:Snip%)) (list s)]) (let ([next (find-next-selected-snip s)]) (if next (loop next (cons s l)) (for-each (lambda: ([s : (Instance mred:Snip%)]) (remove-selected s)) l))))))))]) (override* [on-paint (lambda (before? dc l t r b dx dy caret) (when before? (for-each (lambda: ([region : Region]) (when (region-paint-callback region) (let-values ([(sx sy sw sh) (get-region-box region)]) ((assert (region-paint-callback region)) dc (+ dx sx) (+ dy sy) sw sh))) (when (region-label region) (let ([old-b (send dc get-brush)] [old-p (send dc get-pen)]) (let-values ([(sx sy sw sh) (get-region-box region)]) (send dc set-brush (assert white-brush)) (send dc set-pen no-pen) (send dc draw-rectangle (+ dx sx) (+ dy sy) (assert sw positive?) (assert sh positive?)) (send dc set-pen dark-gray-pen) (draw-roundish-rectangle dc (+ dx sx) (+ dy sy) sw sh) (let ([text (region-label region)]) (if (string? text) (let ([old-f (send dc get-font)]) (send dc set-font nice-font) (let-values ([(x y d a) (send dc get-text-extent text)]) (send dc draw-text text (+ dx sx (/ (- sw x) 2)) (if (region-button? region) ;; Since we use size-in-pixels, the letters should really be 12 pixels high ( including ;; the descender), but the space above the letter can vary by font ; center on 12 , splitting ;; the difference for the descender (+ dy sy (/ (- sh 12) 2) (- 12 y (/ d -2))) (+ dy sy 5)))) (send dc set-font old-f)) (send dc draw-bitmap (assert text) (+ dx sx (/ (- sw (send (assert text) get-width)) 2)) (+ dy sy (/ (- sh (send (assert text) get-height)) 2)) 'solid black-color (send (assert text) get-loaded-mask)))) (when (region-hilite? region) (send dc set-brush (assert hilite-brush)) (send dc set-pen no-pen) (send dc draw-rectangle (+ dx sx 1) (+ dy sy 1) (assert (- sw 2) positive?) (assert (- sh 2) positive?)))) (send dc set-brush old-b) (send dc set-pen old-p)))) regions)))]) (augment* [after-select (lambda: ([s : (Instance mred:Snip%)] [on? : Any]) (inner (void) after-select s on?) (unless (or (not on?) selecting?) (set! selecting? #t) (if select-one? (when raise-to-front? (set-before s #f)) (begin (begin-edit-sequence) (let ([l : (Listof (Instance mred:Snip%)) (make-overlapping-list s (list s) select-backward?)]) ((inst for-each (Instance mred:Snip%)) (lambda: ([i : (Instance mred:Snip%)]) (add-selected i)) l)) (when raise-to-front? (let loop ([snip (find-next-selected-snip #f)][prev : (Option (Instance mred:Snip%)) #f]) (when snip (if prev (set-after snip prev) (set-before snip #f)) (loop (find-next-selected-snip (assert snip)) snip)))) (end-edit-sequence))) (set! selecting? #f)))] [on-interactive-move (lambda (e) (inner (void) on-interactive-move e) (for-each (lambda: ([region : Region]) (set-region-decided-start?! region #f)) regions) (for-each-selected (lambda: ([snip : (Instance Card%)]) (send snip remember-location this))) (set! dragging? #t))]) (override* [interactive-adjust-move (lambda: ([snip : (Instance mred:Snip%)] [xb : (Boxof Real)] [yb : (Boxof Real)]) (super interactive-adjust-move snip xb yb) (let ([snip (cast snip (Instance Card%))]) (let-values: ([([l : Real] [t : Real] [r : Real] [b : Real]) (get-snip-bounds snip)]) (let-values: ([([rl : Real] [rt : Real] [rw : Real] [rh : Real]) (let: ([r : (Option Region) (send snip stay-in-region)]) (if r (values (region-x r) (region-y r) (region-w r) (region-h r)) (let: ([wb : (Boxof Real) (box 0)][hb : (Boxof Real) (box 0)]) (send (assert (get-admin)) get-view #f #f wb hb) (values 0 0 (unbox wb) (unbox hb)))))]) (let ([max-x (- (+ rl rw) (- r l))] [max-y (- (+ rt rh) (- b t))]) (when (< (unbox xb) rl) (set-box! xb rl)) (when (> (unbox xb) max-x) (set-box! xb max-x)) (when (< (unbox yb) rt) (set-box! yb rt)) (when (> (unbox yb) max-y) (set-box! yb max-y)))))))]) (: after-interactive-move ((Instance mred:Mouse-Event%) -> Void) #:augment ((Instance mred:Mouse-Event%) -> Void)) (augment* [after-interactive-move (lambda: ([e : (Instance mred:Mouse-Event%)]) (when dragging? (set! dragging? #f) (inner (void) after-interactive-move e) (for-each-selected (lambda: ([snip : (Instance Card%)]) (send snip back-to-original-location this))) (let: ([cards : (Listof (Instance mred:Snip%)) (get-reverse-selected-list)]) (only-front-selected) ; in case overlap changed (for-each (lambda: ([region : Region]) (when (region-hilite? region) (mred:queue-callback ; Call it outside the current edit sequence (lambda () ((assert (region-callback region)) (cast cards (Listof (Instance Card%)))) (unhilite-region region))))) regions))))]) (override* [on-default-event (lambda: ([e : (Instance mred:Mouse-Event%)]) NB : rewrote this to avoid huge let (let: ([c : (Option (U 'left 'middle 'right)) (or (and (send e button-down? 'left) 'left) (and (send e button-down? 'right) 'right) (and (send e button-down? 'middle) 'middle))]) (cond [(eq? c last-click) c] [(not last-click) c] ;; Move/drag event has different mouse button, ;; and there was no mouse up. Don't accept the ;; click, yet. [else #f]))) (set! last-click click) (when click (let*: ([actions : (List Boolean Boolean Boolean) (cdr (assert (assoc click button-map)))] [one? (list-ref actions 0)] [backward? (list-ref actions 1)] [raise? (list-ref actions 2)]) (unless (and (eq? backward? select-backward?) (eq? one? select-one?) (eq? raise? raise-to-front?)) (set! select-one? one?) (set! select-backward? backward?) (set! raise-to-front? raise?) (no-selected)))) (let*-values ([(lx ly) (dc-location-to-editor-location (send e get-x) (send e get-y))] [(s) (find-snip lx ly)]) ; Clicking on a "selected" card unselects others ; in this interface (when (send e button-down?) (unless (or (not click-base) (not s) (eq? s click-base)) (no-selected)) NB : cast seems to be needed (when (and dragging? click-base (send (assert click-base) user-can-move)) (for-each (lambda: ([region : Region]) (when (and (not (region-button? region)) (region-callback region) (or (not (region-decided-start? region)) (region-can-select? region))) (let-values ([(sx sy sw sh) (get-region-box region)]) (let ([in? (and (<= sx lx (+ sx sw)) (<= sy ly (+ sy sh)))]) (unless (region-decided-start? region) (set-region-decided-start?! region #t) (set-region-can-select?! region (not in?))) (when (and (not (eq? in? (region-hilite? region))) (region-can-select? region)) (set-region-hilite?! region in?) (when (region-interactive-callback region) ((assert (region-interactive-callback region)) in? (get-reverse-selected-list))) (invalidate-bitmap-cache sx sy sw sh)))))) regions)) ; Can't move => no raise, either (unless (or (not click-base) (send (assert click-base) user-can-move)) (set! raise-to-front? #f)) (let ([was-bg? bg-click?]) (if (send e button-down?) (set! bg-click? (not s)) (when (and bg-click? (not (send e dragging?))) (set! bg-click? #f))) (unless bg-click? (super on-default-event e)) (when (and bg-click? dragging?) ;; We didn't call super on-default-event, so we need ;; to explicitly end the drag: (after-interactive-move e)) (when bg-click? ; Check for clicking on a button region: (for-each (lambda: ([region : Region]) (when (and (region-button? region) (region-callback region)) (let-values ([(sx sy sw sh) (get-region-box region)]) (let ([in? (and (<= sx lx (+ sx sw)) (<= sy ly (+ sy sh)))]) (unless (region-decided-start? region) (set-region-decided-start?! region #t) (set-region-can-select?! region in?)) (when (and (not (eq? in? (region-hilite? region))) (region-can-select? region)) (set-region-hilite?! region in?) (invalidate-bitmap-cache sx sy sw sh)))))) regions)) (when (and was-bg? (not bg-click?)) ; Callback hilighted button: (for-each (lambda: ([region : Region]) (when (region-button? region) (set-region-decided-start?! region #f) (when (region-hilite? region) (mred:queue-callback ; Call it outside the current edit sequence (lambda () NB : changed type in typed - base , but this is a bug (unhilite-region region)))))) regions))) (when (and (send e button-down?) click-base (not (send (assert click-base) user-can-move))) (no-selected))) (when (and click click-base) (do-on-single-click (assert click-base))))] [on-double-click (lambda (s e) (cond [(eq? do-on-double-click 'flip) (begin-edit-sequence) (let ([l (get-reverse-selected-list)]) (for-each (lambda: ([s : (Instance mred:Snip%)]) (let ([s (cast s (Instance Card%))]) (when (send s user-can-flip) (send s flip)))) l) (let loop ([l (reverse l)]) (unless (null? l) (set-before (car l) #f) (loop (cdr l))))) (no-selected) (end-edit-sequence)] [do-on-double-click ((assert do-on-double-click (lambda (x) (not (symbol? x)))) s)] [else (void)]))]) (public* [get-all-list (lambda () (let: loop : (Listof (Instance mred:Snip%)) ([t : (Option (Instance mred:Snip%)) (find-first-snip)] [accum : (Listof (Instance mred:Snip%)) null]) (cond [(not t) (reverse accum)] [else (loop (send t next) (cons t accum))])))] [get-full-box (lambda () (let: ([xb : (Boxof Real) (box 0)] [yb : (Boxof Real) (box 0)] [wb : (Boxof Real) (box 0)] [hb : (Boxof Real) (box 0)]) (send (assert (get-admin)) get-view xb yb wb hb) (values 0 0 (unbox wb) (unbox hb))))] [get-region-box (lambda: ([region : Region]) (values (region-x region) (region-y region) (region-w region) (region-h region)))] [add-region (lambda: ([r : Region]) (set! regions (append regions (list r))) (update-region r))] [remove-region (lambda: ([r : Region]) (set! regions (remq r regions)) (update-region r))] [unhilite-region (lambda: ([region : Region]) (set-region-hilite?! region #f) (update-region region))] [hilite-region (lambda: ([region : Region]) (set-region-hilite?! region #t) (update-region region))] [set-double-click-action (lambda: ([a : (U ((Instance mred:Snip%) -> Void) 'flip)]) (set! do-on-double-click a))] [set-single-click-action (lambda: ([a : ((Instance Card%) -> Void)]) (set! do-on-single-click a))] [set-button-action (lambda: ([button : (U 'left 'middle 'right)] [action : Symbol]) (let: ([map : (List Boolean Boolean Boolean) (case action [(drag/one) (list #t #f #f)] [(drag-raise/one) (list #t #f #t)] [(drag/above) (list #f #f #f)] [(drag-raise/above) (list #f #f #t)] [(drag/below) (list #f #t #f)] [(drag-raise/below) (list #f #t #t)] [else (error 'set-button-action "unknown action: ~s" action)])]) (set! button-map (cons (ann (cons button map) (List (U 'left 'right 'middle) Boolean Boolean Boolean)) (remq (assoc button button-map) button-map)))))]) (super-make-object) (set-selection-visible #f))) (: table% Table%) (define table% (class mred:frame% (init title w h) (inherit reflow-container) (augment* [on-close (lambda () (exit))]) (public* [table-width (lambda () (reflow-container) (let-values ([(x y w h) (send pb get-full-box)]) w))] [table-height (lambda () (reflow-container) (let-values ([(x y w h) (send pb get-full-box)]) h))] [begin-card-sequence (lambda () (set! in-sequence (add1 in-sequence)) (send pb begin-edit-sequence))] [end-card-sequence (lambda () (send pb end-edit-sequence) (set! in-sequence (sub1 in-sequence)))] [add-card (lambda ([card : (Instance Card%)] [x : Real] [y : Real]) (position-cards (list card) x y (lambda (p) (values 0 0)) add-cards-callback))] [add-cards (lambda ([cards : (Listof (Instance Card%))] [x : Real] [y : Real] [offset (lambda (p) (values 0 0))]) (position-cards cards x y offset add-cards-callback))] [add-cards-to-region (lambda ([cards : (Listof (Instance Card%))] [region : Region]) (position-cards-in-region cards region add-cards-callback))] [move-card (lambda ([card : (Instance Card%)] [x : Real] [y : Real]) (position-cards (list card) x y (lambda (p) (values 0 0)) move-cards-callback))] [move-cards (lambda ([cards : (Listof (Instance Card%))] [x : Real] [y : Real] [offset (lambda (p) (values 0 0))]) (position-cards cards x y offset move-cards-callback))] [move-cards-to-region (lambda ([cards : (Listof (Instance Card%))] [region : Region]) (position-cards-in-region cards region (lambda ([c : (Instance Card%)] [x : Real] [y : Real]) (send pb move-to c x y))))] [card-location (lambda ([card : (Instance Card%)]) (let ([x : (Boxof Real) (box 0)] [y : (Boxof Real) (box 0)]) (unless (send pb get-snip-location card x y) (raise-mismatch-error 'card-location "card not on table: " card)) (values (unbox x) (unbox y))))] [all-cards (lambda () (send pb get-all-list))] [remove-card (lambda ([card : (Instance Card%)]) (remove-cards (list card)))] [remove-cards (lambda ([cards : (Listof (Instance Card%))]) (begin-card-sequence) (for-each (lambda ([c : (Instance Card%)]) (send pb release-snip c)) cards) (end-card-sequence))] [flip-card (lambda ([card : (Instance Card%)]) (flip-cards (list card)))] [flip-cards (lambda ([cards : (Listof (Instance Card%))]) (if (or (not animate?) (positive? in-sequence)) (for-each (lambda ([c : (Instance Card%)]) (send c flip)) cards) (let ([flip-step (lambda ([go : (-> Void)]) (let ([start (current-milliseconds)]) (begin-card-sequence) (go) (end-card-sequence) (pause (max 0 (- (/ ANIMATION-TIME ANIMATION-STEPS) (/ (- (current-milliseconds) start) 1000))))))]) (flip-step (lambda () (for-each (lambda ([c : (Instance Card%)]) (send c semi-flip)) cards))) (flip-step (lambda () (for-each (lambda ([c : (Instance Card%)]) (send c flip)) cards))) (flip-step (lambda () (for-each (lambda ([c : (Instance Card%)]) (send c semi-flip)) cards))))))] [rotate-card (lambda ([card : (Instance Card%)] [mode : Mode]) (rotate-cards (list card) mode))] [rotate-cards (lambda ([cards : (Listof (Instance Card%))] [mode : Mode]) (begin-card-sequence) (let ([tw (table-width)] [th (table-height)]) (map (lambda ([c : (Instance Card%)]) (let ([w (send c card-width)] [h (send c card-height)]) (send c rotate mode) (let ([w2 (send c card-width)] [h2 (send c card-height)] [x : (Boxof Real) (box 0)] [y : (Boxof Real) (box 0)]) (send pb get-snip-location c x y) (send pb move-to c (min (max 0 (+ (unbox x) (/ (- w w2) 2))) (- tw w2)) (min (max 0 (+ (unbox y) (/ (- h h2) 2))) (- th h2)))))) cards) (end-card-sequence)))] [card-face-up (lambda ([card : (Instance Card%)]) (cards-face-up (list card)))] [cards-face-up (lambda (cards) (flip-cards (filter (lambda ([c : (Instance Card%)]) (send c face-down?)) cards)))] [card-face-down (lambda ([card : (Instance Card%)]) (cards-face-down (list card)))] [cards-face-down (lambda ([cards : (Listof (Instance Card%))]) (flip-cards (filter (lambda ([c : (Instance Card%)]) (not (send c face-down?))) cards)))] [card-to-front (lambda ([card : (Instance Card%)]) (send pb set-before card #f))] [card-to-back (lambda ([card : (Instance Card%)]) (send pb set-after card #f))] [stack-cards (lambda ([cards : (Listof (Instance Card%))]) (unless (null? cards) (send pb only-front-selected) ; in case overlap changes (begin-card-sequence) (let loop ([l (cdr cards)][behind (car cards)]) (unless (null? l) (send pb set-after (car l) behind) (loop (cdr l) (car l)))) (end-card-sequence)))] [add-region (lambda (r) (send pb add-region r))] [remove-region (lambda (r) (send pb remove-region r))] [hilite-region (lambda (r) (send pb hilite-region r))] [unhilite-region (lambda (r) (send pb unhilite-region r))] [set-button-action (lambda (button action) (send pb set-button-action button action))] [set-double-click-action (lambda ([a : (-> (Instance mred:Snip%) Void)]) (send pb set-double-click-action a))] [set-single-click-action (lambda ([a : (-> (Instance Card%) Void)]) (send pb set-single-click-action a))] [pause (lambda ([duration : Real]) (let ([s (make-semaphore)] [a (alarm-evt (+ (current-inexact-milliseconds) (* duration 1000)))] [enabled? (send c is-enabled?)]) ;; Can't move the cards during this time: (send c enable #f) (mred:yield a) (when enabled? (send c enable #t))))] [animated (case-lambda [() animate?] [(on?) (set! animate? (and on? #t))])] [create-status-pane (lambda () (let ([p (make-object mred:horizontal-pane% this)]) (set! msg (new mred:message% [parent p] [label ""] [stretchable-width #t])) p))] [set-status (lambda ([str : String]) (when msg (send (assert msg) set-label str)))] [add-help-button (lambda ([pane : (Instance mred:Area-Container<%>)] [where : (Listof String)] [title : String] [tt? : Any]) (new mred:button% (parent pane) (label (string-constant help-menu-label)) (callback (let ([show-help (show-help where title tt?)]) (lambda x (show-help))))))] [add-scribble-button (lambda ([pane : (Instance mred:Area-Container<%>)] [mod : Module-Path] [tag : String]) (new mred:button% (parent pane) (label (string-constant help-menu-label)) (callback (let ([show-help (show-scribbling mod tag)]) (lambda x (show-help))))))]) (begin (: msg (Option (Instance mred:Button%))) (define msg #f) (: add-cards-callback (-> (Instance Card%) Real Real Void)) (define add-cards-callback (lambda ([card : (Instance Card%)] [x : Real] [y : Real]) (send pb insert card #f x y))) (: move-cards-callback (-> (Instance Card%) Real Real Boolean)) (define move-cards-callback (lambda ([card : (Instance Card%)] [x : Real] [y : Real]) (send pb move-to card x y) (send card remember-location pb)))) (begin (define animate? #t) (define in-sequence 0)) (: position-cards (-> (Listof (Instance Card%)) Real Real (-> Real (Values Real Real)) (-> (Instance Card%) Real Real Any) Void)) ; la (: position-cards-in-region (-> (Listof (Instance Card%)) Region (-> (Instance Card%) Real Real Any) Void)) (private* [position-cards (lambda ([cards : (Listof (Instance Card%))] [x : Real] [y : Real] [offset : (-> Real (Values Real Real))] set) (let ([positions (let: loop : (Listof (Pairof Real Real)) ([l : (Listof (Instance Card%)) cards][n : Real 0]) (if (null? l) null (let-values ([(dx dy) (offset n)]) (cons (cons (+ x dx) (+ y dy)) (loop (cdr l) (add1 n))))))]) (if (or (not animate?) (positive? in-sequence) (eq? set add-cards-callback)) (begin (begin-card-sequence) (for-each (lambda ([c : (Instance Card%)] [p : (Pairof Real Real)]) (set c (car p) (cdr p))) cards positions) (end-card-sequence)) (let-values ([(moving-cards source-xs source-ys dest-xs dest-ys) (let: loop : (Values (Listof (Instance Card%)) (Listof Real) (Listof Real) (Listof Real) (Listof Real) ) ([cl : (Listof (Instance Card%)) cards][pl : (Listof (Pairof Real Real)) positions]) (if (null? cl) (values null null null null null) (let-values ([(mcl sxl syl dxl dyl) (loop (cdr cl) (cdr pl))] [(card) (car cl)] [(x y) (values (caar pl) (cdar pl))]) (let ([xb : (Boxof Real) (box 0)][yb : (Boxof Real) (box 0)]) (send pb get-snip-location card xb yb) (let ([sx (unbox xb)][sy (unbox yb)]) (if (and (= x sx) (= y sy)) (values mcl sxl syl dxl dyl) (values (cons card mcl) (cons sx sxl) (cons sy syl) (cons x dxl) (cons y dyl))))))))]) (let ([time-scale ;; An animation speed that looks good for ;; long moves looks too slow for short ;; moves. So scale the time back by as much as 50 % if the max distance for all cards ;; is short. (let ([max-delta (max (apply max 0 (map (lambda ([sx : Real] [dx : Real]) (abs (- sx dx))) source-xs dest-xs)) (apply max 0 (map (lambda ([sy : Real] [dy : Real]) (abs (- sy dy))) source-ys dest-ys)))]) (if (max-delta . < . 100) (/ (+ max-delta 100) 200.0) 1))]) (let loop ([n 1]) (unless (> n ANIMATION-STEPS) (let ([start (current-milliseconds)] [scale (lambda ([s : Real] [d : Real]) (+ s (* (/ n ANIMATION-STEPS) (- d s))))]) (begin-card-sequence) (for-each (lambda ([c : (Instance Card%)] [sx : Real] [sy : Real] [dx : Real] [dy : Real]) (set c (scale sx dx) (scale sy dy))) moving-cards source-xs source-ys dest-xs dest-ys) (end-card-sequence) (pause (max 0 (- (/ (* time-scale ANIMATION-TIME) ANIMATION-STEPS) (/ (- (current-milliseconds) start) 1000)))) (loop (add1 n)))))))) ;; In case overlap changed: (send pb only-front-selected)))] [position-cards-in-region (lambda ([cards : (Listof (Instance Card%))] [r : Region] set) (unless (null? cards) (let-values ([(x y w h) (send pb get-region-box r)] [(len) (sub1 (length cards))] [(cw ch) (values (send (car cards) card-width) (send (car cards) card-height))]) (let* ([pretty (lambda ([cw : Real]) (+ (* (add1 len) cw) (* len PRETTY-CARD-SEP-AMOUNT)))] [pw (pretty cw)] [ph (pretty ch)]) (let-values ([(x w) (if (> w pw) (values (+ x (/ (- w pw) 2)) pw) (values x w))] [(y h) (if (> h ph) (values (+ y (/ (- h ph) 2)) ph) (values y h))]) (position-cards cards x y (lambda ([p : Real]) (if (zero? len) (values (/ (- w cw) 2) (/ (- h ch) 2)) (values (* (- len p) (/ (- w cw) len)) (* (- len p) (/ (- h ch) len))))) set))))))]) (super-new [label title] [style '(metal no-resize-border)]) (begin (: c (Instance mred:Editor-Canvas%)) (define c (make-object mred:editor-canvas% this #f '(no-vscroll no-hscroll))) (define: pb : (Instance Pasteboard%) (make-object pasteboard%))) (send c min-client-width (assert (+ 10 (exact-floor (* w (send back get-width)))) positive?)) (send c min-client-height (assert (+ 10 (exact-floor (* h (send back get-height)))) positive?)) (send c stretchable-width #f) (send c stretchable-height #f) (send this stretchable-width #f) (send this stretchable-height #f) (send c set-editor pb))) (: draw-roundish-rectangle ((Instance mred:DC<%>) Real Real Real Real -> Void)) (define (draw-roundish-rectangle dc x y w h) (send dc draw-line (+ x 1) y (+ x w -2) y) (send dc draw-line (+ x 1) (+ y h -1) (+ x w -2) (+ y h -1)) (send dc draw-line x (+ y 1) x (+ y h -2)) (send dc draw-line (+ x w -1) (+ y 1) (+ x w -1) (+ y h -2)));)
null
https://raw.githubusercontent.com/nuprl/gradual-typing-performance/35442b3221299a9cadba6810573007736b0d65d4/pre-benchmark/ecoop/benchmarks/gofish/typed/classes.rkt
racket
benchmark infrastructure replace this with base, after defining interfaces utils.rk inlined here -------------------- constants.rkt inlined here -------------------------- Since we use size-in-pixels, the letters the descender), but the space above the letter center on 12 , splitting the difference for the descender in case overlap changed Call it outside the current edit sequence Move/drag event has different mouse button, and there was no mouse up. Don't accept the click, yet. Clicking on a "selected" card unselects others in this interface Can't move => no raise, either We didn't call super on-default-event, so we need to explicitly end the drag: Check for clicking on a button region: Callback hilighted button: Call it outside the current edit sequence in case overlap changes Can't move the cards during this time: la An animation speed that looks good for long moves looks too slow for short moves. So scale the time back by as much is short. In case overlap changed: )
#lang typed/racket/base (require typed/racket/class (prefix-in mred: typed/racket/gui) racket/math string-constants) (require/typed/if "region-typed.rkt" "region.rkt") (require/typed/check "make-cards.rkt" [back (Instance mred:Bitmap%)]) (require/typed/check "show-help.rkt" [show-help ((Listof String) String Any -> (-> Any))]) (require/typed "show-scribbling.rkt" [show-scribbling (Module-Path String -> (-> Void))]) (provide pasteboard% table%) (define-type Pasteboard% (Class #:implements mred:Pasteboard% [only-front-selected (-> Void)] [get-all-list (-> (Listof (Instance mred:Snip%)))] [get-full-box (-> (Values Real Real Real Real))] [get-region-box (Region -> (Values Real Real Real Real))] [add-region (-> Region Void)] [remove-region (-> Region Void)] [unhilite-region (Region -> Void)] [hilite-region (-> Region Void)] [set-double-click-action (-> (-> (Instance mred:Snip%) Void) Void)] [set-single-click-action (-> (-> (Instance Card%) Void) Void)] [set-button-action (-> (U 'left 'middle 'right) Symbol Void)] (augment [after-select ((Instance mred:Snip%) Any -> Void)] [on-interactive-move ((Instance mred:Mouse-Event%) -> Void)] [after-interactive-move ((Instance mred:Mouse-Event%) -> Void)]))) (provide shuffle-list) (: shuffle-list (All (X) (-> (Listof X) Natural (Listof X)))) (define shuffle-list (lambda (l c) (if (zero? c) l (let-values ([(a b) (let ([half (floor (/ (length l) 2))]) (values (let: loop : (Listof X) ([l : (Listof X) l][n : Natural half]) (if (zero? n) null (cons (car l) (loop (cdr l) (sub1 n))))) (list-tail l half)))]) (shuffle-list (let loop : (Listof X) ([a : (Listof X) a] [b : (Listof X) b] [l : (Listof X) null]) (cond [(null? a) (append (reverse b) l)] [(null? b) (append (reverse a) l)] [(zero? (random 2)) (loop (cdr a) b (cons (car a) l))] [else (loop a (cdr b) (cons (car b) l))])) (sub1 c)))))) (define ANIMATION-STEPS 5) (define ANIMATION-TIME 0.3) (define PRETTY-CARD-SEP-AMOUNT 5) (define black-color (make-object mred:color% "black")) (define white-brush (send mred:the-brush-list find-or-create-brush "white" 'solid)) (define hilite-brush (send mred:the-brush-list find-or-create-brush black-color 'hilite)) (define black-pen (send mred:the-pen-list find-or-create-pen black-color 1 'solid)) (define dark-gray-pen (send mred:the-pen-list find-or-create-pen "dark gray" 1 'solid)) (define no-pen (send mred:the-pen-list find-or-create-pen black-color 1 'transparent)) (define nice-font (send mred:the-font-list find-or-create-font 12 'decorative 'normal 'bold #f 'default #t)) (: pasteboard% Pasteboard%) (define pasteboard% (class mred:pasteboard% (inherit begin-edit-sequence end-edit-sequence get-admin invalidate-bitmap-cache find-next-selected-snip find-first-snip find-snip set-before set-after add-selected is-selected? no-selected set-selected remove-selected get-snip-location move-to dc-location-to-editor-location set-selection-visible) (define: select-one? : Boolean #t) (define: select-backward? : Boolean #f) (define: raise-to-front? : Boolean #f) (: button-map (Listof (List (U 'left 'middle 'right) Boolean Boolean Boolean))) (define button-map '((left #f #f #t) (middle #t #f #t) (right #f #t #f))) (define: do-on-double-click : (U 'flip ((Instance mred:Snip%) -> Void)) 'flip) (define: do-on-single-click : ((Instance Card%) -> Void) void) (define: selecting? : Boolean #f) (define: dragging? : Boolean #f) (define: bg-click? : Boolean #f) (define: click-base : (Option (Instance Card%)) #f) (define: last-click : Any #f) (define: regions : (Listof Region) null) (: update-region (Region -> Void)) (: get-snip-bounds ((Instance mred:Snip%) -> (Values Real Real Real Real))) (: get-reverse-selected-list (-> (Listof (Instance mred:Snip%)))) (: for-each-selected (-> (-> (Instance Card%) Any) Void)) (: make-overlapping-list (-> (Instance mred:Snip%) (Listof (Instance mred:Snip%)) Any (Listof (Instance mred:Snip%)))) (private* [get-snip-bounds (lambda: ([s : (Instance mred:Snip%)]) (let: ([xbox : (Boxof Real) (box 0)] [ybox : (Boxof Real) (box 0)]) (get-snip-location s xbox ybox #f) (let ([l (unbox xbox)] [t (unbox ybox)]) (get-snip-location s xbox ybox #t) (values l t (unbox xbox) (unbox ybox)))))] [for-each-selected (lambda (f) (let: loop : Void ([snip : (Option (Instance mred:Snip%)) (find-next-selected-snip #f)]) (when snip (let ([snip : (Instance Card%) (cast snip (Instance Card%))]) (f snip) (loop (find-next-selected-snip snip))))))] [make-overlapping-list (lambda ([s : (Instance mred:Snip%)] so-far behind?) (let-values ([(sl st sr sb) (get-snip-bounds s)]) (let: loop : (Listof (Instance mred:Snip%)) ([t : (Option (Instance mred:Snip%)) (find-first-snip)] [so-far : (Listof (Instance mred:Snip%)) so-far] [get? : Boolean (not behind?)]) (cond [(not t) so-far] [(eq? s t) (if behind? (loop (send t next) so-far #t) so-far)] [get? (let ([l (if (and (not (memq t so-far)) (let-values ([(tl tt tr tb) (get-snip-bounds t)]) (and (or (<= sl tl sr) (<= sl tr sr)) (or (<= st tt sb) (<= st tb sb))))) FIXME so-far)]) (loop (send t next) l #t))] [else (loop (send t next) so-far #f)]))))] [get-reverse-selected-list (lambda () (let: loop : (Listof (Instance mred:Snip%)) ([s (find-next-selected-snip #f)] [l : (Listof (Instance mred:Snip%)) null]) (if s (loop (find-next-selected-snip s) (cons s l)) l)))] [shuffle cards to shuffle in back->front order (let* ([permuted-list : (Listof (Instance Card%)) (shuffle-list selected-list 7)] [get-pos (lambda ([s : (Instance mred:Snip%)]) (let ([xb : (Boxof Real) (box 0)] [yb : (Boxof Real) (box 0)]) (get-snip-location s xb yb) (cons (unbox xb) (unbox yb))))] [sel-loc-list ((inst map (Pairof Real Real) (Instance mred:Snip%)) get-pos selected-list)] [perm-loc-list ((inst map (Pairof Real Real) (Instance mred:Snip%)) get-pos permuted-list)]) ((inst for-each (Instance Card%) (Pairof Real Real) (Pairof Real Real)) (lambda ([s : (Instance Card%)] [start-pos : (Pairof Real Real)] [end-pos : (Pairof Real Real)]) (let* ([sx : Real (car start-pos)] [sy : Real (cdr start-pos)] [ex : Real (car end-pos)] [ey : Real (cdr end-pos)] [steps (max 1 (floor (/ 50 (length selected-list))))]) (let: loop : Void ([i : Integer 1]) (unless (> i steps) (let ([x (+ sx (* (/ i steps) (- ex sx)))] [y (+ sy (* (/ i steps) (- ey sy)))]) (move-to s x y) (mred:flush-display) (loop (add1 i))))))) permuted-list perm-loc-list sel-loc-list) (let loop ([l permuted-list]) (unless (null? l) (set-before (car l) #f) (loop (cdr l)))) (no-selected)))] [update-region (lambda (region) (let-values ([(sx sy sw sh) (get-region-box region)]) (invalidate-bitmap-cache sx sy sw sh)))]) (public* [only-front-selected (lambda () (let: loop : Void ([s : (Option (Instance mred:Snip%)) (find-next-selected-snip #f)] [ok : (Option (Instance mred:Snip%)) (find-first-snip)]) (when s (if (eq? s ok) (loop (find-next-selected-snip s) (send (assert ok) next)) (let: loop ([s : (Instance mred:Snip%) s] [l : (Listof (Instance mred:Snip%)) (list s)]) (let ([next (find-next-selected-snip s)]) (if next (loop next (cons s l)) (for-each (lambda: ([s : (Instance mred:Snip%)]) (remove-selected s)) l))))))))]) (override* [on-paint (lambda (before? dc l t r b dx dy caret) (when before? (for-each (lambda: ([region : Region]) (when (region-paint-callback region) (let-values ([(sx sy sw sh) (get-region-box region)]) ((assert (region-paint-callback region)) dc (+ dx sx) (+ dy sy) sw sh))) (when (region-label region) (let ([old-b (send dc get-brush)] [old-p (send dc get-pen)]) (let-values ([(sx sy sw sh) (get-region-box region)]) (send dc set-brush (assert white-brush)) (send dc set-pen no-pen) (send dc draw-rectangle (+ dx sx) (+ dy sy) (assert sw positive?) (assert sh positive?)) (send dc set-pen dark-gray-pen) (draw-roundish-rectangle dc (+ dx sx) (+ dy sy) sw sh) (let ([text (region-label region)]) (if (string? text) (let ([old-f (send dc get-font)]) (send dc set-font nice-font) (let-values ([(x y d a) (send dc get-text-extent text)]) (send dc draw-text text (+ dx sx (/ (- sw x) 2)) (if (region-button? region) should really be 12 pixels high ( including (+ dy sy (/ (- sh 12) 2) (- 12 y (/ d -2))) (+ dy sy 5)))) (send dc set-font old-f)) (send dc draw-bitmap (assert text) (+ dx sx (/ (- sw (send (assert text) get-width)) 2)) (+ dy sy (/ (- sh (send (assert text) get-height)) 2)) 'solid black-color (send (assert text) get-loaded-mask)))) (when (region-hilite? region) (send dc set-brush (assert hilite-brush)) (send dc set-pen no-pen) (send dc draw-rectangle (+ dx sx 1) (+ dy sy 1) (assert (- sw 2) positive?) (assert (- sh 2) positive?)))) (send dc set-brush old-b) (send dc set-pen old-p)))) regions)))]) (augment* [after-select (lambda: ([s : (Instance mred:Snip%)] [on? : Any]) (inner (void) after-select s on?) (unless (or (not on?) selecting?) (set! selecting? #t) (if select-one? (when raise-to-front? (set-before s #f)) (begin (begin-edit-sequence) (let ([l : (Listof (Instance mred:Snip%)) (make-overlapping-list s (list s) select-backward?)]) ((inst for-each (Instance mred:Snip%)) (lambda: ([i : (Instance mred:Snip%)]) (add-selected i)) l)) (when raise-to-front? (let loop ([snip (find-next-selected-snip #f)][prev : (Option (Instance mred:Snip%)) #f]) (when snip (if prev (set-after snip prev) (set-before snip #f)) (loop (find-next-selected-snip (assert snip)) snip)))) (end-edit-sequence))) (set! selecting? #f)))] [on-interactive-move (lambda (e) (inner (void) on-interactive-move e) (for-each (lambda: ([region : Region]) (set-region-decided-start?! region #f)) regions) (for-each-selected (lambda: ([snip : (Instance Card%)]) (send snip remember-location this))) (set! dragging? #t))]) (override* [interactive-adjust-move (lambda: ([snip : (Instance mred:Snip%)] [xb : (Boxof Real)] [yb : (Boxof Real)]) (super interactive-adjust-move snip xb yb) (let ([snip (cast snip (Instance Card%))]) (let-values: ([([l : Real] [t : Real] [r : Real] [b : Real]) (get-snip-bounds snip)]) (let-values: ([([rl : Real] [rt : Real] [rw : Real] [rh : Real]) (let: ([r : (Option Region) (send snip stay-in-region)]) (if r (values (region-x r) (region-y r) (region-w r) (region-h r)) (let: ([wb : (Boxof Real) (box 0)][hb : (Boxof Real) (box 0)]) (send (assert (get-admin)) get-view #f #f wb hb) (values 0 0 (unbox wb) (unbox hb)))))]) (let ([max-x (- (+ rl rw) (- r l))] [max-y (- (+ rt rh) (- b t))]) (when (< (unbox xb) rl) (set-box! xb rl)) (when (> (unbox xb) max-x) (set-box! xb max-x)) (when (< (unbox yb) rt) (set-box! yb rt)) (when (> (unbox yb) max-y) (set-box! yb max-y)))))))]) (: after-interactive-move ((Instance mred:Mouse-Event%) -> Void) #:augment ((Instance mred:Mouse-Event%) -> Void)) (augment* [after-interactive-move (lambda: ([e : (Instance mred:Mouse-Event%)]) (when dragging? (set! dragging? #f) (inner (void) after-interactive-move e) (for-each-selected (lambda: ([snip : (Instance Card%)]) (send snip back-to-original-location this))) (let: ([cards : (Listof (Instance mred:Snip%)) (get-reverse-selected-list)]) (for-each (lambda: ([region : Region]) (when (region-hilite? region) (mred:queue-callback (lambda () ((assert (region-callback region)) (cast cards (Listof (Instance Card%)))) (unhilite-region region))))) regions))))]) (override* [on-default-event (lambda: ([e : (Instance mred:Mouse-Event%)]) NB : rewrote this to avoid huge let (let: ([c : (Option (U 'left 'middle 'right)) (or (and (send e button-down? 'left) 'left) (and (send e button-down? 'right) 'right) (and (send e button-down? 'middle) 'middle))]) (cond [(eq? c last-click) c] [(not last-click) c] [else #f]))) (set! last-click click) (when click (let*: ([actions : (List Boolean Boolean Boolean) (cdr (assert (assoc click button-map)))] [one? (list-ref actions 0)] [backward? (list-ref actions 1)] [raise? (list-ref actions 2)]) (unless (and (eq? backward? select-backward?) (eq? one? select-one?) (eq? raise? raise-to-front?)) (set! select-one? one?) (set! select-backward? backward?) (set! raise-to-front? raise?) (no-selected)))) (let*-values ([(lx ly) (dc-location-to-editor-location (send e get-x) (send e get-y))] [(s) (find-snip lx ly)]) (when (send e button-down?) (unless (or (not click-base) (not s) (eq? s click-base)) (no-selected)) NB : cast seems to be needed (when (and dragging? click-base (send (assert click-base) user-can-move)) (for-each (lambda: ([region : Region]) (when (and (not (region-button? region)) (region-callback region) (or (not (region-decided-start? region)) (region-can-select? region))) (let-values ([(sx sy sw sh) (get-region-box region)]) (let ([in? (and (<= sx lx (+ sx sw)) (<= sy ly (+ sy sh)))]) (unless (region-decided-start? region) (set-region-decided-start?! region #t) (set-region-can-select?! region (not in?))) (when (and (not (eq? in? (region-hilite? region))) (region-can-select? region)) (set-region-hilite?! region in?) (when (region-interactive-callback region) ((assert (region-interactive-callback region)) in? (get-reverse-selected-list))) (invalidate-bitmap-cache sx sy sw sh)))))) regions)) (unless (or (not click-base) (send (assert click-base) user-can-move)) (set! raise-to-front? #f)) (let ([was-bg? bg-click?]) (if (send e button-down?) (set! bg-click? (not s)) (when (and bg-click? (not (send e dragging?))) (set! bg-click? #f))) (unless bg-click? (super on-default-event e)) (when (and bg-click? dragging?) (after-interactive-move e)) (when bg-click? (for-each (lambda: ([region : Region]) (when (and (region-button? region) (region-callback region)) (let-values ([(sx sy sw sh) (get-region-box region)]) (let ([in? (and (<= sx lx (+ sx sw)) (<= sy ly (+ sy sh)))]) (unless (region-decided-start? region) (set-region-decided-start?! region #t) (set-region-can-select?! region in?)) (when (and (not (eq? in? (region-hilite? region))) (region-can-select? region)) (set-region-hilite?! region in?) (invalidate-bitmap-cache sx sy sw sh)))))) regions)) (when (and was-bg? (not bg-click?)) (for-each (lambda: ([region : Region]) (when (region-button? region) (set-region-decided-start?! region #f) (when (region-hilite? region) (mred:queue-callback (lambda () NB : changed type in typed - base , but this is a bug (unhilite-region region)))))) regions))) (when (and (send e button-down?) click-base (not (send (assert click-base) user-can-move))) (no-selected))) (when (and click click-base) (do-on-single-click (assert click-base))))] [on-double-click (lambda (s e) (cond [(eq? do-on-double-click 'flip) (begin-edit-sequence) (let ([l (get-reverse-selected-list)]) (for-each (lambda: ([s : (Instance mred:Snip%)]) (let ([s (cast s (Instance Card%))]) (when (send s user-can-flip) (send s flip)))) l) (let loop ([l (reverse l)]) (unless (null? l) (set-before (car l) #f) (loop (cdr l))))) (no-selected) (end-edit-sequence)] [do-on-double-click ((assert do-on-double-click (lambda (x) (not (symbol? x)))) s)] [else (void)]))]) (public* [get-all-list (lambda () (let: loop : (Listof (Instance mred:Snip%)) ([t : (Option (Instance mred:Snip%)) (find-first-snip)] [accum : (Listof (Instance mred:Snip%)) null]) (cond [(not t) (reverse accum)] [else (loop (send t next) (cons t accum))])))] [get-full-box (lambda () (let: ([xb : (Boxof Real) (box 0)] [yb : (Boxof Real) (box 0)] [wb : (Boxof Real) (box 0)] [hb : (Boxof Real) (box 0)]) (send (assert (get-admin)) get-view xb yb wb hb) (values 0 0 (unbox wb) (unbox hb))))] [get-region-box (lambda: ([region : Region]) (values (region-x region) (region-y region) (region-w region) (region-h region)))] [add-region (lambda: ([r : Region]) (set! regions (append regions (list r))) (update-region r))] [remove-region (lambda: ([r : Region]) (set! regions (remq r regions)) (update-region r))] [unhilite-region (lambda: ([region : Region]) (set-region-hilite?! region #f) (update-region region))] [hilite-region (lambda: ([region : Region]) (set-region-hilite?! region #t) (update-region region))] [set-double-click-action (lambda: ([a : (U ((Instance mred:Snip%) -> Void) 'flip)]) (set! do-on-double-click a))] [set-single-click-action (lambda: ([a : ((Instance Card%) -> Void)]) (set! do-on-single-click a))] [set-button-action (lambda: ([button : (U 'left 'middle 'right)] [action : Symbol]) (let: ([map : (List Boolean Boolean Boolean) (case action [(drag/one) (list #t #f #f)] [(drag-raise/one) (list #t #f #t)] [(drag/above) (list #f #f #f)] [(drag-raise/above) (list #f #f #t)] [(drag/below) (list #f #t #f)] [(drag-raise/below) (list #f #t #t)] [else (error 'set-button-action "unknown action: ~s" action)])]) (set! button-map (cons (ann (cons button map) (List (U 'left 'right 'middle) Boolean Boolean Boolean)) (remq (assoc button button-map) button-map)))))]) (super-make-object) (set-selection-visible #f))) (: table% Table%) (define table% (class mred:frame% (init title w h) (inherit reflow-container) (augment* [on-close (lambda () (exit))]) (public* [table-width (lambda () (reflow-container) (let-values ([(x y w h) (send pb get-full-box)]) w))] [table-height (lambda () (reflow-container) (let-values ([(x y w h) (send pb get-full-box)]) h))] [begin-card-sequence (lambda () (set! in-sequence (add1 in-sequence)) (send pb begin-edit-sequence))] [end-card-sequence (lambda () (send pb end-edit-sequence) (set! in-sequence (sub1 in-sequence)))] [add-card (lambda ([card : (Instance Card%)] [x : Real] [y : Real]) (position-cards (list card) x y (lambda (p) (values 0 0)) add-cards-callback))] [add-cards (lambda ([cards : (Listof (Instance Card%))] [x : Real] [y : Real] [offset (lambda (p) (values 0 0))]) (position-cards cards x y offset add-cards-callback))] [add-cards-to-region (lambda ([cards : (Listof (Instance Card%))] [region : Region]) (position-cards-in-region cards region add-cards-callback))] [move-card (lambda ([card : (Instance Card%)] [x : Real] [y : Real]) (position-cards (list card) x y (lambda (p) (values 0 0)) move-cards-callback))] [move-cards (lambda ([cards : (Listof (Instance Card%))] [x : Real] [y : Real] [offset (lambda (p) (values 0 0))]) (position-cards cards x y offset move-cards-callback))] [move-cards-to-region (lambda ([cards : (Listof (Instance Card%))] [region : Region]) (position-cards-in-region cards region (lambda ([c : (Instance Card%)] [x : Real] [y : Real]) (send pb move-to c x y))))] [card-location (lambda ([card : (Instance Card%)]) (let ([x : (Boxof Real) (box 0)] [y : (Boxof Real) (box 0)]) (unless (send pb get-snip-location card x y) (raise-mismatch-error 'card-location "card not on table: " card)) (values (unbox x) (unbox y))))] [all-cards (lambda () (send pb get-all-list))] [remove-card (lambda ([card : (Instance Card%)]) (remove-cards (list card)))] [remove-cards (lambda ([cards : (Listof (Instance Card%))]) (begin-card-sequence) (for-each (lambda ([c : (Instance Card%)]) (send pb release-snip c)) cards) (end-card-sequence))] [flip-card (lambda ([card : (Instance Card%)]) (flip-cards (list card)))] [flip-cards (lambda ([cards : (Listof (Instance Card%))]) (if (or (not animate?) (positive? in-sequence)) (for-each (lambda ([c : (Instance Card%)]) (send c flip)) cards) (let ([flip-step (lambda ([go : (-> Void)]) (let ([start (current-milliseconds)]) (begin-card-sequence) (go) (end-card-sequence) (pause (max 0 (- (/ ANIMATION-TIME ANIMATION-STEPS) (/ (- (current-milliseconds) start) 1000))))))]) (flip-step (lambda () (for-each (lambda ([c : (Instance Card%)]) (send c semi-flip)) cards))) (flip-step (lambda () (for-each (lambda ([c : (Instance Card%)]) (send c flip)) cards))) (flip-step (lambda () (for-each (lambda ([c : (Instance Card%)]) (send c semi-flip)) cards))))))] [rotate-card (lambda ([card : (Instance Card%)] [mode : Mode]) (rotate-cards (list card) mode))] [rotate-cards (lambda ([cards : (Listof (Instance Card%))] [mode : Mode]) (begin-card-sequence) (let ([tw (table-width)] [th (table-height)]) (map (lambda ([c : (Instance Card%)]) (let ([w (send c card-width)] [h (send c card-height)]) (send c rotate mode) (let ([w2 (send c card-width)] [h2 (send c card-height)] [x : (Boxof Real) (box 0)] [y : (Boxof Real) (box 0)]) (send pb get-snip-location c x y) (send pb move-to c (min (max 0 (+ (unbox x) (/ (- w w2) 2))) (- tw w2)) (min (max 0 (+ (unbox y) (/ (- h h2) 2))) (- th h2)))))) cards) (end-card-sequence)))] [card-face-up (lambda ([card : (Instance Card%)]) (cards-face-up (list card)))] [cards-face-up (lambda (cards) (flip-cards (filter (lambda ([c : (Instance Card%)]) (send c face-down?)) cards)))] [card-face-down (lambda ([card : (Instance Card%)]) (cards-face-down (list card)))] [cards-face-down (lambda ([cards : (Listof (Instance Card%))]) (flip-cards (filter (lambda ([c : (Instance Card%)]) (not (send c face-down?))) cards)))] [card-to-front (lambda ([card : (Instance Card%)]) (send pb set-before card #f))] [card-to-back (lambda ([card : (Instance Card%)]) (send pb set-after card #f))] [stack-cards (lambda ([cards : (Listof (Instance Card%))]) (unless (null? cards) (begin-card-sequence) (let loop ([l (cdr cards)][behind (car cards)]) (unless (null? l) (send pb set-after (car l) behind) (loop (cdr l) (car l)))) (end-card-sequence)))] [add-region (lambda (r) (send pb add-region r))] [remove-region (lambda (r) (send pb remove-region r))] [hilite-region (lambda (r) (send pb hilite-region r))] [unhilite-region (lambda (r) (send pb unhilite-region r))] [set-button-action (lambda (button action) (send pb set-button-action button action))] [set-double-click-action (lambda ([a : (-> (Instance mred:Snip%) Void)]) (send pb set-double-click-action a))] [set-single-click-action (lambda ([a : (-> (Instance Card%) Void)]) (send pb set-single-click-action a))] [pause (lambda ([duration : Real]) (let ([s (make-semaphore)] [a (alarm-evt (+ (current-inexact-milliseconds) (* duration 1000)))] [enabled? (send c is-enabled?)]) (send c enable #f) (mred:yield a) (when enabled? (send c enable #t))))] [animated (case-lambda [() animate?] [(on?) (set! animate? (and on? #t))])] [create-status-pane (lambda () (let ([p (make-object mred:horizontal-pane% this)]) (set! msg (new mred:message% [parent p] [label ""] [stretchable-width #t])) p))] [set-status (lambda ([str : String]) (when msg (send (assert msg) set-label str)))] [add-help-button (lambda ([pane : (Instance mred:Area-Container<%>)] [where : (Listof String)] [title : String] [tt? : Any]) (new mred:button% (parent pane) (label (string-constant help-menu-label)) (callback (let ([show-help (show-help where title tt?)]) (lambda x (show-help))))))] [add-scribble-button (lambda ([pane : (Instance mred:Area-Container<%>)] [mod : Module-Path] [tag : String]) (new mred:button% (parent pane) (label (string-constant help-menu-label)) (callback (let ([show-help (show-scribbling mod tag)]) (lambda x (show-help))))))]) (begin (: msg (Option (Instance mred:Button%))) (define msg #f) (: add-cards-callback (-> (Instance Card%) Real Real Void)) (define add-cards-callback (lambda ([card : (Instance Card%)] [x : Real] [y : Real]) (send pb insert card #f x y))) (: move-cards-callback (-> (Instance Card%) Real Real Boolean)) (define move-cards-callback (lambda ([card : (Instance Card%)] [x : Real] [y : Real]) (send pb move-to card x y) (send card remember-location pb)))) (begin (define animate? #t) (define in-sequence 0)) (: position-cards-in-region (-> (Listof (Instance Card%)) Region (-> (Instance Card%) Real Real Any) Void)) (private* [position-cards (lambda ([cards : (Listof (Instance Card%))] [x : Real] [y : Real] [offset : (-> Real (Values Real Real))] set) (let ([positions (let: loop : (Listof (Pairof Real Real)) ([l : (Listof (Instance Card%)) cards][n : Real 0]) (if (null? l) null (let-values ([(dx dy) (offset n)]) (cons (cons (+ x dx) (+ y dy)) (loop (cdr l) (add1 n))))))]) (if (or (not animate?) (positive? in-sequence) (eq? set add-cards-callback)) (begin (begin-card-sequence) (for-each (lambda ([c : (Instance Card%)] [p : (Pairof Real Real)]) (set c (car p) (cdr p))) cards positions) (end-card-sequence)) (let-values ([(moving-cards source-xs source-ys dest-xs dest-ys) (let: loop : (Values (Listof (Instance Card%)) (Listof Real) (Listof Real) (Listof Real) (Listof Real) ) ([cl : (Listof (Instance Card%)) cards][pl : (Listof (Pairof Real Real)) positions]) (if (null? cl) (values null null null null null) (let-values ([(mcl sxl syl dxl dyl) (loop (cdr cl) (cdr pl))] [(card) (car cl)] [(x y) (values (caar pl) (cdar pl))]) (let ([xb : (Boxof Real) (box 0)][yb : (Boxof Real) (box 0)]) (send pb get-snip-location card xb yb) (let ([sx (unbox xb)][sy (unbox yb)]) (if (and (= x sx) (= y sy)) (values mcl sxl syl dxl dyl) (values (cons card mcl) (cons sx sxl) (cons sy syl) (cons x dxl) (cons y dyl))))))))]) (let ([time-scale as 50 % if the max distance for all cards (let ([max-delta (max (apply max 0 (map (lambda ([sx : Real] [dx : Real]) (abs (- sx dx))) source-xs dest-xs)) (apply max 0 (map (lambda ([sy : Real] [dy : Real]) (abs (- sy dy))) source-ys dest-ys)))]) (if (max-delta . < . 100) (/ (+ max-delta 100) 200.0) 1))]) (let loop ([n 1]) (unless (> n ANIMATION-STEPS) (let ([start (current-milliseconds)] [scale (lambda ([s : Real] [d : Real]) (+ s (* (/ n ANIMATION-STEPS) (- d s))))]) (begin-card-sequence) (for-each (lambda ([c : (Instance Card%)] [sx : Real] [sy : Real] [dx : Real] [dy : Real]) (set c (scale sx dx) (scale sy dy))) moving-cards source-xs source-ys dest-xs dest-ys) (end-card-sequence) (pause (max 0 (- (/ (* time-scale ANIMATION-TIME) ANIMATION-STEPS) (/ (- (current-milliseconds) start) 1000)))) (loop (add1 n)))))))) (send pb only-front-selected)))] [position-cards-in-region (lambda ([cards : (Listof (Instance Card%))] [r : Region] set) (unless (null? cards) (let-values ([(x y w h) (send pb get-region-box r)] [(len) (sub1 (length cards))] [(cw ch) (values (send (car cards) card-width) (send (car cards) card-height))]) (let* ([pretty (lambda ([cw : Real]) (+ (* (add1 len) cw) (* len PRETTY-CARD-SEP-AMOUNT)))] [pw (pretty cw)] [ph (pretty ch)]) (let-values ([(x w) (if (> w pw) (values (+ x (/ (- w pw) 2)) pw) (values x w))] [(y h) (if (> h ph) (values (+ y (/ (- h ph) 2)) ph) (values y h))]) (position-cards cards x y (lambda ([p : Real]) (if (zero? len) (values (/ (- w cw) 2) (/ (- h ch) 2)) (values (* (- len p) (/ (- w cw) len)) (* (- len p) (/ (- h ch) len))))) set))))))]) (super-new [label title] [style '(metal no-resize-border)]) (begin (: c (Instance mred:Editor-Canvas%)) (define c (make-object mred:editor-canvas% this #f '(no-vscroll no-hscroll))) (define: pb : (Instance Pasteboard%) (make-object pasteboard%))) (send c min-client-width (assert (+ 10 (exact-floor (* w (send back get-width)))) positive?)) (send c min-client-height (assert (+ 10 (exact-floor (* h (send back get-height)))) positive?)) (send c stretchable-width #f) (send c stretchable-height #f) (send this stretchable-width #f) (send this stretchable-height #f) (send c set-editor pb))) (: draw-roundish-rectangle ((Instance mred:DC<%>) Real Real Real Real -> Void)) (define (draw-roundish-rectangle dc x y w h) (send dc draw-line (+ x 1) y (+ x w -2) y) (send dc draw-line (+ x 1) (+ y h -1) (+ x w -2) (+ y h -1)) (send dc draw-line x (+ y 1) x (+ y h -2))
3a49c0534fe0111384e80a417a42117a32b77b20811ffacba92dcb4498f5bcff
ghcjs/jsaddle-dom
WebGL2RenderingContext.hs
# LANGUAGE PatternSynonyms # -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} # OPTIONS_GHC -fno - warn - unused - imports # module JSDOM.Generated.WebGL2RenderingContext (bufferDataPtr, bufferData, bufferSubData, bufferDataView, bufferSubDataView, copyBufferSubData, getBufferSubData, blitFramebuffer, framebufferTextureLayer, getInternalformatParameter, getInternalformatParameter_, invalidateFramebuffer, invalidateSubFramebuffer, readBuffer, renderbufferStorageMultisample, texStorage2D, texStorage3D, texImage3D, texSubImage3DView, texSubImage3D, copyTexSubImage3D, compressedTexImage3D, compressedTexSubImage3D, getFragDataLocation, getFragDataLocation_, uniform1ui, uniform2ui, uniform3ui, uniform4ui, uniform1uiv, uniform2uiv, uniform3uiv, uniform4uiv, uniformMatrix2x3fv, uniformMatrix3x2fv, uniformMatrix2x4fv, uniformMatrix4x2fv, uniformMatrix3x4fv, uniformMatrix4x3fv, vertexAttribI4i, vertexAttribI4iv, vertexAttribI4ui, vertexAttribI4uiv, vertexAttribIPointer, vertexAttribDivisor, drawArraysInstanced, drawElementsInstanced, drawRangeElements, drawBuffers, clearBufferiv, clearBufferuiv, clearBufferfv, clearBufferfi, createQuery, createQuery_, deleteQuery, isQuery, isQuery_, beginQuery, endQuery, getQuery, getQuery_, getQueryParameter, getQueryParameter_, createSampler, createSampler_, deleteSampler, isSampler, isSampler_, bindSampler, samplerParameteri, samplerParameterf, getSamplerParameter, getSamplerParameter_, fenceSync, fenceSync_, isSync, isSync_, deleteSync, clientWaitSync, clientWaitSync_, waitSync, getSyncParameter, getSyncParameter_, createTransformFeedback, createTransformFeedback_, deleteTransformFeedback, isTransformFeedback, isTransformFeedback_, bindTransformFeedback, beginTransformFeedback, endTransformFeedback, transformFeedbackVaryings, getTransformFeedbackVarying, getTransformFeedbackVarying_, pauseTransformFeedback, resumeTransformFeedback, bindBufferBase, bindBufferRange, getIndexedParameter, getIndexedParameter_, getUniformIndices, getUniformIndices_, getActiveUniforms, getActiveUniforms_, getUniformBlockIndex, getUniformBlockIndex_, getActiveUniformBlockParameter, getActiveUniformBlockParameter_, getActiveUniformBlockName, getActiveUniformBlockName_, uniformBlockBinding, createVertexArray, createVertexArray_, deleteVertexArray, isVertexArray, isVertexArray_, bindVertexArray, pattern READ_BUFFER, pattern UNPACK_ROW_LENGTH, pattern UNPACK_SKIP_ROWS, pattern UNPACK_SKIP_PIXELS, pattern PACK_ROW_LENGTH, pattern PACK_SKIP_ROWS, pattern PACK_SKIP_PIXELS, pattern COLOR, pattern DEPTH, pattern STENCIL, pattern RED, pattern RGB8, pattern RGBA8, pattern RGB10_A2, pattern TEXTURE_BINDING_3D, pattern UNPACK_SKIP_IMAGES, pattern UNPACK_IMAGE_HEIGHT, pattern TEXTURE_3D, pattern TEXTURE_WRAP_R, pattern MAX_3D_TEXTURE_SIZE, pattern UNSIGNED_INT_2_10_10_10_REV, pattern MAX_ELEMENTS_VERTICES, pattern MAX_ELEMENTS_INDICES, pattern TEXTURE_MIN_LOD, pattern TEXTURE_MAX_LOD, pattern TEXTURE_BASE_LEVEL, pattern TEXTURE_MAX_LEVEL, pattern MIN, pattern MAX, pattern DEPTH_COMPONENT24, pattern MAX_TEXTURE_LOD_BIAS, pattern TEXTURE_COMPARE_MODE, pattern TEXTURE_COMPARE_FUNC, pattern CURRENT_QUERY, pattern QUERY_RESULT, pattern QUERY_RESULT_AVAILABLE, pattern STREAM_READ, pattern STREAM_COPY, pattern STATIC_READ, pattern STATIC_COPY, pattern DYNAMIC_READ, pattern DYNAMIC_COPY, pattern MAX_DRAW_BUFFERS, pattern DRAW_BUFFER0, pattern DRAW_BUFFER1, pattern DRAW_BUFFER2, pattern DRAW_BUFFER3, pattern DRAW_BUFFER4, pattern DRAW_BUFFER5, pattern DRAW_BUFFER6, pattern DRAW_BUFFER7, pattern DRAW_BUFFER8, pattern DRAW_BUFFER9, pattern DRAW_BUFFER10, pattern DRAW_BUFFER11, pattern DRAW_BUFFER12, pattern DRAW_BUFFER13, pattern DRAW_BUFFER14, pattern DRAW_BUFFER15, pattern MAX_FRAGMENT_UNIFORM_COMPONENTS, pattern MAX_VERTEX_UNIFORM_COMPONENTS, pattern SAMPLER_3D, pattern SAMPLER_2D_SHADOW, pattern FRAGMENT_SHADER_DERIVATIVE_HINT, pattern PIXEL_PACK_BUFFER, pattern PIXEL_UNPACK_BUFFER, pattern PIXEL_PACK_BUFFER_BINDING, pattern PIXEL_UNPACK_BUFFER_BINDING, pattern FLOAT_MAT2x3, pattern FLOAT_MAT2x4, pattern FLOAT_MAT3x2, pattern FLOAT_MAT3x4, pattern FLOAT_MAT4x2, pattern FLOAT_MAT4x3, pattern SRGB, pattern SRGB8, pattern SRGB8_ALPHA8, pattern COMPARE_REF_TO_TEXTURE, pattern RGBA32F, pattern RGB32F, pattern RGBA16F, pattern RGB16F, pattern VERTEX_ATTRIB_ARRAY_INTEGER, pattern MAX_ARRAY_TEXTURE_LAYERS, pattern MIN_PROGRAM_TEXEL_OFFSET, pattern MAX_PROGRAM_TEXEL_OFFSET, pattern MAX_VARYING_COMPONENTS, pattern TEXTURE_2D_ARRAY, pattern TEXTURE_BINDING_2D_ARRAY, pattern R11F_G11F_B10F, pattern UNSIGNED_INT_10F_11F_11F_REV, pattern RGB9_E5, pattern UNSIGNED_INT_5_9_9_9_REV, pattern TRANSFORM_FEEDBACK_BUFFER_MODE, pattern MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS, pattern TRANSFORM_FEEDBACK_VARYINGS, pattern TRANSFORM_FEEDBACK_BUFFER_START, pattern TRANSFORM_FEEDBACK_BUFFER_SIZE, pattern TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN, pattern RASTERIZER_DISCARD, pattern MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS, pattern MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS, pattern INTERLEAVED_ATTRIBS, pattern SEPARATE_ATTRIBS, pattern TRANSFORM_FEEDBACK_BUFFER, pattern TRANSFORM_FEEDBACK_BUFFER_BINDING, pattern RGBA32UI, pattern RGB32UI, pattern RGBA16UI, pattern RGB16UI, pattern RGBA8UI, pattern RGB8UI, pattern RGBA32I, pattern RGB32I, pattern RGBA16I, pattern RGB16I, pattern RGBA8I, pattern RGB8I, pattern RED_INTEGER, pattern RGB_INTEGER, pattern RGBA_INTEGER, pattern SAMPLER_2D_ARRAY, pattern SAMPLER_2D_ARRAY_SHADOW, pattern SAMPLER_CUBE_SHADOW, pattern UNSIGNED_INT_VEC2, pattern UNSIGNED_INT_VEC3, pattern UNSIGNED_INT_VEC4, pattern INT_SAMPLER_2D, pattern INT_SAMPLER_3D, pattern INT_SAMPLER_CUBE, pattern INT_SAMPLER_2D_ARRAY, pattern UNSIGNED_INT_SAMPLER_2D, pattern UNSIGNED_INT_SAMPLER_3D, pattern UNSIGNED_INT_SAMPLER_CUBE, pattern UNSIGNED_INT_SAMPLER_2D_ARRAY, pattern DEPTH_COMPONENT32F, pattern DEPTH32F_STENCIL8, pattern FLOAT_32_UNSIGNED_INT_24_8_REV, pattern FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING, pattern FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE, pattern FRAMEBUFFER_ATTACHMENT_RED_SIZE, pattern FRAMEBUFFER_ATTACHMENT_GREEN_SIZE, pattern FRAMEBUFFER_ATTACHMENT_BLUE_SIZE, pattern FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE, pattern FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE, pattern FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE, pattern FRAMEBUFFER_DEFAULT, pattern DEPTH_STENCIL_ATTACHMENT, pattern DEPTH_STENCIL, pattern UNSIGNED_INT_24_8, pattern DEPTH24_STENCIL8, pattern UNSIGNED_NORMALIZED, pattern DRAW_FRAMEBUFFER_BINDING, pattern READ_FRAMEBUFFER, pattern DRAW_FRAMEBUFFER, pattern READ_FRAMEBUFFER_BINDING, pattern RENDERBUFFER_SAMPLES, pattern FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER, pattern MAX_COLOR_ATTACHMENTS, pattern COLOR_ATTACHMENT1, pattern COLOR_ATTACHMENT2, pattern COLOR_ATTACHMENT3, pattern COLOR_ATTACHMENT4, pattern COLOR_ATTACHMENT5, pattern COLOR_ATTACHMENT6, pattern COLOR_ATTACHMENT7, pattern COLOR_ATTACHMENT8, pattern COLOR_ATTACHMENT9, pattern COLOR_ATTACHMENT10, pattern COLOR_ATTACHMENT11, pattern COLOR_ATTACHMENT12, pattern COLOR_ATTACHMENT13, pattern COLOR_ATTACHMENT14, pattern COLOR_ATTACHMENT15, pattern FRAMEBUFFER_INCOMPLETE_MULTISAMPLE, pattern MAX_SAMPLES, pattern HALF_FLOAT, pattern RG, pattern RG_INTEGER, pattern R8, pattern RG8, pattern R16F, pattern R32F, pattern RG16F, pattern RG32F, pattern R8I, pattern R8UI, pattern R16I, pattern R16UI, pattern R32I, pattern R32UI, pattern RG8I, pattern RG8UI, pattern RG16I, pattern RG16UI, pattern RG32I, pattern RG32UI, pattern VERTEX_ARRAY_BINDING, pattern R8_SNORM, pattern RG8_SNORM, pattern RGB8_SNORM, pattern RGBA8_SNORM, pattern SIGNED_NORMALIZED, pattern PRIMITIVE_RESTART_FIXED_INDEX, pattern COPY_READ_BUFFER, pattern COPY_WRITE_BUFFER, pattern COPY_READ_BUFFER_BINDING, pattern COPY_WRITE_BUFFER_BINDING, pattern UNIFORM_BUFFER, pattern UNIFORM_BUFFER_BINDING, pattern UNIFORM_BUFFER_START, pattern UNIFORM_BUFFER_SIZE, pattern MAX_VERTEX_UNIFORM_BLOCKS, pattern MAX_FRAGMENT_UNIFORM_BLOCKS, pattern MAX_COMBINED_UNIFORM_BLOCKS, pattern MAX_UNIFORM_BUFFER_BINDINGS, pattern MAX_UNIFORM_BLOCK_SIZE, pattern MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS, pattern MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS, pattern UNIFORM_BUFFER_OFFSET_ALIGNMENT, pattern ACTIVE_UNIFORM_BLOCKS, pattern UNIFORM_TYPE, pattern UNIFORM_SIZE, pattern UNIFORM_BLOCK_INDEX, pattern UNIFORM_OFFSET, pattern UNIFORM_ARRAY_STRIDE, pattern UNIFORM_MATRIX_STRIDE, pattern UNIFORM_IS_ROW_MAJOR, pattern UNIFORM_BLOCK_BINDING, pattern UNIFORM_BLOCK_DATA_SIZE, pattern UNIFORM_BLOCK_ACTIVE_UNIFORMS, pattern UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES, pattern UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER, pattern UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER, pattern INVALID_INDEX, pattern MAX_VERTEX_OUTPUT_COMPONENTS, pattern MAX_FRAGMENT_INPUT_COMPONENTS, pattern MAX_SERVER_WAIT_TIMEOUT, pattern OBJECT_TYPE, pattern SYNC_CONDITION, pattern SYNC_STATUS, pattern SYNC_FLAGS, pattern SYNC_FENCE, pattern SYNC_GPU_COMMANDS_COMPLETE, pattern UNSIGNALED, pattern SIGNALED, pattern ALREADY_SIGNALED, pattern TIMEOUT_EXPIRED, pattern CONDITION_SATISFIED, pattern WAIT_FAILED, pattern SYNC_FLUSH_COMMANDS_BIT, pattern VERTEX_ATTRIB_ARRAY_DIVISOR, pattern ANY_SAMPLES_PASSED, pattern ANY_SAMPLES_PASSED_CONSERVATIVE, pattern SAMPLER_BINDING, pattern RGB10_A2UI, pattern TEXTURE_SWIZZLE_R, pattern TEXTURE_SWIZZLE_G, pattern TEXTURE_SWIZZLE_B, pattern TEXTURE_SWIZZLE_A, pattern GREEN, pattern BLUE, pattern INT_2_10_10_10_REV, pattern TRANSFORM_FEEDBACK, pattern TRANSFORM_FEEDBACK_PAUSED, pattern TRANSFORM_FEEDBACK_ACTIVE, pattern TRANSFORM_FEEDBACK_BINDING, pattern COMPRESSED_R11_EAC, pattern COMPRESSED_SIGNED_R11_EAC, pattern COMPRESSED_RG11_EAC, pattern COMPRESSED_SIGNED_RG11_EAC, pattern COMPRESSED_RGB8_ETC2, pattern COMPRESSED_SRGB8_ETC2, pattern COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2, pattern COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2, pattern COMPRESSED_RGBA8_ETC2_EAC, pattern COMPRESSED_SRGB8_ALPHA8_ETC2_EAC, pattern TEXTURE_IMMUTABLE_FORMAT, pattern MAX_ELEMENT_INDEX, pattern NUM_SAMPLE_COUNTS, pattern TEXTURE_IMMUTABLE_LEVELS, pattern VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE, pattern TIMEOUT_IGNORED, WebGL2RenderingContext(..), gTypeWebGL2RenderingContext) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums | < -US/docs/Web/API/WebGL2RenderingContext.bufferData Mozilla WebGL2RenderingContext.bufferData documentation > bufferDataPtr :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> GLsizeiptr -> GLenum -> m () bufferDataPtr self target size usage = liftDOM (void (self ^. jsf "bufferData" [toJSVal target, integralToDoubleToJSVal size, toJSVal usage])) | < -US/docs/Web/API/WebGL2RenderingContext.bufferData Mozilla WebGL2RenderingContext.bufferData documentation > bufferData :: (MonadDOM m, IsBufferDataSource srcData) => WebGL2RenderingContext -> GLenum -> Maybe srcData -> GLenum -> m () bufferData self target srcData usage = liftDOM (void (self ^. jsf "bufferData" [toJSVal target, toJSVal srcData, toJSVal usage])) | < -US/docs/Web/API/WebGL2RenderingContext.bufferSubData Mozilla WebGL2RenderingContext.bufferSubData documentation > bufferSubData :: (MonadDOM m, IsBufferDataSource srcData) => WebGL2RenderingContext -> GLenum -> GLintptr -> Maybe srcData -> m () bufferSubData self target dstByteOffset srcData = liftDOM (void (self ^. jsf "bufferSubData" [toJSVal target, integralToDoubleToJSVal dstByteOffset, toJSVal srcData])) | < -US/docs/Web/API/WebGL2RenderingContext.bufferData Mozilla WebGL2RenderingContext.bufferData documentation > bufferDataView :: (MonadDOM m, IsArrayBufferView data') => WebGL2RenderingContext -> GLenum -> data' -> GLenum -> GLuint -> Maybe GLuint -> m () bufferDataView self target data' usage srcOffset length = liftDOM (void (self ^. jsf "bufferData" [toJSVal target, toJSVal data', toJSVal usage, toJSVal srcOffset, toJSVal length])) | < -US/docs/Web/API/WebGL2RenderingContext.bufferSubData Mozilla WebGL2RenderingContext.bufferSubData documentation > bufferSubDataView :: (MonadDOM m, IsArrayBufferView srcData) => WebGL2RenderingContext -> GLenum -> GLintptr -> srcData -> GLuint -> Maybe GLuint -> m () bufferSubDataView self target dstByteOffset srcData srcOffset length = liftDOM (void (self ^. jsf "bufferSubData" [toJSVal target, integralToDoubleToJSVal dstByteOffset, toJSVal srcData, toJSVal srcOffset, toJSVal length])) | < -US/docs/Web/API/WebGL2RenderingContext.copyBufferSubData Mozilla WebGL2RenderingContext.copyBufferSubData documentation > copyBufferSubData :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> GLenum -> GLintptr -> GLintptr -> GLsizeiptr -> m () copyBufferSubData self readTarget writeTarget readOffset writeOffset size = liftDOM (void (self ^. jsf "copyBufferSubData" [toJSVal readTarget, toJSVal writeTarget, integralToDoubleToJSVal readOffset, integralToDoubleToJSVal writeOffset, integralToDoubleToJSVal size])) -- | <-US/docs/Web/API/WebGL2RenderingContext.getBufferSubData Mozilla WebGL2RenderingContext.getBufferSubData documentation> getBufferSubData :: (MonadDOM m, IsArrayBufferView dstData) => WebGL2RenderingContext -> GLenum -> GLintptr -> dstData -> Maybe GLuint -> Maybe GLuint -> m () getBufferSubData self target srcByteOffset dstData dstOffset length = liftDOM (void (self ^. jsf "getBufferSubData" [toJSVal target, integralToDoubleToJSVal srcByteOffset, toJSVal dstData, toJSVal dstOffset, toJSVal length])) | < -US/docs/Web/API/WebGL2RenderingContext.blitFramebuffer Mozilla WebGL2RenderingContext.blitFramebuffer documentation > blitFramebuffer :: (MonadDOM m) => WebGL2RenderingContext -> GLint -> GLint -> GLint -> GLint -> GLint -> GLint -> GLint -> GLint -> GLbitfield -> GLenum -> m () blitFramebuffer self srcX0 srcY0 srcX1 srcY1 dstX0 dstY0 dstX1 dstY1 mask filter = liftDOM (void (self ^. jsf "blitFramebuffer" [toJSVal srcX0, toJSVal srcY0, toJSVal srcX1, toJSVal srcY1, toJSVal dstX0, toJSVal dstY0, toJSVal dstX1, toJSVal dstY1, toJSVal mask, toJSVal filter])) | < -US/docs/Web/API/WebGL2RenderingContext.framebufferTextureLayer Mozilla WebGL2RenderingContext.framebufferTextureLayer documentation > framebufferTextureLayer :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> GLenum -> GLuint -> GLint -> GLint -> m () framebufferTextureLayer self target attachment texture level layer = liftDOM (void (self ^. jsf "framebufferTextureLayer" [toJSVal target, toJSVal attachment, toJSVal texture, toJSVal level, toJSVal layer])) | < -US/docs/Web/API/WebGL2RenderingContext.getInternalformatParameter Mozilla WebGL2RenderingContext.getInternalformatParameter documentation > getInternalformatParameter :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> GLenum -> GLenum -> m JSVal getInternalformatParameter self target internalformat pname = liftDOM ((self ^. jsf "getInternalformatParameter" [toJSVal target, toJSVal internalformat, toJSVal pname]) >>= toJSVal) | < -US/docs/Web/API/WebGL2RenderingContext.getInternalformatParameter Mozilla WebGL2RenderingContext.getInternalformatParameter documentation > getInternalformatParameter_ :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> GLenum -> GLenum -> m () getInternalformatParameter_ self target internalformat pname = liftDOM (void (self ^. jsf "getInternalformatParameter" [toJSVal target, toJSVal internalformat, toJSVal pname])) | < -US/docs/Web/API/WebGL2RenderingContext.invalidateFramebuffer Mozilla WebGL2RenderingContext.invalidateFramebuffer documentation > invalidateFramebuffer :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> [GLenum] -> m () invalidateFramebuffer self target attachments = liftDOM (void (self ^. jsf "invalidateFramebuffer" [toJSVal target, toJSVal (array attachments)])) | < -US/docs/Web/API/WebGL2RenderingContext.invalidateSubFramebuffer Mozilla WebGL2RenderingContext.invalidateSubFramebuffer documentation > invalidateSubFramebuffer :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> [GLenum] -> GLint -> GLint -> GLsizei -> GLsizei -> m () invalidateSubFramebuffer self target attachments x y width height = liftDOM (void (self ^. jsf "invalidateSubFramebuffer" [toJSVal target, toJSVal (array attachments), toJSVal x, toJSVal y, toJSVal width, toJSVal height])) | < -US/docs/Web/API/WebGL2RenderingContext.readBuffer Mozilla WebGL2RenderingContext.readBuffer documentation > readBuffer :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> m () readBuffer self src = liftDOM (void (self ^. jsf "readBuffer" [toJSVal src])) | < -US/docs/Web/API/WebGL2RenderingContext.renderbufferStorageMultisample Mozilla WebGL2RenderingContext.renderbufferStorageMultisample documentation > renderbufferStorageMultisample :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> GLsizei -> GLenum -> GLsizei -> GLsizei -> m () renderbufferStorageMultisample self target samples internalformat width height = liftDOM (void (self ^. jsf "renderbufferStorageMultisample" [toJSVal target, toJSVal samples, toJSVal internalformat, toJSVal width, toJSVal height])) -- | <-US/docs/Web/API/WebGL2RenderingContext.texStorage2D Mozilla WebGL2RenderingContext.texStorage2D documentation> texStorage2D :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> GLsizei -> GLenum -> GLsizei -> GLsizei -> m () texStorage2D self target levels internalformat width height = liftDOM (void (self ^. jsf "texStorage2D" [toJSVal target, toJSVal levels, toJSVal internalformat, toJSVal width, toJSVal height])) -- | <-US/docs/Web/API/WebGL2RenderingContext.texStorage3D Mozilla WebGL2RenderingContext.texStorage3D documentation> texStorage3D :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> GLsizei -> GLenum -> GLsizei -> GLsizei -> GLsizei -> m () texStorage3D self target levels internalformat width height depth = liftDOM (void (self ^. jsf "texStorage3D" [toJSVal target, toJSVal levels, toJSVal internalformat, toJSVal width, toJSVal height, toJSVal depth])) | < -US/docs/Web/API/WebGL2RenderingContext.texImage3D Mozilla WebGL2RenderingContext.texImage3D documentation > texImage3D :: (MonadDOM m, IsArrayBufferView pixels) => WebGL2RenderingContext -> GLenum -> GLint -> GLint -> GLsizei -> GLsizei -> GLsizei -> GLint -> GLenum -> GLenum -> Maybe pixels -> m () texImage3D self target level internalformat width height depth border format type' pixels = liftDOM (void (self ^. jsf "texImage3D" [toJSVal target, toJSVal level, toJSVal internalformat, toJSVal width, toJSVal height, toJSVal depth, toJSVal border, toJSVal format, toJSVal type', toJSVal pixels])) -- | <-US/docs/Web/API/WebGL2RenderingContext.texSubImage3D Mozilla WebGL2RenderingContext.texSubImage3D documentation> texSubImage3DView :: (MonadDOM m, IsArrayBufferView pixels) => WebGL2RenderingContext -> GLenum -> GLint -> GLint -> GLint -> GLint -> GLsizei -> GLsizei -> GLsizei -> GLenum -> GLenum -> Maybe pixels -> m () texSubImage3DView self target level xoffset yoffset zoffset width height depth format type' pixels = liftDOM (void (self ^. jsf "texSubImage3D" [toJSVal target, toJSVal level, toJSVal xoffset, toJSVal yoffset, toJSVal zoffset, toJSVal width, toJSVal height, toJSVal depth, toJSVal format, toJSVal type', toJSVal pixels])) -- | <-US/docs/Web/API/WebGL2RenderingContext.texSubImage3D Mozilla WebGL2RenderingContext.texSubImage3D documentation> texSubImage3D :: (MonadDOM m, IsTexImageSource source) => WebGL2RenderingContext -> GLenum -> GLint -> GLint -> GLint -> GLint -> GLenum -> GLenum -> source -> m () texSubImage3D self target level xoffset yoffset zoffset format type' source = liftDOM (void (self ^. jsf "texSubImage3D" [toJSVal target, toJSVal level, toJSVal xoffset, toJSVal yoffset, toJSVal zoffset, toJSVal format, toJSVal type', toJSVal source])) | < -US/docs/Web/API/WebGL2RenderingContext.copyTexSubImage3D Mozilla WebGL2RenderingContext.copyTexSubImage3D documentation > copyTexSubImage3D :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> GLint -> GLint -> GLint -> GLint -> GLint -> GLint -> GLsizei -> GLsizei -> m () copyTexSubImage3D self target level xoffset yoffset zoffset x y width height = liftDOM (void (self ^. jsf "copyTexSubImage3D" [toJSVal target, toJSVal level, toJSVal xoffset, toJSVal yoffset, toJSVal zoffset, toJSVal x, toJSVal y, toJSVal width, toJSVal height])) | < -US/docs/Web/API/WebGL2RenderingContext.compressedTexImage3D Mozilla WebGL2RenderingContext.compressedTexImage3D documentation > compressedTexImage3D :: (MonadDOM m, IsArrayBufferView data') => WebGL2RenderingContext -> GLenum -> GLint -> GLenum -> GLsizei -> GLsizei -> GLsizei -> GLint -> GLsizei -> Maybe data' -> m () compressedTexImage3D self target level internalformat width height depth border imageSize data' = liftDOM (void (self ^. jsf "compressedTexImage3D" [toJSVal target, toJSVal level, toJSVal internalformat, toJSVal width, toJSVal height, toJSVal depth, toJSVal border, toJSVal imageSize, toJSVal data'])) | < -US/docs/Web/API/WebGL2RenderingContext.compressedTexSubImage3D Mozilla WebGL2RenderingContext.compressedTexSubImage3D documentation > compressedTexSubImage3D :: (MonadDOM m, IsArrayBufferView data') => WebGL2RenderingContext -> GLenum -> GLint -> GLint -> GLint -> GLint -> GLsizei -> GLsizei -> GLsizei -> GLenum -> GLsizei -> Maybe data' -> m () compressedTexSubImage3D self target level xoffset yoffset zoffset width height depth format imageSize data' = liftDOM (void (self ^. jsf "compressedTexSubImage3D" [toJSVal target, toJSVal level, toJSVal xoffset, toJSVal yoffset, toJSVal zoffset, toJSVal width, toJSVal height, toJSVal depth, toJSVal format, toJSVal imageSize, toJSVal data'])) | < -US/docs/Web/API/WebGL2RenderingContext.getFragDataLocation Mozilla WebGL2RenderingContext.getFragDataLocation documentation > getFragDataLocation :: (MonadDOM m, ToJSString name) => WebGL2RenderingContext -> Maybe WebGLProgram -> name -> m GLint getFragDataLocation self program name = liftDOM ((self ^. jsf "getFragDataLocation" [toJSVal program, toJSVal name]) >>= fromJSValUnchecked) | < -US/docs/Web/API/WebGL2RenderingContext.getFragDataLocation Mozilla WebGL2RenderingContext.getFragDataLocation documentation > getFragDataLocation_ :: (MonadDOM m, ToJSString name) => WebGL2RenderingContext -> Maybe WebGLProgram -> name -> m () getFragDataLocation_ self program name = liftDOM (void (self ^. jsf "getFragDataLocation" [toJSVal program, toJSVal name])) | < -US/docs/Web/API/WebGL2RenderingContext.uniform1ui Mozilla WebGL2RenderingContext.uniform1ui documentation > uniform1ui :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLUniformLocation -> GLuint -> m () uniform1ui self location v0 = liftDOM (void (self ^. jsf "uniform1ui" [toJSVal location, toJSVal v0])) -- | <-US/docs/Web/API/WebGL2RenderingContext.uniform2ui Mozilla WebGL2RenderingContext.uniform2ui documentation> uniform2ui :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLUniformLocation -> GLuint -> GLuint -> m () uniform2ui self location v0 v1 = liftDOM (void (self ^. jsf "uniform2ui" [toJSVal location, toJSVal v0, toJSVal v1])) | < -US/docs/Web/API/WebGL2RenderingContext.uniform3ui Mozilla WebGL2RenderingContext.uniform3ui documentation > uniform3ui :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLUniformLocation -> GLuint -> GLuint -> GLuint -> m () uniform3ui self location v0 v1 v2 = liftDOM (void (self ^. jsf "uniform3ui" [toJSVal location, toJSVal v0, toJSVal v1, toJSVal v2])) -- | <-US/docs/Web/API/WebGL2RenderingContext.uniform4ui Mozilla WebGL2RenderingContext.uniform4ui documentation> uniform4ui :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLUniformLocation -> GLuint -> GLuint -> GLuint -> GLuint -> m () uniform4ui self location v0 v1 v2 v3 = liftDOM (void (self ^. jsf "uniform4ui" [toJSVal location, toJSVal v0, toJSVal v1, toJSVal v2, toJSVal v3])) | < -US/docs/Web/API/WebGL2RenderingContext.uniform1uiv Mozilla WebGL2RenderingContext.uniform1uiv documentation > uniform1uiv :: (MonadDOM m, IsUint32Array value) => WebGL2RenderingContext -> Maybe WebGLUniformLocation -> Maybe value -> m () uniform1uiv self location value = liftDOM (void (self ^. jsf "uniform1uiv" [toJSVal location, toJSVal value])) | < -US/docs/Web/API/WebGL2RenderingContext.uniform2uiv Mozilla WebGL2RenderingContext.uniform2uiv documentation > uniform2uiv :: (MonadDOM m, IsUint32Array value) => WebGL2RenderingContext -> Maybe WebGLUniformLocation -> Maybe value -> m () uniform2uiv self location value = liftDOM (void (self ^. jsf "uniform2uiv" [toJSVal location, toJSVal value])) | < -US/docs/Web/API/WebGL2RenderingContext.uniform3uiv Mozilla WebGL2RenderingContext.uniform3uiv documentation > uniform3uiv :: (MonadDOM m, IsUint32Array value) => WebGL2RenderingContext -> Maybe WebGLUniformLocation -> Maybe value -> m () uniform3uiv self location value = liftDOM (void (self ^. jsf "uniform3uiv" [toJSVal location, toJSVal value])) | < -US/docs/Web/API/WebGL2RenderingContext.uniform4uiv Mozilla WebGL2RenderingContext.uniform4uiv documentation > uniform4uiv :: (MonadDOM m, IsUint32Array value) => WebGL2RenderingContext -> Maybe WebGLUniformLocation -> Maybe value -> m () uniform4uiv self location value = liftDOM (void (self ^. jsf "uniform4uiv" [toJSVal location, toJSVal value])) -- | <-US/docs/Web/API/WebGL2RenderingContext.uniformMatrix2x3fv Mozilla WebGL2RenderingContext.uniformMatrix2x3fv documentation> uniformMatrix2x3fv :: (MonadDOM m, IsFloat32Array value) => WebGL2RenderingContext -> Maybe WebGLUniformLocation -> GLboolean -> Maybe value -> m () uniformMatrix2x3fv self location transpose value = liftDOM (void (self ^. jsf "uniformMatrix2x3fv" [toJSVal location, toJSVal transpose, toJSVal value])) -- | <-US/docs/Web/API/WebGL2RenderingContext.uniformMatrix3x2fv Mozilla WebGL2RenderingContext.uniformMatrix3x2fv documentation> uniformMatrix3x2fv :: (MonadDOM m, IsFloat32Array value) => WebGL2RenderingContext -> Maybe WebGLUniformLocation -> GLboolean -> Maybe value -> m () uniformMatrix3x2fv self location transpose value = liftDOM (void (self ^. jsf "uniformMatrix3x2fv" [toJSVal location, toJSVal transpose, toJSVal value])) | < WebGL2RenderingContext.uniformMatrix2x4fv documentation > uniformMatrix2x4fv :: (MonadDOM m, IsFloat32Array value) => WebGL2RenderingContext -> Maybe WebGLUniformLocation -> GLboolean -> Maybe value -> m () uniformMatrix2x4fv self location transpose value = liftDOM (void (self ^. jsf "uniformMatrix2x4fv" [toJSVal location, toJSVal transpose, toJSVal value])) -- | <-US/docs/Web/API/WebGL2RenderingContext.uniformMatrix4x2fv Mozilla WebGL2RenderingContext.uniformMatrix4x2fv documentation> uniformMatrix4x2fv :: (MonadDOM m, IsFloat32Array value) => WebGL2RenderingContext -> Maybe WebGLUniformLocation -> GLboolean -> Maybe value -> m () uniformMatrix4x2fv self location transpose value = liftDOM (void (self ^. jsf "uniformMatrix4x2fv" [toJSVal location, toJSVal transpose, toJSVal value])) | < -US/docs/Web/API/WebGL2RenderingContext.uniformMatrix3x4fv Mozilla WebGL2RenderingContext.uniformMatrix3x4fv documentation > uniformMatrix3x4fv :: (MonadDOM m, IsFloat32Array value) => WebGL2RenderingContext -> Maybe WebGLUniformLocation -> GLboolean -> Maybe value -> m () uniformMatrix3x4fv self location transpose value = liftDOM (void (self ^. jsf "uniformMatrix3x4fv" [toJSVal location, toJSVal transpose, toJSVal value])) | < -US/docs/Web/API/WebGL2RenderingContext.uniformMatrix4x3fv Mozilla WebGL2RenderingContext.uniformMatrix4x3fv documentation > uniformMatrix4x3fv :: (MonadDOM m, IsFloat32Array value) => WebGL2RenderingContext -> Maybe WebGLUniformLocation -> GLboolean -> Maybe value -> m () uniformMatrix4x3fv self location transpose value = liftDOM (void (self ^. jsf "uniformMatrix4x3fv" [toJSVal location, toJSVal transpose, toJSVal value])) | < -US/docs/Web/API/WebGL2RenderingContext.vertexAttribI4i Mozilla WebGL2RenderingContext.vertexAttribI4i documentation > vertexAttribI4i :: (MonadDOM m) => WebGL2RenderingContext -> GLuint -> GLint -> GLint -> GLint -> GLint -> m () vertexAttribI4i self index x y z w = liftDOM (void (self ^. jsf "vertexAttribI4i" [toJSVal index, toJSVal x, toJSVal y, toJSVal z, toJSVal w])) | < -US/docs/Web/API/WebGL2RenderingContext.vertexAttribI4iv Mozilla WebGL2RenderingContext.vertexAttribI4iv documentation > vertexAttribI4iv :: (MonadDOM m, IsInt32Array v) => WebGL2RenderingContext -> GLuint -> Maybe v -> m () vertexAttribI4iv self index v = liftDOM (void (self ^. jsf "vertexAttribI4iv" [toJSVal index, toJSVal v])) -- | <-US/docs/Web/API/WebGL2RenderingContext.vertexAttribI4ui Mozilla WebGL2RenderingContext.vertexAttribI4ui documentation> vertexAttribI4ui :: (MonadDOM m) => WebGL2RenderingContext -> GLuint -> GLuint -> GLuint -> GLuint -> GLuint -> m () vertexAttribI4ui self index x y z w = liftDOM (void (self ^. jsf "vertexAttribI4ui" [toJSVal index, toJSVal x, toJSVal y, toJSVal z, toJSVal w])) -- | <-US/docs/Web/API/WebGL2RenderingContext.vertexAttribI4uiv Mozilla WebGL2RenderingContext.vertexAttribI4uiv documentation> vertexAttribI4uiv :: (MonadDOM m, IsUint32Array v) => WebGL2RenderingContext -> GLuint -> Maybe v -> m () vertexAttribI4uiv self index v = liftDOM (void (self ^. jsf "vertexAttribI4uiv" [toJSVal index, toJSVal v])) -- | <-US/docs/Web/API/WebGL2RenderingContext.vertexAttribIPointer Mozilla WebGL2RenderingContext.vertexAttribIPointer documentation> vertexAttribIPointer :: (MonadDOM m) => WebGL2RenderingContext -> GLuint -> GLint -> GLenum -> GLsizei -> GLintptr -> m () vertexAttribIPointer self index size type' stride offset = liftDOM (void (self ^. jsf "vertexAttribIPointer" [toJSVal index, toJSVal size, toJSVal type', toJSVal stride, integralToDoubleToJSVal offset])) | < -US/docs/Web/API/WebGL2RenderingContext.vertexAttribDivisor Mozilla WebGL2RenderingContext.vertexAttribDivisor documentation > vertexAttribDivisor :: (MonadDOM m) => WebGL2RenderingContext -> GLuint -> GLuint -> m () vertexAttribDivisor self index divisor = liftDOM (void (self ^. jsf "vertexAttribDivisor" [toJSVal index, toJSVal divisor])) | < -US/docs/Web/API/WebGL2RenderingContext.drawArraysInstanced Mozilla WebGL2RenderingContext.drawArraysInstanced documentation > drawArraysInstanced :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> GLint -> GLsizei -> GLsizei -> m () drawArraysInstanced self mode first count instanceCount = liftDOM (void (self ^. jsf "drawArraysInstanced" [toJSVal mode, toJSVal first, toJSVal count, toJSVal instanceCount])) -- | <-US/docs/Web/API/WebGL2RenderingContext.drawElementsInstanced Mozilla WebGL2RenderingContext.drawElementsInstanced documentation> drawElementsInstanced :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> GLsizei -> GLenum -> GLintptr -> GLsizei -> m () drawElementsInstanced self mode count type' offset instanceCount = liftDOM (void (self ^. jsf "drawElementsInstanced" [toJSVal mode, toJSVal count, toJSVal type', integralToDoubleToJSVal offset, toJSVal instanceCount])) | < -US/docs/Web/API/WebGL2RenderingContext.drawRangeElements Mozilla WebGL2RenderingContext.drawRangeElements documentation > drawRangeElements :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> GLuint -> GLuint -> GLsizei -> GLenum -> GLintptr -> m () drawRangeElements self mode start end count type' offset = liftDOM (void (self ^. jsf "drawRangeElements" [toJSVal mode, toJSVal start, toJSVal end, toJSVal count, toJSVal type', integralToDoubleToJSVal offset])) | < -US/docs/Web/API/WebGL2RenderingContext.drawBuffers Mozilla WebGL2RenderingContext.drawBuffers documentation > drawBuffers :: (MonadDOM m) => WebGL2RenderingContext -> [GLenum] -> m () drawBuffers self buffers = liftDOM (void (self ^. jsf "drawBuffers" [toJSVal (array buffers)])) | < -US/docs/Web/API/WebGL2RenderingContext.clearBufferiv Mozilla WebGL2RenderingContext.clearBufferiv documentation > clearBufferiv :: (MonadDOM m, IsInt32Array value) => WebGL2RenderingContext -> GLenum -> GLint -> Maybe value -> m () clearBufferiv self buffer drawbuffer value = liftDOM (void (self ^. jsf "clearBufferiv" [toJSVal buffer, toJSVal drawbuffer, toJSVal value])) | < -US/docs/Web/API/WebGL2RenderingContext.clearBufferuiv Mozilla WebGL2RenderingContext.clearBufferuiv documentation > clearBufferuiv :: (MonadDOM m, IsUint32Array value) => WebGL2RenderingContext -> GLenum -> GLint -> Maybe value -> m () clearBufferuiv self buffer drawbuffer value = liftDOM (void (self ^. jsf "clearBufferuiv" [toJSVal buffer, toJSVal drawbuffer, toJSVal value])) | < -US/docs/Web/API/WebGL2RenderingContext.clearBufferfv Mozilla WebGL2RenderingContext.clearBufferfv documentation > clearBufferfv :: (MonadDOM m, IsFloat32Array value) => WebGL2RenderingContext -> GLenum -> GLint -> Maybe value -> m () clearBufferfv self buffer drawbuffer value = liftDOM (void (self ^. jsf "clearBufferfv" [toJSVal buffer, toJSVal drawbuffer, toJSVal value])) -- | <-US/docs/Web/API/WebGL2RenderingContext.clearBufferfi Mozilla WebGL2RenderingContext.clearBufferfi documentation> clearBufferfi :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> GLint -> GLfloat -> GLint -> m () clearBufferfi self buffer drawbuffer depth stencil = liftDOM (void (self ^. jsf "clearBufferfi" [toJSVal buffer, toJSVal drawbuffer, toJSVal depth, toJSVal stencil])) | < -US/docs/Web/API/WebGL2RenderingContext.createQuery Mozilla WebGL2RenderingContext.createQuery documentation > createQuery :: (MonadDOM m) => WebGL2RenderingContext -> m WebGLQuery createQuery self = liftDOM ((self ^. jsf "createQuery" ()) >>= fromJSValUnchecked) | < -US/docs/Web/API/WebGL2RenderingContext.createQuery Mozilla WebGL2RenderingContext.createQuery documentation > createQuery_ :: (MonadDOM m) => WebGL2RenderingContext -> m () createQuery_ self = liftDOM (void (self ^. jsf "createQuery" ())) | < -US/docs/Web/API/WebGL2RenderingContext.deleteQuery Mozilla WebGL2RenderingContext.deleteQuery documentation > deleteQuery :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLQuery -> m () deleteQuery self query = liftDOM (void (self ^. jsf "deleteQuery" [toJSVal query])) -- | <-US/docs/Web/API/WebGL2RenderingContext.isQuery Mozilla WebGL2RenderingContext.isQuery documentation> isQuery :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLQuery -> m GLboolean isQuery self query = liftDOM ((self ^. jsf "isQuery" [toJSVal query]) >>= fromJSValUnchecked) -- | <-US/docs/Web/API/WebGL2RenderingContext.isQuery Mozilla WebGL2RenderingContext.isQuery documentation> isQuery_ :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLQuery -> m () isQuery_ self query = liftDOM (void (self ^. jsf "isQuery" [toJSVal query])) -- | <-US/docs/Web/API/WebGL2RenderingContext.beginQuery Mozilla WebGL2RenderingContext.beginQuery documentation> beginQuery :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> Maybe WebGLQuery -> m () beginQuery self target query = liftDOM (void (self ^. jsf "beginQuery" [toJSVal target, toJSVal query])) | < documentation > endQuery :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> m () endQuery self target = liftDOM (void (self ^. jsf "endQuery" [toJSVal target])) -- | <-US/docs/Web/API/WebGL2RenderingContext.getQuery Mozilla WebGL2RenderingContext.getQuery documentation> getQuery :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> GLenum -> m WebGLQuery getQuery self target pname = liftDOM ((self ^. jsf "getQuery" [toJSVal target, toJSVal pname]) >>= fromJSValUnchecked) -- | <-US/docs/Web/API/WebGL2RenderingContext.getQuery Mozilla WebGL2RenderingContext.getQuery documentation> getQuery_ :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> GLenum -> m () getQuery_ self target pname = liftDOM (void (self ^. jsf "getQuery" [toJSVal target, toJSVal pname])) | < -US/docs/Web/API/WebGL2RenderingContext.getQueryParameter Mozilla WebGL2RenderingContext.getQueryParameter documentation > getQueryParameter :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLQuery -> GLenum -> m JSVal getQueryParameter self query pname = liftDOM ((self ^. jsf "getQueryParameter" [toJSVal query, toJSVal pname]) >>= toJSVal) | < -US/docs/Web/API/WebGL2RenderingContext.getQueryParameter Mozilla WebGL2RenderingContext.getQueryParameter documentation > getQueryParameter_ :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLQuery -> GLenum -> m () getQueryParameter_ self query pname = liftDOM (void (self ^. jsf "getQueryParameter" [toJSVal query, toJSVal pname])) | < -US/docs/Web/API/WebGL2RenderingContext.createSampler Mozilla WebGL2RenderingContext.createSampler documentation > createSampler :: (MonadDOM m) => WebGL2RenderingContext -> m WebGLSampler createSampler self = liftDOM ((self ^. jsf "createSampler" ()) >>= fromJSValUnchecked) | < -US/docs/Web/API/WebGL2RenderingContext.createSampler Mozilla WebGL2RenderingContext.createSampler documentation > createSampler_ :: (MonadDOM m) => WebGL2RenderingContext -> m () createSampler_ self = liftDOM (void (self ^. jsf "createSampler" ())) | < -US/docs/Web/API/WebGL2RenderingContext.deleteSampler Mozilla WebGL2RenderingContext.deleteSampler documentation > deleteSampler :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLSampler -> m () deleteSampler self sampler = liftDOM (void (self ^. jsf "deleteSampler" [toJSVal sampler])) | < -US/docs/Web/API/WebGL2RenderingContext.isSampler Mozilla WebGL2RenderingContext.isSampler documentation > isSampler :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLSampler -> m GLboolean isSampler self sampler = liftDOM ((self ^. jsf "isSampler" [toJSVal sampler]) >>= fromJSValUnchecked) | < -US/docs/Web/API/WebGL2RenderingContext.isSampler Mozilla WebGL2RenderingContext.isSampler documentation > isSampler_ :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLSampler -> m () isSampler_ self sampler = liftDOM (void (self ^. jsf "isSampler" [toJSVal sampler])) | < -US/docs/Web/API/WebGL2RenderingContext.bindSampler Mozilla WebGL2RenderingContext.bindSampler documentation > bindSampler :: (MonadDOM m) => WebGL2RenderingContext -> GLuint -> Maybe WebGLSampler -> m () bindSampler self unit sampler = liftDOM (void (self ^. jsf "bindSampler" [toJSVal unit, toJSVal sampler])) -- | <-US/docs/Web/API/WebGL2RenderingContext.samplerParameteri Mozilla WebGL2RenderingContext.samplerParameteri documentation> samplerParameteri :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLSampler -> GLenum -> GLint -> m () samplerParameteri self sampler pname param = liftDOM (void (self ^. jsf "samplerParameteri" [toJSVal sampler, toJSVal pname, toJSVal param])) | < -US/docs/Web/API/WebGL2RenderingContext.samplerParameterf Mozilla WebGL2RenderingContext.samplerParameterf documentation > samplerParameterf :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLSampler -> GLenum -> GLfloat -> m () samplerParameterf self sampler pname param = liftDOM (void (self ^. jsf "samplerParameterf" [toJSVal sampler, toJSVal pname, toJSVal param])) | < -US/docs/Web/API/WebGL2RenderingContext.getSamplerParameter Mozilla WebGL2RenderingContext.getSamplerParameter documentation > getSamplerParameter :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLSampler -> GLenum -> m JSVal getSamplerParameter self sampler pname = liftDOM ((self ^. jsf "getSamplerParameter" [toJSVal sampler, toJSVal pname]) >>= toJSVal) | < -US/docs/Web/API/WebGL2RenderingContext.getSamplerParameter Mozilla WebGL2RenderingContext.getSamplerParameter documentation > getSamplerParameter_ :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLSampler -> GLenum -> m () getSamplerParameter_ self sampler pname = liftDOM (void (self ^. jsf "getSamplerParameter" [toJSVal sampler, toJSVal pname])) | < -US/docs/Web/API/WebGL2RenderingContext.fenceSync Mozilla WebGL2RenderingContext.fenceSync documentation > fenceSync :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> GLbitfield -> m WebGLSync fenceSync self condition flags = liftDOM ((self ^. jsf "fenceSync" [toJSVal condition, toJSVal flags]) >>= fromJSValUnchecked) | < -US/docs/Web/API/WebGL2RenderingContext.fenceSync Mozilla WebGL2RenderingContext.fenceSync documentation > fenceSync_ :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> GLbitfield -> m () fenceSync_ self condition flags = liftDOM (void (self ^. jsf "fenceSync" [toJSVal condition, toJSVal flags])) | < -US/docs/Web/API/WebGL2RenderingContext.isSync Mozilla WebGL2RenderingContext.isSync documentation > isSync :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLSync -> m GLboolean isSync self sync = liftDOM ((self ^. jsf "isSync" [toJSVal sync]) >>= fromJSValUnchecked) | < -US/docs/Web/API/WebGL2RenderingContext.isSync Mozilla WebGL2RenderingContext.isSync documentation > isSync_ :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLSync -> m () isSync_ self sync = liftDOM (void (self ^. jsf "isSync" [toJSVal sync])) -- | <-US/docs/Web/API/WebGL2RenderingContext.deleteSync Mozilla WebGL2RenderingContext.deleteSync documentation> deleteSync :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLSync -> m () deleteSync self sync = liftDOM (void (self ^. jsf "deleteSync" [toJSVal sync])) -- | <-US/docs/Web/API/WebGL2RenderingContext.clientWaitSync Mozilla WebGL2RenderingContext.clientWaitSync documentation> clientWaitSync :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLSync -> GLbitfield -> GLuint64 -> m GLenum clientWaitSync self sync flags timeout = liftDOM ((self ^. jsf "clientWaitSync" [toJSVal sync, toJSVal flags, integralToDoubleToJSVal timeout]) >>= fromJSValUnchecked) -- | <-US/docs/Web/API/WebGL2RenderingContext.clientWaitSync Mozilla WebGL2RenderingContext.clientWaitSync documentation> clientWaitSync_ :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLSync -> GLbitfield -> GLuint64 -> m () clientWaitSync_ self sync flags timeout = liftDOM (void (self ^. jsf "clientWaitSync" [toJSVal sync, toJSVal flags, integralToDoubleToJSVal timeout])) | < -US/docs/Web/API/WebGL2RenderingContext.waitSync Mozilla WebGL2RenderingContext.waitSync documentation > waitSync :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLSync -> GLbitfield -> GLuint64 -> m () waitSync self sync flags timeout = liftDOM (void (self ^. jsf "waitSync" [toJSVal sync, toJSVal flags, integralToDoubleToJSVal timeout])) | < -US/docs/Web/API/WebGL2RenderingContext.getSyncParameter Mozilla WebGL2RenderingContext.getSyncParameter documentation > getSyncParameter :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLSync -> GLenum -> m JSVal getSyncParameter self sync pname = liftDOM ((self ^. jsf "getSyncParameter" [toJSVal sync, toJSVal pname]) >>= toJSVal) | < -US/docs/Web/API/WebGL2RenderingContext.getSyncParameter Mozilla WebGL2RenderingContext.getSyncParameter documentation > getSyncParameter_ :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLSync -> GLenum -> m () getSyncParameter_ self sync pname = liftDOM (void (self ^. jsf "getSyncParameter" [toJSVal sync, toJSVal pname])) -- | <-US/docs/Web/API/WebGL2RenderingContext.createTransformFeedback Mozilla WebGL2RenderingContext.createTransformFeedback documentation> createTransformFeedback :: (MonadDOM m) => WebGL2RenderingContext -> m WebGLTransformFeedback createTransformFeedback self = liftDOM ((self ^. jsf "createTransformFeedback" ()) >>= fromJSValUnchecked) -- | <-US/docs/Web/API/WebGL2RenderingContext.createTransformFeedback Mozilla WebGL2RenderingContext.createTransformFeedback documentation> createTransformFeedback_ :: (MonadDOM m) => WebGL2RenderingContext -> m () createTransformFeedback_ self = liftDOM (void (self ^. jsf "createTransformFeedback" ())) -- | <-US/docs/Web/API/WebGL2RenderingContext.deleteTransformFeedback Mozilla WebGL2RenderingContext.deleteTransformFeedback documentation> deleteTransformFeedback :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLTransformFeedback -> m () deleteTransformFeedback self id = liftDOM (void (self ^. jsf "deleteTransformFeedback" [toJSVal id])) | < -US/docs/Web/API/WebGL2RenderingContext.isTransformFeedback Mozilla WebGL2RenderingContext.isTransformFeedback documentation > isTransformFeedback :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLTransformFeedback -> m GLboolean isTransformFeedback self id = liftDOM ((self ^. jsf "isTransformFeedback" [toJSVal id]) >>= fromJSValUnchecked) | < -US/docs/Web/API/WebGL2RenderingContext.isTransformFeedback Mozilla WebGL2RenderingContext.isTransformFeedback documentation > isTransformFeedback_ :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLTransformFeedback -> m () isTransformFeedback_ self id = liftDOM (void (self ^. jsf "isTransformFeedback" [toJSVal id])) -- | <-US/docs/Web/API/WebGL2RenderingContext.bindTransformFeedback Mozilla WebGL2RenderingContext.bindTransformFeedback documentation> bindTransformFeedback :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> Maybe WebGLTransformFeedback -> m () bindTransformFeedback self target id = liftDOM (void (self ^. jsf "bindTransformFeedback" [toJSVal target, toJSVal id])) -- | <-US/docs/Web/API/WebGL2RenderingContext.beginTransformFeedback Mozilla WebGL2RenderingContext.beginTransformFeedback documentation> beginTransformFeedback :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> m () beginTransformFeedback self primitiveMode = liftDOM (void (self ^. jsf "beginTransformFeedback" [toJSVal primitiveMode])) | < -US/docs/Web/API/WebGL2RenderingContext.endTransformFeedback Mozilla WebGL2RenderingContext.endTransformFeedback documentation > endTransformFeedback :: (MonadDOM m) => WebGL2RenderingContext -> m () endTransformFeedback self = liftDOM (void (self ^. jsf "endTransformFeedback" ())) | < -US/docs/Web/API/WebGL2RenderingContext.transformFeedbackVaryings Mozilla WebGL2RenderingContext.transformFeedbackVaryings documentation > transformFeedbackVaryings :: (MonadDOM m, ToJSString varyings) => WebGL2RenderingContext -> Maybe WebGLProgram -> [varyings] -> GLenum -> m () transformFeedbackVaryings self program varyings bufferMode = liftDOM (void (self ^. jsf "transformFeedbackVaryings" [toJSVal program, toJSVal (array varyings), toJSVal bufferMode])) | < -US/docs/Web/API/WebGL2RenderingContext.getTransformFeedbackVarying Mozilla WebGL2RenderingContext.getTransformFeedbackVarying documentation > getTransformFeedbackVarying :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLProgram -> GLuint -> m WebGLActiveInfo getTransformFeedbackVarying self program index = liftDOM ((self ^. jsf "getTransformFeedbackVarying" [toJSVal program, toJSVal index]) >>= fromJSValUnchecked) | < -US/docs/Web/API/WebGL2RenderingContext.getTransformFeedbackVarying Mozilla WebGL2RenderingContext.getTransformFeedbackVarying documentation > getTransformFeedbackVarying_ :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLProgram -> GLuint -> m () getTransformFeedbackVarying_ self program index = liftDOM (void (self ^. jsf "getTransformFeedbackVarying" [toJSVal program, toJSVal index])) | < -US/docs/Web/API/WebGL2RenderingContext.pauseTransformFeedback Mozilla WebGL2RenderingContext.pauseTransformFeedback documentation > pauseTransformFeedback :: (MonadDOM m) => WebGL2RenderingContext -> m () pauseTransformFeedback self = liftDOM (void (self ^. jsf "pauseTransformFeedback" ())) -- | <-US/docs/Web/API/WebGL2RenderingContext.resumeTransformFeedback Mozilla WebGL2RenderingContext.resumeTransformFeedback documentation> resumeTransformFeedback :: (MonadDOM m) => WebGL2RenderingContext -> m () resumeTransformFeedback self = liftDOM (void (self ^. jsf "resumeTransformFeedback" ())) | < -US/docs/Web/API/WebGL2RenderingContext.bindBufferBase Mozilla WebGL2RenderingContext.bindBufferBase documentation > bindBufferBase :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> GLuint -> Maybe WebGLBuffer -> m () bindBufferBase self target index buffer = liftDOM (void (self ^. jsf "bindBufferBase" [toJSVal target, toJSVal index, toJSVal buffer])) | < -US/docs/Web/API/WebGL2RenderingContext.bindBufferRange Mozilla WebGL2RenderingContext.bindBufferRange documentation > bindBufferRange :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> GLuint -> Maybe WebGLBuffer -> GLintptr -> GLsizeiptr -> m () bindBufferRange self target index buffer offset size = liftDOM (void (self ^. jsf "bindBufferRange" [toJSVal target, toJSVal index, toJSVal buffer, integralToDoubleToJSVal offset, integralToDoubleToJSVal size])) | < WebGL2RenderingContext.getIndexedParameter documentation > getIndexedParameter :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> GLuint -> m JSVal getIndexedParameter self target index = liftDOM ((self ^. jsf "getIndexedParameter" [toJSVal target, toJSVal index]) >>= toJSVal) | < WebGL2RenderingContext.getIndexedParameter documentation > getIndexedParameter_ :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> GLuint -> m () getIndexedParameter_ self target index = liftDOM (void (self ^. jsf "getIndexedParameter" [toJSVal target, toJSVal index])) | < -US/docs/Web/API/WebGL2RenderingContext.getUniformIndices Mozilla WebGL2RenderingContext.getUniformIndices documentation > getUniformIndices :: (MonadDOM m, ToJSString uniformNames) => WebGL2RenderingContext -> Maybe WebGLProgram -> [uniformNames] -> m Uint32Array getUniformIndices self program uniformNames = liftDOM ((self ^. jsf "getUniformIndices" [toJSVal program, toJSVal (array uniformNames)]) >>= fromJSValUnchecked) | < -US/docs/Web/API/WebGL2RenderingContext.getUniformIndices Mozilla WebGL2RenderingContext.getUniformIndices documentation > getUniformIndices_ :: (MonadDOM m, ToJSString uniformNames) => WebGL2RenderingContext -> Maybe WebGLProgram -> [uniformNames] -> m () getUniformIndices_ self program uniformNames = liftDOM (void (self ^. jsf "getUniformIndices" [toJSVal program, toJSVal (array uniformNames)])) -- | <-US/docs/Web/API/WebGL2RenderingContext.getActiveUniforms Mozilla WebGL2RenderingContext.getActiveUniforms documentation> getActiveUniforms :: (MonadDOM m, IsUint32Array uniformIndices) => WebGL2RenderingContext -> Maybe WebGLProgram -> Maybe uniformIndices -> GLenum -> m Int32Array getActiveUniforms self program uniformIndices pname = liftDOM ((self ^. jsf "getActiveUniforms" [toJSVal program, toJSVal uniformIndices, toJSVal pname]) >>= fromJSValUnchecked) -- | <-US/docs/Web/API/WebGL2RenderingContext.getActiveUniforms Mozilla WebGL2RenderingContext.getActiveUniforms documentation> getActiveUniforms_ :: (MonadDOM m, IsUint32Array uniformIndices) => WebGL2RenderingContext -> Maybe WebGLProgram -> Maybe uniformIndices -> GLenum -> m () getActiveUniforms_ self program uniformIndices pname = liftDOM (void (self ^. jsf "getActiveUniforms" [toJSVal program, toJSVal uniformIndices, toJSVal pname])) | < -US/docs/Web/API/WebGL2RenderingContext.getUniformBlockIndex Mozilla WebGL2RenderingContext.getUniformBlockIndex documentation > getUniformBlockIndex :: (MonadDOM m, ToJSString uniformBlockName) => WebGL2RenderingContext -> Maybe WebGLProgram -> uniformBlockName -> m GLuint getUniformBlockIndex self program uniformBlockName = liftDOM ((self ^. jsf "getUniformBlockIndex" [toJSVal program, toJSVal uniformBlockName]) >>= fromJSValUnchecked) | < -US/docs/Web/API/WebGL2RenderingContext.getUniformBlockIndex Mozilla WebGL2RenderingContext.getUniformBlockIndex documentation > getUniformBlockIndex_ :: (MonadDOM m, ToJSString uniformBlockName) => WebGL2RenderingContext -> Maybe WebGLProgram -> uniformBlockName -> m () getUniformBlockIndex_ self program uniformBlockName = liftDOM (void (self ^. jsf "getUniformBlockIndex" [toJSVal program, toJSVal uniformBlockName])) | < -US/docs/Web/API/WebGL2RenderingContext.getActiveUniformBlockParameter Mozilla WebGL2RenderingContext.getActiveUniformBlockParameter documentation > getActiveUniformBlockParameter :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLProgram -> GLuint -> GLenum -> m JSVal getActiveUniformBlockParameter self program uniformBlockIndex pname = liftDOM ((self ^. jsf "getActiveUniformBlockParameter" [toJSVal program, toJSVal uniformBlockIndex, toJSVal pname]) >>= toJSVal) | < -US/docs/Web/API/WebGL2RenderingContext.getActiveUniformBlockParameter Mozilla WebGL2RenderingContext.getActiveUniformBlockParameter documentation > getActiveUniformBlockParameter_ :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLProgram -> GLuint -> GLenum -> m () getActiveUniformBlockParameter_ self program uniformBlockIndex pname = liftDOM (void (self ^. jsf "getActiveUniformBlockParameter" [toJSVal program, toJSVal uniformBlockIndex, toJSVal pname])) | < -US/docs/Web/API/WebGL2RenderingContext.getActiveUniformBlockName Mozilla WebGL2RenderingContext.getActiveUniformBlockName documentation > getActiveUniformBlockName :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLProgram -> GLuint -> m JSVal getActiveUniformBlockName self program uniformBlockIndex = liftDOM ((self ^. jsf "getActiveUniformBlockName" [toJSVal program, toJSVal uniformBlockIndex]) >>= toJSVal) | < -US/docs/Web/API/WebGL2RenderingContext.getActiveUniformBlockName Mozilla WebGL2RenderingContext.getActiveUniformBlockName documentation > getActiveUniformBlockName_ :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLProgram -> GLuint -> m () getActiveUniformBlockName_ self program uniformBlockIndex = liftDOM (void (self ^. jsf "getActiveUniformBlockName" [toJSVal program, toJSVal uniformBlockIndex])) | < -US/docs/Web/API/WebGL2RenderingContext.uniformBlockBinding Mozilla WebGL2RenderingContext.uniformBlockBinding documentation > uniformBlockBinding :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLProgram -> GLuint -> GLuint -> m () uniformBlockBinding self program uniformBlockIndex uniformBlockBinding = liftDOM (void (self ^. jsf "uniformBlockBinding" [toJSVal program, toJSVal uniformBlockIndex, toJSVal uniformBlockBinding])) | < -US/docs/Web/API/WebGL2RenderingContext.createVertexArray Mozilla WebGL2RenderingContext.createVertexArray documentation > createVertexArray :: (MonadDOM m) => WebGL2RenderingContext -> m WebGLVertexArrayObject createVertexArray self = liftDOM ((self ^. jsf "createVertexArray" ()) >>= fromJSValUnchecked) | < -US/docs/Web/API/WebGL2RenderingContext.createVertexArray Mozilla WebGL2RenderingContext.createVertexArray documentation > createVertexArray_ :: (MonadDOM m) => WebGL2RenderingContext -> m () createVertexArray_ self = liftDOM (void (self ^. jsf "createVertexArray" ())) | < -US/docs/Web/API/WebGL2RenderingContext.deleteVertexArray Mozilla WebGL2RenderingContext.deleteVertexArray documentation > deleteVertexArray :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLVertexArrayObject -> m () deleteVertexArray self vertexArray = liftDOM (void (self ^. jsf "deleteVertexArray" [toJSVal vertexArray])) | < -US/docs/Web/API/WebGL2RenderingContext.isVertexArray Mozilla WebGL2RenderingContext.isVertexArray documentation > isVertexArray :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLVertexArrayObject -> m GLboolean isVertexArray self vertexArray = liftDOM ((self ^. jsf "isVertexArray" [toJSVal vertexArray]) >>= fromJSValUnchecked) | < -US/docs/Web/API/WebGL2RenderingContext.isVertexArray Mozilla WebGL2RenderingContext.isVertexArray documentation > isVertexArray_ :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLVertexArrayObject -> m () isVertexArray_ self vertexArray = liftDOM (void (self ^. jsf "isVertexArray" [toJSVal vertexArray])) -- | <-US/docs/Web/API/WebGL2RenderingContext.bindVertexArray Mozilla WebGL2RenderingContext.bindVertexArray documentation> bindVertexArray :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLVertexArrayObject -> m () bindVertexArray self vertexArray = liftDOM (void (self ^. jsf "bindVertexArray" [toJSVal vertexArray])) pattern READ_BUFFER = 3074 pattern UNPACK_ROW_LENGTH = 3314 pattern UNPACK_SKIP_ROWS = 3315 pattern UNPACK_SKIP_PIXELS = 3316 pattern PACK_ROW_LENGTH = 3330 pattern PACK_SKIP_ROWS = 3331 pattern PACK_SKIP_PIXELS = 3332 pattern COLOR = 6144 pattern DEPTH = 6145 pattern STENCIL = 6146 pattern RED = 6403 pattern RGB8 = 32849 pattern RGBA8 = 32856 pattern RGB10_A2 = 32857 pattern TEXTURE_BINDING_3D = 32874 pattern UNPACK_SKIP_IMAGES = 32877 pattern UNPACK_IMAGE_HEIGHT = 32878 pattern TEXTURE_3D = 32879 pattern TEXTURE_WRAP_R = 32882 pattern MAX_3D_TEXTURE_SIZE = 32883 pattern UNSIGNED_INT_2_10_10_10_REV = 33640 pattern MAX_ELEMENTS_VERTICES = 33000 pattern MAX_ELEMENTS_INDICES = 33001 pattern TEXTURE_MIN_LOD = 33082 pattern TEXTURE_MAX_LOD = 33083 pattern TEXTURE_BASE_LEVEL = 33084 pattern TEXTURE_MAX_LEVEL = 33085 pattern MIN = 32775 pattern MAX = 32776 pattern DEPTH_COMPONENT24 = 33190 pattern MAX_TEXTURE_LOD_BIAS = 34045 pattern TEXTURE_COMPARE_MODE = 34892 pattern TEXTURE_COMPARE_FUNC = 34893 pattern CURRENT_QUERY = 34917 pattern QUERY_RESULT = 34918 pattern QUERY_RESULT_AVAILABLE = 34919 pattern STREAM_READ = 35041 pattern STREAM_COPY = 35042 pattern STATIC_READ = 35045 pattern STATIC_COPY = 35046 pattern DYNAMIC_READ = 35049 pattern DYNAMIC_COPY = 35050 pattern MAX_DRAW_BUFFERS = 34852 pattern DRAW_BUFFER0 = 34853 pattern DRAW_BUFFER1 = 34854 pattern DRAW_BUFFER2 = 34855 pattern DRAW_BUFFER3 = 34856 pattern DRAW_BUFFER4 = 34857 pattern DRAW_BUFFER5 = 34858 pattern DRAW_BUFFER6 = 34859 pattern DRAW_BUFFER7 = 34860 pattern DRAW_BUFFER8 = 34861 pattern DRAW_BUFFER9 = 34862 pattern DRAW_BUFFER10 = 34863 pattern DRAW_BUFFER11 = 34864 pattern DRAW_BUFFER12 = 34865 pattern DRAW_BUFFER13 = 34866 pattern DRAW_BUFFER14 = 34867 pattern DRAW_BUFFER15 = 34868 pattern MAX_FRAGMENT_UNIFORM_COMPONENTS = 35657 pattern MAX_VERTEX_UNIFORM_COMPONENTS = 35658 pattern SAMPLER_3D = 35679 pattern SAMPLER_2D_SHADOW = 35682 pattern FRAGMENT_SHADER_DERIVATIVE_HINT = 35723 pattern PIXEL_PACK_BUFFER = 35051 pattern PIXEL_UNPACK_BUFFER = 35052 pattern PIXEL_PACK_BUFFER_BINDING = 35053 pattern PIXEL_UNPACK_BUFFER_BINDING = 35055 pattern FLOAT_MAT2x3 = 35685 pattern FLOAT_MAT2x4 = 35686 pattern FLOAT_MAT3x2 = 35687 pattern FLOAT_MAT3x4 = 35688 pattern FLOAT_MAT4x2 = 35689 pattern FLOAT_MAT4x3 = 35690 pattern SRGB = 35904 pattern SRGB8 = 35905 pattern SRGB8_ALPHA8 = 35907 pattern COMPARE_REF_TO_TEXTURE = 34894 pattern RGBA32F = 34836 pattern RGB32F = 34837 pattern RGBA16F = 34842 pattern RGB16F = 34843 pattern VERTEX_ATTRIB_ARRAY_INTEGER = 35069 pattern MAX_ARRAY_TEXTURE_LAYERS = 35071 pattern MIN_PROGRAM_TEXEL_OFFSET = 35076 pattern MAX_PROGRAM_TEXEL_OFFSET = 35077 pattern MAX_VARYING_COMPONENTS = 35659 pattern TEXTURE_2D_ARRAY = 35866 pattern TEXTURE_BINDING_2D_ARRAY = 35869 pattern R11F_G11F_B10F = 35898 pattern UNSIGNED_INT_10F_11F_11F_REV = 35899 pattern RGB9_E5 = 35901 pattern UNSIGNED_INT_5_9_9_9_REV = 35902 pattern TRANSFORM_FEEDBACK_BUFFER_MODE = 35967 pattern MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS = 35968 pattern TRANSFORM_FEEDBACK_VARYINGS = 35971 pattern TRANSFORM_FEEDBACK_BUFFER_START = 35972 pattern TRANSFORM_FEEDBACK_BUFFER_SIZE = 35973 pattern TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN = 35976 pattern RASTERIZER_DISCARD = 35977 pattern MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS = 35978 pattern MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS = 35979 pattern INTERLEAVED_ATTRIBS = 35980 pattern SEPARATE_ATTRIBS = 35981 pattern TRANSFORM_FEEDBACK_BUFFER = 35982 pattern TRANSFORM_FEEDBACK_BUFFER_BINDING = 35983 pattern RGBA32UI = 36208 pattern RGB32UI = 36209 pattern RGBA16UI = 36214 pattern RGB16UI = 36215 pattern RGBA8UI = 36220 pattern RGB8UI = 36221 pattern RGBA32I = 36226 pattern RGB32I = 36227 pattern RGBA16I = 36232 pattern RGB16I = 36233 pattern RGBA8I = 36238 pattern RGB8I = 36239 pattern RED_INTEGER = 36244 pattern RGB_INTEGER = 36248 pattern RGBA_INTEGER = 36249 pattern SAMPLER_2D_ARRAY = 36289 pattern SAMPLER_2D_ARRAY_SHADOW = 36292 pattern SAMPLER_CUBE_SHADOW = 36293 pattern UNSIGNED_INT_VEC2 = 36294 pattern UNSIGNED_INT_VEC3 = 36295 pattern UNSIGNED_INT_VEC4 = 36296 pattern INT_SAMPLER_2D = 36298 pattern INT_SAMPLER_3D = 36299 pattern INT_SAMPLER_CUBE = 36300 pattern INT_SAMPLER_2D_ARRAY = 36303 pattern UNSIGNED_INT_SAMPLER_2D = 36306 pattern UNSIGNED_INT_SAMPLER_3D = 36307 pattern UNSIGNED_INT_SAMPLER_CUBE = 36308 pattern UNSIGNED_INT_SAMPLER_2D_ARRAY = 36311 pattern DEPTH_COMPONENT32F = 36012 pattern DEPTH32F_STENCIL8 = 36013 pattern FLOAT_32_UNSIGNED_INT_24_8_REV = 36269 pattern FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING = 33296 pattern FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE = 33297 pattern FRAMEBUFFER_ATTACHMENT_RED_SIZE = 33298 pattern FRAMEBUFFER_ATTACHMENT_GREEN_SIZE = 33299 pattern FRAMEBUFFER_ATTACHMENT_BLUE_SIZE = 33300 pattern FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE = 33301 pattern FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE = 33302 pattern FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE = 33303 pattern FRAMEBUFFER_DEFAULT = 33304 pattern DEPTH_STENCIL_ATTACHMENT = 33306 pattern DEPTH_STENCIL = 34041 pattern UNSIGNED_INT_24_8 = 34042 pattern DEPTH24_STENCIL8 = 35056 pattern UNSIGNED_NORMALIZED = 35863 pattern DRAW_FRAMEBUFFER_BINDING = 36006 pattern READ_FRAMEBUFFER = 36008 pattern DRAW_FRAMEBUFFER = 36009 pattern READ_FRAMEBUFFER_BINDING = 36010 pattern RENDERBUFFER_SAMPLES = 36011 pattern FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER = 36052 pattern MAX_COLOR_ATTACHMENTS = 36063 pattern COLOR_ATTACHMENT1 = 36065 pattern COLOR_ATTACHMENT2 = 36066 pattern COLOR_ATTACHMENT3 = 36067 pattern COLOR_ATTACHMENT4 = 36068 pattern COLOR_ATTACHMENT5 = 36069 pattern COLOR_ATTACHMENT6 = 36070 pattern COLOR_ATTACHMENT7 = 36071 pattern COLOR_ATTACHMENT8 = 36072 pattern COLOR_ATTACHMENT9 = 36073 pattern COLOR_ATTACHMENT10 = 36074 pattern COLOR_ATTACHMENT11 = 36075 pattern COLOR_ATTACHMENT12 = 36076 pattern COLOR_ATTACHMENT13 = 36077 pattern COLOR_ATTACHMENT14 = 36078 pattern COLOR_ATTACHMENT15 = 36079 pattern FRAMEBUFFER_INCOMPLETE_MULTISAMPLE = 36182 pattern MAX_SAMPLES = 36183 pattern HALF_FLOAT = 5131 pattern RG = 33319 pattern RG_INTEGER = 33320 pattern R8 = 33321 pattern RG8 = 33323 pattern R16F = 33325 pattern R32F = 33326 pattern RG16F = 33327 pattern RG32F = 33328 pattern R8I = 33329 pattern R8UI = 33330 pattern R16I = 33331 pattern R16UI = 33332 pattern R32I = 33333 pattern R32UI = 33334 pattern RG8I = 33335 pattern RG8UI = 33336 pattern RG16I = 33337 pattern RG16UI = 33338 pattern RG32I = 33339 pattern RG32UI = 33340 pattern VERTEX_ARRAY_BINDING = 34229 pattern R8_SNORM = 36756 pattern RG8_SNORM = 36757 pattern RGB8_SNORM = 36758 pattern RGBA8_SNORM = 36759 pattern SIGNED_NORMALIZED = 36764 pattern PRIMITIVE_RESTART_FIXED_INDEX = 36201 pattern COPY_READ_BUFFER = 36662 pattern COPY_WRITE_BUFFER = 36663 pattern COPY_READ_BUFFER_BINDING = 36662 pattern COPY_WRITE_BUFFER_BINDING = 36663 pattern UNIFORM_BUFFER = 35345 pattern UNIFORM_BUFFER_BINDING = 35368 pattern UNIFORM_BUFFER_START = 35369 pattern UNIFORM_BUFFER_SIZE = 35370 pattern MAX_VERTEX_UNIFORM_BLOCKS = 35371 pattern MAX_FRAGMENT_UNIFORM_BLOCKS = 35373 pattern MAX_COMBINED_UNIFORM_BLOCKS = 35374 pattern MAX_UNIFORM_BUFFER_BINDINGS = 35375 pattern MAX_UNIFORM_BLOCK_SIZE = 35376 pattern MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS = 35377 pattern MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS = 35379 pattern UNIFORM_BUFFER_OFFSET_ALIGNMENT = 35380 pattern ACTIVE_UNIFORM_BLOCKS = 35382 pattern UNIFORM_TYPE = 35383 pattern UNIFORM_SIZE = 35384 pattern UNIFORM_BLOCK_INDEX = 35386 pattern UNIFORM_OFFSET = 35387 pattern UNIFORM_ARRAY_STRIDE = 35388 pattern UNIFORM_MATRIX_STRIDE = 35389 pattern UNIFORM_IS_ROW_MAJOR = 35390 pattern UNIFORM_BLOCK_BINDING = 35391 pattern UNIFORM_BLOCK_DATA_SIZE = 35392 pattern UNIFORM_BLOCK_ACTIVE_UNIFORMS = 35394 pattern UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES = 35395 pattern UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER = 35396 pattern UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER = 35398 pattern INVALID_INDEX = 4294967295 pattern MAX_VERTEX_OUTPUT_COMPONENTS = 37154 pattern MAX_FRAGMENT_INPUT_COMPONENTS = 37157 pattern MAX_SERVER_WAIT_TIMEOUT = 37137 pattern OBJECT_TYPE = 37138 pattern SYNC_CONDITION = 37139 pattern SYNC_STATUS = 37140 pattern SYNC_FLAGS = 37141 pattern SYNC_FENCE = 37142 pattern SYNC_GPU_COMMANDS_COMPLETE = 37143 pattern UNSIGNALED = 37144 pattern SIGNALED = 37145 pattern ALREADY_SIGNALED = 37146 pattern TIMEOUT_EXPIRED = 37147 pattern CONDITION_SATISFIED = 37148 pattern WAIT_FAILED = 37149 pattern SYNC_FLUSH_COMMANDS_BIT = 1 pattern VERTEX_ATTRIB_ARRAY_DIVISOR = 35070 pattern ANY_SAMPLES_PASSED = 35887 pattern ANY_SAMPLES_PASSED_CONSERVATIVE = 36202 pattern SAMPLER_BINDING = 35097 pattern RGB10_A2UI = 36975 pattern TEXTURE_SWIZZLE_R = 36418 pattern TEXTURE_SWIZZLE_G = 36419 pattern TEXTURE_SWIZZLE_B = 36420 pattern TEXTURE_SWIZZLE_A = 36421 pattern GREEN = 6404 pattern BLUE = 6405 pattern INT_2_10_10_10_REV = 36255 pattern TRANSFORM_FEEDBACK = 36386 pattern TRANSFORM_FEEDBACK_PAUSED = 36387 pattern TRANSFORM_FEEDBACK_ACTIVE = 36388 pattern TRANSFORM_FEEDBACK_BINDING = 36389 pattern COMPRESSED_R11_EAC = 37488 pattern COMPRESSED_SIGNED_R11_EAC = 37489 pattern COMPRESSED_RG11_EAC = 37490 pattern COMPRESSED_SIGNED_RG11_EAC = 37491 pattern COMPRESSED_RGB8_ETC2 = 37492 pattern COMPRESSED_SRGB8_ETC2 = 37493 pattern COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 37494 pattern COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 37495 pattern COMPRESSED_RGBA8_ETC2_EAC = 37496 pattern COMPRESSED_SRGB8_ALPHA8_ETC2_EAC = 37497 pattern TEXTURE_IMMUTABLE_FORMAT = 37167 pattern MAX_ELEMENT_INDEX = 36203 pattern NUM_SAMPLE_COUNTS = 37760 pattern TEXTURE_IMMUTABLE_LEVELS = 33503 pattern VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE = 35070 pattern TIMEOUT_IGNORED = 18446744073709551615
null
https://raw.githubusercontent.com/ghcjs/jsaddle-dom/5f5094277d4b11f3dc3e2df6bb437b75712d268f/src/JSDOM/Generated/WebGL2RenderingContext.hs
haskell
For HasCallStack compatibility # LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures # | <-US/docs/Web/API/WebGL2RenderingContext.getBufferSubData Mozilla WebGL2RenderingContext.getBufferSubData documentation> | <-US/docs/Web/API/WebGL2RenderingContext.texStorage2D Mozilla WebGL2RenderingContext.texStorage2D documentation> | <-US/docs/Web/API/WebGL2RenderingContext.texStorage3D Mozilla WebGL2RenderingContext.texStorage3D documentation> | <-US/docs/Web/API/WebGL2RenderingContext.texSubImage3D Mozilla WebGL2RenderingContext.texSubImage3D documentation> | <-US/docs/Web/API/WebGL2RenderingContext.texSubImage3D Mozilla WebGL2RenderingContext.texSubImage3D documentation> | <-US/docs/Web/API/WebGL2RenderingContext.uniform2ui Mozilla WebGL2RenderingContext.uniform2ui documentation> | <-US/docs/Web/API/WebGL2RenderingContext.uniform4ui Mozilla WebGL2RenderingContext.uniform4ui documentation> | <-US/docs/Web/API/WebGL2RenderingContext.uniformMatrix2x3fv Mozilla WebGL2RenderingContext.uniformMatrix2x3fv documentation> | <-US/docs/Web/API/WebGL2RenderingContext.uniformMatrix3x2fv Mozilla WebGL2RenderingContext.uniformMatrix3x2fv documentation> | <-US/docs/Web/API/WebGL2RenderingContext.uniformMatrix4x2fv Mozilla WebGL2RenderingContext.uniformMatrix4x2fv documentation> | <-US/docs/Web/API/WebGL2RenderingContext.vertexAttribI4ui Mozilla WebGL2RenderingContext.vertexAttribI4ui documentation> | <-US/docs/Web/API/WebGL2RenderingContext.vertexAttribI4uiv Mozilla WebGL2RenderingContext.vertexAttribI4uiv documentation> | <-US/docs/Web/API/WebGL2RenderingContext.vertexAttribIPointer Mozilla WebGL2RenderingContext.vertexAttribIPointer documentation> | <-US/docs/Web/API/WebGL2RenderingContext.drawElementsInstanced Mozilla WebGL2RenderingContext.drawElementsInstanced documentation> | <-US/docs/Web/API/WebGL2RenderingContext.clearBufferfi Mozilla WebGL2RenderingContext.clearBufferfi documentation> | <-US/docs/Web/API/WebGL2RenderingContext.isQuery Mozilla WebGL2RenderingContext.isQuery documentation> | <-US/docs/Web/API/WebGL2RenderingContext.isQuery Mozilla WebGL2RenderingContext.isQuery documentation> | <-US/docs/Web/API/WebGL2RenderingContext.beginQuery Mozilla WebGL2RenderingContext.beginQuery documentation> | <-US/docs/Web/API/WebGL2RenderingContext.getQuery Mozilla WebGL2RenderingContext.getQuery documentation> | <-US/docs/Web/API/WebGL2RenderingContext.getQuery Mozilla WebGL2RenderingContext.getQuery documentation> | <-US/docs/Web/API/WebGL2RenderingContext.samplerParameteri Mozilla WebGL2RenderingContext.samplerParameteri documentation> | <-US/docs/Web/API/WebGL2RenderingContext.deleteSync Mozilla WebGL2RenderingContext.deleteSync documentation> | <-US/docs/Web/API/WebGL2RenderingContext.clientWaitSync Mozilla WebGL2RenderingContext.clientWaitSync documentation> | <-US/docs/Web/API/WebGL2RenderingContext.clientWaitSync Mozilla WebGL2RenderingContext.clientWaitSync documentation> | <-US/docs/Web/API/WebGL2RenderingContext.createTransformFeedback Mozilla WebGL2RenderingContext.createTransformFeedback documentation> | <-US/docs/Web/API/WebGL2RenderingContext.createTransformFeedback Mozilla WebGL2RenderingContext.createTransformFeedback documentation> | <-US/docs/Web/API/WebGL2RenderingContext.deleteTransformFeedback Mozilla WebGL2RenderingContext.deleteTransformFeedback documentation> | <-US/docs/Web/API/WebGL2RenderingContext.bindTransformFeedback Mozilla WebGL2RenderingContext.bindTransformFeedback documentation> | <-US/docs/Web/API/WebGL2RenderingContext.beginTransformFeedback Mozilla WebGL2RenderingContext.beginTransformFeedback documentation> | <-US/docs/Web/API/WebGL2RenderingContext.resumeTransformFeedback Mozilla WebGL2RenderingContext.resumeTransformFeedback documentation> | <-US/docs/Web/API/WebGL2RenderingContext.getActiveUniforms Mozilla WebGL2RenderingContext.getActiveUniforms documentation> | <-US/docs/Web/API/WebGL2RenderingContext.getActiveUniforms Mozilla WebGL2RenderingContext.getActiveUniforms documentation> | <-US/docs/Web/API/WebGL2RenderingContext.bindVertexArray Mozilla WebGL2RenderingContext.bindVertexArray documentation>
# LANGUAGE PatternSynonyms # # OPTIONS_GHC -fno - warn - unused - imports # module JSDOM.Generated.WebGL2RenderingContext (bufferDataPtr, bufferData, bufferSubData, bufferDataView, bufferSubDataView, copyBufferSubData, getBufferSubData, blitFramebuffer, framebufferTextureLayer, getInternalformatParameter, getInternalformatParameter_, invalidateFramebuffer, invalidateSubFramebuffer, readBuffer, renderbufferStorageMultisample, texStorage2D, texStorage3D, texImage3D, texSubImage3DView, texSubImage3D, copyTexSubImage3D, compressedTexImage3D, compressedTexSubImage3D, getFragDataLocation, getFragDataLocation_, uniform1ui, uniform2ui, uniform3ui, uniform4ui, uniform1uiv, uniform2uiv, uniform3uiv, uniform4uiv, uniformMatrix2x3fv, uniformMatrix3x2fv, uniformMatrix2x4fv, uniformMatrix4x2fv, uniformMatrix3x4fv, uniformMatrix4x3fv, vertexAttribI4i, vertexAttribI4iv, vertexAttribI4ui, vertexAttribI4uiv, vertexAttribIPointer, vertexAttribDivisor, drawArraysInstanced, drawElementsInstanced, drawRangeElements, drawBuffers, clearBufferiv, clearBufferuiv, clearBufferfv, clearBufferfi, createQuery, createQuery_, deleteQuery, isQuery, isQuery_, beginQuery, endQuery, getQuery, getQuery_, getQueryParameter, getQueryParameter_, createSampler, createSampler_, deleteSampler, isSampler, isSampler_, bindSampler, samplerParameteri, samplerParameterf, getSamplerParameter, getSamplerParameter_, fenceSync, fenceSync_, isSync, isSync_, deleteSync, clientWaitSync, clientWaitSync_, waitSync, getSyncParameter, getSyncParameter_, createTransformFeedback, createTransformFeedback_, deleteTransformFeedback, isTransformFeedback, isTransformFeedback_, bindTransformFeedback, beginTransformFeedback, endTransformFeedback, transformFeedbackVaryings, getTransformFeedbackVarying, getTransformFeedbackVarying_, pauseTransformFeedback, resumeTransformFeedback, bindBufferBase, bindBufferRange, getIndexedParameter, getIndexedParameter_, getUniformIndices, getUniformIndices_, getActiveUniforms, getActiveUniforms_, getUniformBlockIndex, getUniformBlockIndex_, getActiveUniformBlockParameter, getActiveUniformBlockParameter_, getActiveUniformBlockName, getActiveUniformBlockName_, uniformBlockBinding, createVertexArray, createVertexArray_, deleteVertexArray, isVertexArray, isVertexArray_, bindVertexArray, pattern READ_BUFFER, pattern UNPACK_ROW_LENGTH, pattern UNPACK_SKIP_ROWS, pattern UNPACK_SKIP_PIXELS, pattern PACK_ROW_LENGTH, pattern PACK_SKIP_ROWS, pattern PACK_SKIP_PIXELS, pattern COLOR, pattern DEPTH, pattern STENCIL, pattern RED, pattern RGB8, pattern RGBA8, pattern RGB10_A2, pattern TEXTURE_BINDING_3D, pattern UNPACK_SKIP_IMAGES, pattern UNPACK_IMAGE_HEIGHT, pattern TEXTURE_3D, pattern TEXTURE_WRAP_R, pattern MAX_3D_TEXTURE_SIZE, pattern UNSIGNED_INT_2_10_10_10_REV, pattern MAX_ELEMENTS_VERTICES, pattern MAX_ELEMENTS_INDICES, pattern TEXTURE_MIN_LOD, pattern TEXTURE_MAX_LOD, pattern TEXTURE_BASE_LEVEL, pattern TEXTURE_MAX_LEVEL, pattern MIN, pattern MAX, pattern DEPTH_COMPONENT24, pattern MAX_TEXTURE_LOD_BIAS, pattern TEXTURE_COMPARE_MODE, pattern TEXTURE_COMPARE_FUNC, pattern CURRENT_QUERY, pattern QUERY_RESULT, pattern QUERY_RESULT_AVAILABLE, pattern STREAM_READ, pattern STREAM_COPY, pattern STATIC_READ, pattern STATIC_COPY, pattern DYNAMIC_READ, pattern DYNAMIC_COPY, pattern MAX_DRAW_BUFFERS, pattern DRAW_BUFFER0, pattern DRAW_BUFFER1, pattern DRAW_BUFFER2, pattern DRAW_BUFFER3, pattern DRAW_BUFFER4, pattern DRAW_BUFFER5, pattern DRAW_BUFFER6, pattern DRAW_BUFFER7, pattern DRAW_BUFFER8, pattern DRAW_BUFFER9, pattern DRAW_BUFFER10, pattern DRAW_BUFFER11, pattern DRAW_BUFFER12, pattern DRAW_BUFFER13, pattern DRAW_BUFFER14, pattern DRAW_BUFFER15, pattern MAX_FRAGMENT_UNIFORM_COMPONENTS, pattern MAX_VERTEX_UNIFORM_COMPONENTS, pattern SAMPLER_3D, pattern SAMPLER_2D_SHADOW, pattern FRAGMENT_SHADER_DERIVATIVE_HINT, pattern PIXEL_PACK_BUFFER, pattern PIXEL_UNPACK_BUFFER, pattern PIXEL_PACK_BUFFER_BINDING, pattern PIXEL_UNPACK_BUFFER_BINDING, pattern FLOAT_MAT2x3, pattern FLOAT_MAT2x4, pattern FLOAT_MAT3x2, pattern FLOAT_MAT3x4, pattern FLOAT_MAT4x2, pattern FLOAT_MAT4x3, pattern SRGB, pattern SRGB8, pattern SRGB8_ALPHA8, pattern COMPARE_REF_TO_TEXTURE, pattern RGBA32F, pattern RGB32F, pattern RGBA16F, pattern RGB16F, pattern VERTEX_ATTRIB_ARRAY_INTEGER, pattern MAX_ARRAY_TEXTURE_LAYERS, pattern MIN_PROGRAM_TEXEL_OFFSET, pattern MAX_PROGRAM_TEXEL_OFFSET, pattern MAX_VARYING_COMPONENTS, pattern TEXTURE_2D_ARRAY, pattern TEXTURE_BINDING_2D_ARRAY, pattern R11F_G11F_B10F, pattern UNSIGNED_INT_10F_11F_11F_REV, pattern RGB9_E5, pattern UNSIGNED_INT_5_9_9_9_REV, pattern TRANSFORM_FEEDBACK_BUFFER_MODE, pattern MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS, pattern TRANSFORM_FEEDBACK_VARYINGS, pattern TRANSFORM_FEEDBACK_BUFFER_START, pattern TRANSFORM_FEEDBACK_BUFFER_SIZE, pattern TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN, pattern RASTERIZER_DISCARD, pattern MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS, pattern MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS, pattern INTERLEAVED_ATTRIBS, pattern SEPARATE_ATTRIBS, pattern TRANSFORM_FEEDBACK_BUFFER, pattern TRANSFORM_FEEDBACK_BUFFER_BINDING, pattern RGBA32UI, pattern RGB32UI, pattern RGBA16UI, pattern RGB16UI, pattern RGBA8UI, pattern RGB8UI, pattern RGBA32I, pattern RGB32I, pattern RGBA16I, pattern RGB16I, pattern RGBA8I, pattern RGB8I, pattern RED_INTEGER, pattern RGB_INTEGER, pattern RGBA_INTEGER, pattern SAMPLER_2D_ARRAY, pattern SAMPLER_2D_ARRAY_SHADOW, pattern SAMPLER_CUBE_SHADOW, pattern UNSIGNED_INT_VEC2, pattern UNSIGNED_INT_VEC3, pattern UNSIGNED_INT_VEC4, pattern INT_SAMPLER_2D, pattern INT_SAMPLER_3D, pattern INT_SAMPLER_CUBE, pattern INT_SAMPLER_2D_ARRAY, pattern UNSIGNED_INT_SAMPLER_2D, pattern UNSIGNED_INT_SAMPLER_3D, pattern UNSIGNED_INT_SAMPLER_CUBE, pattern UNSIGNED_INT_SAMPLER_2D_ARRAY, pattern DEPTH_COMPONENT32F, pattern DEPTH32F_STENCIL8, pattern FLOAT_32_UNSIGNED_INT_24_8_REV, pattern FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING, pattern FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE, pattern FRAMEBUFFER_ATTACHMENT_RED_SIZE, pattern FRAMEBUFFER_ATTACHMENT_GREEN_SIZE, pattern FRAMEBUFFER_ATTACHMENT_BLUE_SIZE, pattern FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE, pattern FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE, pattern FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE, pattern FRAMEBUFFER_DEFAULT, pattern DEPTH_STENCIL_ATTACHMENT, pattern DEPTH_STENCIL, pattern UNSIGNED_INT_24_8, pattern DEPTH24_STENCIL8, pattern UNSIGNED_NORMALIZED, pattern DRAW_FRAMEBUFFER_BINDING, pattern READ_FRAMEBUFFER, pattern DRAW_FRAMEBUFFER, pattern READ_FRAMEBUFFER_BINDING, pattern RENDERBUFFER_SAMPLES, pattern FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER, pattern MAX_COLOR_ATTACHMENTS, pattern COLOR_ATTACHMENT1, pattern COLOR_ATTACHMENT2, pattern COLOR_ATTACHMENT3, pattern COLOR_ATTACHMENT4, pattern COLOR_ATTACHMENT5, pattern COLOR_ATTACHMENT6, pattern COLOR_ATTACHMENT7, pattern COLOR_ATTACHMENT8, pattern COLOR_ATTACHMENT9, pattern COLOR_ATTACHMENT10, pattern COLOR_ATTACHMENT11, pattern COLOR_ATTACHMENT12, pattern COLOR_ATTACHMENT13, pattern COLOR_ATTACHMENT14, pattern COLOR_ATTACHMENT15, pattern FRAMEBUFFER_INCOMPLETE_MULTISAMPLE, pattern MAX_SAMPLES, pattern HALF_FLOAT, pattern RG, pattern RG_INTEGER, pattern R8, pattern RG8, pattern R16F, pattern R32F, pattern RG16F, pattern RG32F, pattern R8I, pattern R8UI, pattern R16I, pattern R16UI, pattern R32I, pattern R32UI, pattern RG8I, pattern RG8UI, pattern RG16I, pattern RG16UI, pattern RG32I, pattern RG32UI, pattern VERTEX_ARRAY_BINDING, pattern R8_SNORM, pattern RG8_SNORM, pattern RGB8_SNORM, pattern RGBA8_SNORM, pattern SIGNED_NORMALIZED, pattern PRIMITIVE_RESTART_FIXED_INDEX, pattern COPY_READ_BUFFER, pattern COPY_WRITE_BUFFER, pattern COPY_READ_BUFFER_BINDING, pattern COPY_WRITE_BUFFER_BINDING, pattern UNIFORM_BUFFER, pattern UNIFORM_BUFFER_BINDING, pattern UNIFORM_BUFFER_START, pattern UNIFORM_BUFFER_SIZE, pattern MAX_VERTEX_UNIFORM_BLOCKS, pattern MAX_FRAGMENT_UNIFORM_BLOCKS, pattern MAX_COMBINED_UNIFORM_BLOCKS, pattern MAX_UNIFORM_BUFFER_BINDINGS, pattern MAX_UNIFORM_BLOCK_SIZE, pattern MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS, pattern MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS, pattern UNIFORM_BUFFER_OFFSET_ALIGNMENT, pattern ACTIVE_UNIFORM_BLOCKS, pattern UNIFORM_TYPE, pattern UNIFORM_SIZE, pattern UNIFORM_BLOCK_INDEX, pattern UNIFORM_OFFSET, pattern UNIFORM_ARRAY_STRIDE, pattern UNIFORM_MATRIX_STRIDE, pattern UNIFORM_IS_ROW_MAJOR, pattern UNIFORM_BLOCK_BINDING, pattern UNIFORM_BLOCK_DATA_SIZE, pattern UNIFORM_BLOCK_ACTIVE_UNIFORMS, pattern UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES, pattern UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER, pattern UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER, pattern INVALID_INDEX, pattern MAX_VERTEX_OUTPUT_COMPONENTS, pattern MAX_FRAGMENT_INPUT_COMPONENTS, pattern MAX_SERVER_WAIT_TIMEOUT, pattern OBJECT_TYPE, pattern SYNC_CONDITION, pattern SYNC_STATUS, pattern SYNC_FLAGS, pattern SYNC_FENCE, pattern SYNC_GPU_COMMANDS_COMPLETE, pattern UNSIGNALED, pattern SIGNALED, pattern ALREADY_SIGNALED, pattern TIMEOUT_EXPIRED, pattern CONDITION_SATISFIED, pattern WAIT_FAILED, pattern SYNC_FLUSH_COMMANDS_BIT, pattern VERTEX_ATTRIB_ARRAY_DIVISOR, pattern ANY_SAMPLES_PASSED, pattern ANY_SAMPLES_PASSED_CONSERVATIVE, pattern SAMPLER_BINDING, pattern RGB10_A2UI, pattern TEXTURE_SWIZZLE_R, pattern TEXTURE_SWIZZLE_G, pattern TEXTURE_SWIZZLE_B, pattern TEXTURE_SWIZZLE_A, pattern GREEN, pattern BLUE, pattern INT_2_10_10_10_REV, pattern TRANSFORM_FEEDBACK, pattern TRANSFORM_FEEDBACK_PAUSED, pattern TRANSFORM_FEEDBACK_ACTIVE, pattern TRANSFORM_FEEDBACK_BINDING, pattern COMPRESSED_R11_EAC, pattern COMPRESSED_SIGNED_R11_EAC, pattern COMPRESSED_RG11_EAC, pattern COMPRESSED_SIGNED_RG11_EAC, pattern COMPRESSED_RGB8_ETC2, pattern COMPRESSED_SRGB8_ETC2, pattern COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2, pattern COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2, pattern COMPRESSED_RGBA8_ETC2_EAC, pattern COMPRESSED_SRGB8_ALPHA8_ETC2_EAC, pattern TEXTURE_IMMUTABLE_FORMAT, pattern MAX_ELEMENT_INDEX, pattern NUM_SAMPLE_COUNTS, pattern TEXTURE_IMMUTABLE_LEVELS, pattern VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE, pattern TIMEOUT_IGNORED, WebGL2RenderingContext(..), gTypeWebGL2RenderingContext) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums | < -US/docs/Web/API/WebGL2RenderingContext.bufferData Mozilla WebGL2RenderingContext.bufferData documentation > bufferDataPtr :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> GLsizeiptr -> GLenum -> m () bufferDataPtr self target size usage = liftDOM (void (self ^. jsf "bufferData" [toJSVal target, integralToDoubleToJSVal size, toJSVal usage])) | < -US/docs/Web/API/WebGL2RenderingContext.bufferData Mozilla WebGL2RenderingContext.bufferData documentation > bufferData :: (MonadDOM m, IsBufferDataSource srcData) => WebGL2RenderingContext -> GLenum -> Maybe srcData -> GLenum -> m () bufferData self target srcData usage = liftDOM (void (self ^. jsf "bufferData" [toJSVal target, toJSVal srcData, toJSVal usage])) | < -US/docs/Web/API/WebGL2RenderingContext.bufferSubData Mozilla WebGL2RenderingContext.bufferSubData documentation > bufferSubData :: (MonadDOM m, IsBufferDataSource srcData) => WebGL2RenderingContext -> GLenum -> GLintptr -> Maybe srcData -> m () bufferSubData self target dstByteOffset srcData = liftDOM (void (self ^. jsf "bufferSubData" [toJSVal target, integralToDoubleToJSVal dstByteOffset, toJSVal srcData])) | < -US/docs/Web/API/WebGL2RenderingContext.bufferData Mozilla WebGL2RenderingContext.bufferData documentation > bufferDataView :: (MonadDOM m, IsArrayBufferView data') => WebGL2RenderingContext -> GLenum -> data' -> GLenum -> GLuint -> Maybe GLuint -> m () bufferDataView self target data' usage srcOffset length = liftDOM (void (self ^. jsf "bufferData" [toJSVal target, toJSVal data', toJSVal usage, toJSVal srcOffset, toJSVal length])) | < -US/docs/Web/API/WebGL2RenderingContext.bufferSubData Mozilla WebGL2RenderingContext.bufferSubData documentation > bufferSubDataView :: (MonadDOM m, IsArrayBufferView srcData) => WebGL2RenderingContext -> GLenum -> GLintptr -> srcData -> GLuint -> Maybe GLuint -> m () bufferSubDataView self target dstByteOffset srcData srcOffset length = liftDOM (void (self ^. jsf "bufferSubData" [toJSVal target, integralToDoubleToJSVal dstByteOffset, toJSVal srcData, toJSVal srcOffset, toJSVal length])) | < -US/docs/Web/API/WebGL2RenderingContext.copyBufferSubData Mozilla WebGL2RenderingContext.copyBufferSubData documentation > copyBufferSubData :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> GLenum -> GLintptr -> GLintptr -> GLsizeiptr -> m () copyBufferSubData self readTarget writeTarget readOffset writeOffset size = liftDOM (void (self ^. jsf "copyBufferSubData" [toJSVal readTarget, toJSVal writeTarget, integralToDoubleToJSVal readOffset, integralToDoubleToJSVal writeOffset, integralToDoubleToJSVal size])) getBufferSubData :: (MonadDOM m, IsArrayBufferView dstData) => WebGL2RenderingContext -> GLenum -> GLintptr -> dstData -> Maybe GLuint -> Maybe GLuint -> m () getBufferSubData self target srcByteOffset dstData dstOffset length = liftDOM (void (self ^. jsf "getBufferSubData" [toJSVal target, integralToDoubleToJSVal srcByteOffset, toJSVal dstData, toJSVal dstOffset, toJSVal length])) | < -US/docs/Web/API/WebGL2RenderingContext.blitFramebuffer Mozilla WebGL2RenderingContext.blitFramebuffer documentation > blitFramebuffer :: (MonadDOM m) => WebGL2RenderingContext -> GLint -> GLint -> GLint -> GLint -> GLint -> GLint -> GLint -> GLint -> GLbitfield -> GLenum -> m () blitFramebuffer self srcX0 srcY0 srcX1 srcY1 dstX0 dstY0 dstX1 dstY1 mask filter = liftDOM (void (self ^. jsf "blitFramebuffer" [toJSVal srcX0, toJSVal srcY0, toJSVal srcX1, toJSVal srcY1, toJSVal dstX0, toJSVal dstY0, toJSVal dstX1, toJSVal dstY1, toJSVal mask, toJSVal filter])) | < -US/docs/Web/API/WebGL2RenderingContext.framebufferTextureLayer Mozilla WebGL2RenderingContext.framebufferTextureLayer documentation > framebufferTextureLayer :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> GLenum -> GLuint -> GLint -> GLint -> m () framebufferTextureLayer self target attachment texture level layer = liftDOM (void (self ^. jsf "framebufferTextureLayer" [toJSVal target, toJSVal attachment, toJSVal texture, toJSVal level, toJSVal layer])) | < -US/docs/Web/API/WebGL2RenderingContext.getInternalformatParameter Mozilla WebGL2RenderingContext.getInternalformatParameter documentation > getInternalformatParameter :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> GLenum -> GLenum -> m JSVal getInternalformatParameter self target internalformat pname = liftDOM ((self ^. jsf "getInternalformatParameter" [toJSVal target, toJSVal internalformat, toJSVal pname]) >>= toJSVal) | < -US/docs/Web/API/WebGL2RenderingContext.getInternalformatParameter Mozilla WebGL2RenderingContext.getInternalformatParameter documentation > getInternalformatParameter_ :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> GLenum -> GLenum -> m () getInternalformatParameter_ self target internalformat pname = liftDOM (void (self ^. jsf "getInternalformatParameter" [toJSVal target, toJSVal internalformat, toJSVal pname])) | < -US/docs/Web/API/WebGL2RenderingContext.invalidateFramebuffer Mozilla WebGL2RenderingContext.invalidateFramebuffer documentation > invalidateFramebuffer :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> [GLenum] -> m () invalidateFramebuffer self target attachments = liftDOM (void (self ^. jsf "invalidateFramebuffer" [toJSVal target, toJSVal (array attachments)])) | < -US/docs/Web/API/WebGL2RenderingContext.invalidateSubFramebuffer Mozilla WebGL2RenderingContext.invalidateSubFramebuffer documentation > invalidateSubFramebuffer :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> [GLenum] -> GLint -> GLint -> GLsizei -> GLsizei -> m () invalidateSubFramebuffer self target attachments x y width height = liftDOM (void (self ^. jsf "invalidateSubFramebuffer" [toJSVal target, toJSVal (array attachments), toJSVal x, toJSVal y, toJSVal width, toJSVal height])) | < -US/docs/Web/API/WebGL2RenderingContext.readBuffer Mozilla WebGL2RenderingContext.readBuffer documentation > readBuffer :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> m () readBuffer self src = liftDOM (void (self ^. jsf "readBuffer" [toJSVal src])) | < -US/docs/Web/API/WebGL2RenderingContext.renderbufferStorageMultisample Mozilla WebGL2RenderingContext.renderbufferStorageMultisample documentation > renderbufferStorageMultisample :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> GLsizei -> GLenum -> GLsizei -> GLsizei -> m () renderbufferStorageMultisample self target samples internalformat width height = liftDOM (void (self ^. jsf "renderbufferStorageMultisample" [toJSVal target, toJSVal samples, toJSVal internalformat, toJSVal width, toJSVal height])) texStorage2D :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> GLsizei -> GLenum -> GLsizei -> GLsizei -> m () texStorage2D self target levels internalformat width height = liftDOM (void (self ^. jsf "texStorage2D" [toJSVal target, toJSVal levels, toJSVal internalformat, toJSVal width, toJSVal height])) texStorage3D :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> GLsizei -> GLenum -> GLsizei -> GLsizei -> GLsizei -> m () texStorage3D self target levels internalformat width height depth = liftDOM (void (self ^. jsf "texStorage3D" [toJSVal target, toJSVal levels, toJSVal internalformat, toJSVal width, toJSVal height, toJSVal depth])) | < -US/docs/Web/API/WebGL2RenderingContext.texImage3D Mozilla WebGL2RenderingContext.texImage3D documentation > texImage3D :: (MonadDOM m, IsArrayBufferView pixels) => WebGL2RenderingContext -> GLenum -> GLint -> GLint -> GLsizei -> GLsizei -> GLsizei -> GLint -> GLenum -> GLenum -> Maybe pixels -> m () texImage3D self target level internalformat width height depth border format type' pixels = liftDOM (void (self ^. jsf "texImage3D" [toJSVal target, toJSVal level, toJSVal internalformat, toJSVal width, toJSVal height, toJSVal depth, toJSVal border, toJSVal format, toJSVal type', toJSVal pixels])) texSubImage3DView :: (MonadDOM m, IsArrayBufferView pixels) => WebGL2RenderingContext -> GLenum -> GLint -> GLint -> GLint -> GLint -> GLsizei -> GLsizei -> GLsizei -> GLenum -> GLenum -> Maybe pixels -> m () texSubImage3DView self target level xoffset yoffset zoffset width height depth format type' pixels = liftDOM (void (self ^. jsf "texSubImage3D" [toJSVal target, toJSVal level, toJSVal xoffset, toJSVal yoffset, toJSVal zoffset, toJSVal width, toJSVal height, toJSVal depth, toJSVal format, toJSVal type', toJSVal pixels])) texSubImage3D :: (MonadDOM m, IsTexImageSource source) => WebGL2RenderingContext -> GLenum -> GLint -> GLint -> GLint -> GLint -> GLenum -> GLenum -> source -> m () texSubImage3D self target level xoffset yoffset zoffset format type' source = liftDOM (void (self ^. jsf "texSubImage3D" [toJSVal target, toJSVal level, toJSVal xoffset, toJSVal yoffset, toJSVal zoffset, toJSVal format, toJSVal type', toJSVal source])) | < -US/docs/Web/API/WebGL2RenderingContext.copyTexSubImage3D Mozilla WebGL2RenderingContext.copyTexSubImage3D documentation > copyTexSubImage3D :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> GLint -> GLint -> GLint -> GLint -> GLint -> GLint -> GLsizei -> GLsizei -> m () copyTexSubImage3D self target level xoffset yoffset zoffset x y width height = liftDOM (void (self ^. jsf "copyTexSubImage3D" [toJSVal target, toJSVal level, toJSVal xoffset, toJSVal yoffset, toJSVal zoffset, toJSVal x, toJSVal y, toJSVal width, toJSVal height])) | < -US/docs/Web/API/WebGL2RenderingContext.compressedTexImage3D Mozilla WebGL2RenderingContext.compressedTexImage3D documentation > compressedTexImage3D :: (MonadDOM m, IsArrayBufferView data') => WebGL2RenderingContext -> GLenum -> GLint -> GLenum -> GLsizei -> GLsizei -> GLsizei -> GLint -> GLsizei -> Maybe data' -> m () compressedTexImage3D self target level internalformat width height depth border imageSize data' = liftDOM (void (self ^. jsf "compressedTexImage3D" [toJSVal target, toJSVal level, toJSVal internalformat, toJSVal width, toJSVal height, toJSVal depth, toJSVal border, toJSVal imageSize, toJSVal data'])) | < -US/docs/Web/API/WebGL2RenderingContext.compressedTexSubImage3D Mozilla WebGL2RenderingContext.compressedTexSubImage3D documentation > compressedTexSubImage3D :: (MonadDOM m, IsArrayBufferView data') => WebGL2RenderingContext -> GLenum -> GLint -> GLint -> GLint -> GLint -> GLsizei -> GLsizei -> GLsizei -> GLenum -> GLsizei -> Maybe data' -> m () compressedTexSubImage3D self target level xoffset yoffset zoffset width height depth format imageSize data' = liftDOM (void (self ^. jsf "compressedTexSubImage3D" [toJSVal target, toJSVal level, toJSVal xoffset, toJSVal yoffset, toJSVal zoffset, toJSVal width, toJSVal height, toJSVal depth, toJSVal format, toJSVal imageSize, toJSVal data'])) | < -US/docs/Web/API/WebGL2RenderingContext.getFragDataLocation Mozilla WebGL2RenderingContext.getFragDataLocation documentation > getFragDataLocation :: (MonadDOM m, ToJSString name) => WebGL2RenderingContext -> Maybe WebGLProgram -> name -> m GLint getFragDataLocation self program name = liftDOM ((self ^. jsf "getFragDataLocation" [toJSVal program, toJSVal name]) >>= fromJSValUnchecked) | < -US/docs/Web/API/WebGL2RenderingContext.getFragDataLocation Mozilla WebGL2RenderingContext.getFragDataLocation documentation > getFragDataLocation_ :: (MonadDOM m, ToJSString name) => WebGL2RenderingContext -> Maybe WebGLProgram -> name -> m () getFragDataLocation_ self program name = liftDOM (void (self ^. jsf "getFragDataLocation" [toJSVal program, toJSVal name])) | < -US/docs/Web/API/WebGL2RenderingContext.uniform1ui Mozilla WebGL2RenderingContext.uniform1ui documentation > uniform1ui :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLUniformLocation -> GLuint -> m () uniform1ui self location v0 = liftDOM (void (self ^. jsf "uniform1ui" [toJSVal location, toJSVal v0])) uniform2ui :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLUniformLocation -> GLuint -> GLuint -> m () uniform2ui self location v0 v1 = liftDOM (void (self ^. jsf "uniform2ui" [toJSVal location, toJSVal v0, toJSVal v1])) | < -US/docs/Web/API/WebGL2RenderingContext.uniform3ui Mozilla WebGL2RenderingContext.uniform3ui documentation > uniform3ui :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLUniformLocation -> GLuint -> GLuint -> GLuint -> m () uniform3ui self location v0 v1 v2 = liftDOM (void (self ^. jsf "uniform3ui" [toJSVal location, toJSVal v0, toJSVal v1, toJSVal v2])) uniform4ui :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLUniformLocation -> GLuint -> GLuint -> GLuint -> GLuint -> m () uniform4ui self location v0 v1 v2 v3 = liftDOM (void (self ^. jsf "uniform4ui" [toJSVal location, toJSVal v0, toJSVal v1, toJSVal v2, toJSVal v3])) | < -US/docs/Web/API/WebGL2RenderingContext.uniform1uiv Mozilla WebGL2RenderingContext.uniform1uiv documentation > uniform1uiv :: (MonadDOM m, IsUint32Array value) => WebGL2RenderingContext -> Maybe WebGLUniformLocation -> Maybe value -> m () uniform1uiv self location value = liftDOM (void (self ^. jsf "uniform1uiv" [toJSVal location, toJSVal value])) | < -US/docs/Web/API/WebGL2RenderingContext.uniform2uiv Mozilla WebGL2RenderingContext.uniform2uiv documentation > uniform2uiv :: (MonadDOM m, IsUint32Array value) => WebGL2RenderingContext -> Maybe WebGLUniformLocation -> Maybe value -> m () uniform2uiv self location value = liftDOM (void (self ^. jsf "uniform2uiv" [toJSVal location, toJSVal value])) | < -US/docs/Web/API/WebGL2RenderingContext.uniform3uiv Mozilla WebGL2RenderingContext.uniform3uiv documentation > uniform3uiv :: (MonadDOM m, IsUint32Array value) => WebGL2RenderingContext -> Maybe WebGLUniformLocation -> Maybe value -> m () uniform3uiv self location value = liftDOM (void (self ^. jsf "uniform3uiv" [toJSVal location, toJSVal value])) | < -US/docs/Web/API/WebGL2RenderingContext.uniform4uiv Mozilla WebGL2RenderingContext.uniform4uiv documentation > uniform4uiv :: (MonadDOM m, IsUint32Array value) => WebGL2RenderingContext -> Maybe WebGLUniformLocation -> Maybe value -> m () uniform4uiv self location value = liftDOM (void (self ^. jsf "uniform4uiv" [toJSVal location, toJSVal value])) uniformMatrix2x3fv :: (MonadDOM m, IsFloat32Array value) => WebGL2RenderingContext -> Maybe WebGLUniformLocation -> GLboolean -> Maybe value -> m () uniformMatrix2x3fv self location transpose value = liftDOM (void (self ^. jsf "uniformMatrix2x3fv" [toJSVal location, toJSVal transpose, toJSVal value])) uniformMatrix3x2fv :: (MonadDOM m, IsFloat32Array value) => WebGL2RenderingContext -> Maybe WebGLUniformLocation -> GLboolean -> Maybe value -> m () uniformMatrix3x2fv self location transpose value = liftDOM (void (self ^. jsf "uniformMatrix3x2fv" [toJSVal location, toJSVal transpose, toJSVal value])) | < WebGL2RenderingContext.uniformMatrix2x4fv documentation > uniformMatrix2x4fv :: (MonadDOM m, IsFloat32Array value) => WebGL2RenderingContext -> Maybe WebGLUniformLocation -> GLboolean -> Maybe value -> m () uniformMatrix2x4fv self location transpose value = liftDOM (void (self ^. jsf "uniformMatrix2x4fv" [toJSVal location, toJSVal transpose, toJSVal value])) uniformMatrix4x2fv :: (MonadDOM m, IsFloat32Array value) => WebGL2RenderingContext -> Maybe WebGLUniformLocation -> GLboolean -> Maybe value -> m () uniformMatrix4x2fv self location transpose value = liftDOM (void (self ^. jsf "uniformMatrix4x2fv" [toJSVal location, toJSVal transpose, toJSVal value])) | < -US/docs/Web/API/WebGL2RenderingContext.uniformMatrix3x4fv Mozilla WebGL2RenderingContext.uniformMatrix3x4fv documentation > uniformMatrix3x4fv :: (MonadDOM m, IsFloat32Array value) => WebGL2RenderingContext -> Maybe WebGLUniformLocation -> GLboolean -> Maybe value -> m () uniformMatrix3x4fv self location transpose value = liftDOM (void (self ^. jsf "uniformMatrix3x4fv" [toJSVal location, toJSVal transpose, toJSVal value])) | < -US/docs/Web/API/WebGL2RenderingContext.uniformMatrix4x3fv Mozilla WebGL2RenderingContext.uniformMatrix4x3fv documentation > uniformMatrix4x3fv :: (MonadDOM m, IsFloat32Array value) => WebGL2RenderingContext -> Maybe WebGLUniformLocation -> GLboolean -> Maybe value -> m () uniformMatrix4x3fv self location transpose value = liftDOM (void (self ^. jsf "uniformMatrix4x3fv" [toJSVal location, toJSVal transpose, toJSVal value])) | < -US/docs/Web/API/WebGL2RenderingContext.vertexAttribI4i Mozilla WebGL2RenderingContext.vertexAttribI4i documentation > vertexAttribI4i :: (MonadDOM m) => WebGL2RenderingContext -> GLuint -> GLint -> GLint -> GLint -> GLint -> m () vertexAttribI4i self index x y z w = liftDOM (void (self ^. jsf "vertexAttribI4i" [toJSVal index, toJSVal x, toJSVal y, toJSVal z, toJSVal w])) | < -US/docs/Web/API/WebGL2RenderingContext.vertexAttribI4iv Mozilla WebGL2RenderingContext.vertexAttribI4iv documentation > vertexAttribI4iv :: (MonadDOM m, IsInt32Array v) => WebGL2RenderingContext -> GLuint -> Maybe v -> m () vertexAttribI4iv self index v = liftDOM (void (self ^. jsf "vertexAttribI4iv" [toJSVal index, toJSVal v])) vertexAttribI4ui :: (MonadDOM m) => WebGL2RenderingContext -> GLuint -> GLuint -> GLuint -> GLuint -> GLuint -> m () vertexAttribI4ui self index x y z w = liftDOM (void (self ^. jsf "vertexAttribI4ui" [toJSVal index, toJSVal x, toJSVal y, toJSVal z, toJSVal w])) vertexAttribI4uiv :: (MonadDOM m, IsUint32Array v) => WebGL2RenderingContext -> GLuint -> Maybe v -> m () vertexAttribI4uiv self index v = liftDOM (void (self ^. jsf "vertexAttribI4uiv" [toJSVal index, toJSVal v])) vertexAttribIPointer :: (MonadDOM m) => WebGL2RenderingContext -> GLuint -> GLint -> GLenum -> GLsizei -> GLintptr -> m () vertexAttribIPointer self index size type' stride offset = liftDOM (void (self ^. jsf "vertexAttribIPointer" [toJSVal index, toJSVal size, toJSVal type', toJSVal stride, integralToDoubleToJSVal offset])) | < -US/docs/Web/API/WebGL2RenderingContext.vertexAttribDivisor Mozilla WebGL2RenderingContext.vertexAttribDivisor documentation > vertexAttribDivisor :: (MonadDOM m) => WebGL2RenderingContext -> GLuint -> GLuint -> m () vertexAttribDivisor self index divisor = liftDOM (void (self ^. jsf "vertexAttribDivisor" [toJSVal index, toJSVal divisor])) | < -US/docs/Web/API/WebGL2RenderingContext.drawArraysInstanced Mozilla WebGL2RenderingContext.drawArraysInstanced documentation > drawArraysInstanced :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> GLint -> GLsizei -> GLsizei -> m () drawArraysInstanced self mode first count instanceCount = liftDOM (void (self ^. jsf "drawArraysInstanced" [toJSVal mode, toJSVal first, toJSVal count, toJSVal instanceCount])) drawElementsInstanced :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> GLsizei -> GLenum -> GLintptr -> GLsizei -> m () drawElementsInstanced self mode count type' offset instanceCount = liftDOM (void (self ^. jsf "drawElementsInstanced" [toJSVal mode, toJSVal count, toJSVal type', integralToDoubleToJSVal offset, toJSVal instanceCount])) | < -US/docs/Web/API/WebGL2RenderingContext.drawRangeElements Mozilla WebGL2RenderingContext.drawRangeElements documentation > drawRangeElements :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> GLuint -> GLuint -> GLsizei -> GLenum -> GLintptr -> m () drawRangeElements self mode start end count type' offset = liftDOM (void (self ^. jsf "drawRangeElements" [toJSVal mode, toJSVal start, toJSVal end, toJSVal count, toJSVal type', integralToDoubleToJSVal offset])) | < -US/docs/Web/API/WebGL2RenderingContext.drawBuffers Mozilla WebGL2RenderingContext.drawBuffers documentation > drawBuffers :: (MonadDOM m) => WebGL2RenderingContext -> [GLenum] -> m () drawBuffers self buffers = liftDOM (void (self ^. jsf "drawBuffers" [toJSVal (array buffers)])) | < -US/docs/Web/API/WebGL2RenderingContext.clearBufferiv Mozilla WebGL2RenderingContext.clearBufferiv documentation > clearBufferiv :: (MonadDOM m, IsInt32Array value) => WebGL2RenderingContext -> GLenum -> GLint -> Maybe value -> m () clearBufferiv self buffer drawbuffer value = liftDOM (void (self ^. jsf "clearBufferiv" [toJSVal buffer, toJSVal drawbuffer, toJSVal value])) | < -US/docs/Web/API/WebGL2RenderingContext.clearBufferuiv Mozilla WebGL2RenderingContext.clearBufferuiv documentation > clearBufferuiv :: (MonadDOM m, IsUint32Array value) => WebGL2RenderingContext -> GLenum -> GLint -> Maybe value -> m () clearBufferuiv self buffer drawbuffer value = liftDOM (void (self ^. jsf "clearBufferuiv" [toJSVal buffer, toJSVal drawbuffer, toJSVal value])) | < -US/docs/Web/API/WebGL2RenderingContext.clearBufferfv Mozilla WebGL2RenderingContext.clearBufferfv documentation > clearBufferfv :: (MonadDOM m, IsFloat32Array value) => WebGL2RenderingContext -> GLenum -> GLint -> Maybe value -> m () clearBufferfv self buffer drawbuffer value = liftDOM (void (self ^. jsf "clearBufferfv" [toJSVal buffer, toJSVal drawbuffer, toJSVal value])) clearBufferfi :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> GLint -> GLfloat -> GLint -> m () clearBufferfi self buffer drawbuffer depth stencil = liftDOM (void (self ^. jsf "clearBufferfi" [toJSVal buffer, toJSVal drawbuffer, toJSVal depth, toJSVal stencil])) | < -US/docs/Web/API/WebGL2RenderingContext.createQuery Mozilla WebGL2RenderingContext.createQuery documentation > createQuery :: (MonadDOM m) => WebGL2RenderingContext -> m WebGLQuery createQuery self = liftDOM ((self ^. jsf "createQuery" ()) >>= fromJSValUnchecked) | < -US/docs/Web/API/WebGL2RenderingContext.createQuery Mozilla WebGL2RenderingContext.createQuery documentation > createQuery_ :: (MonadDOM m) => WebGL2RenderingContext -> m () createQuery_ self = liftDOM (void (self ^. jsf "createQuery" ())) | < -US/docs/Web/API/WebGL2RenderingContext.deleteQuery Mozilla WebGL2RenderingContext.deleteQuery documentation > deleteQuery :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLQuery -> m () deleteQuery self query = liftDOM (void (self ^. jsf "deleteQuery" [toJSVal query])) isQuery :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLQuery -> m GLboolean isQuery self query = liftDOM ((self ^. jsf "isQuery" [toJSVal query]) >>= fromJSValUnchecked) isQuery_ :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLQuery -> m () isQuery_ self query = liftDOM (void (self ^. jsf "isQuery" [toJSVal query])) beginQuery :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> Maybe WebGLQuery -> m () beginQuery self target query = liftDOM (void (self ^. jsf "beginQuery" [toJSVal target, toJSVal query])) | < documentation > endQuery :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> m () endQuery self target = liftDOM (void (self ^. jsf "endQuery" [toJSVal target])) getQuery :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> GLenum -> m WebGLQuery getQuery self target pname = liftDOM ((self ^. jsf "getQuery" [toJSVal target, toJSVal pname]) >>= fromJSValUnchecked) getQuery_ :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> GLenum -> m () getQuery_ self target pname = liftDOM (void (self ^. jsf "getQuery" [toJSVal target, toJSVal pname])) | < -US/docs/Web/API/WebGL2RenderingContext.getQueryParameter Mozilla WebGL2RenderingContext.getQueryParameter documentation > getQueryParameter :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLQuery -> GLenum -> m JSVal getQueryParameter self query pname = liftDOM ((self ^. jsf "getQueryParameter" [toJSVal query, toJSVal pname]) >>= toJSVal) | < -US/docs/Web/API/WebGL2RenderingContext.getQueryParameter Mozilla WebGL2RenderingContext.getQueryParameter documentation > getQueryParameter_ :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLQuery -> GLenum -> m () getQueryParameter_ self query pname = liftDOM (void (self ^. jsf "getQueryParameter" [toJSVal query, toJSVal pname])) | < -US/docs/Web/API/WebGL2RenderingContext.createSampler Mozilla WebGL2RenderingContext.createSampler documentation > createSampler :: (MonadDOM m) => WebGL2RenderingContext -> m WebGLSampler createSampler self = liftDOM ((self ^. jsf "createSampler" ()) >>= fromJSValUnchecked) | < -US/docs/Web/API/WebGL2RenderingContext.createSampler Mozilla WebGL2RenderingContext.createSampler documentation > createSampler_ :: (MonadDOM m) => WebGL2RenderingContext -> m () createSampler_ self = liftDOM (void (self ^. jsf "createSampler" ())) | < -US/docs/Web/API/WebGL2RenderingContext.deleteSampler Mozilla WebGL2RenderingContext.deleteSampler documentation > deleteSampler :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLSampler -> m () deleteSampler self sampler = liftDOM (void (self ^. jsf "deleteSampler" [toJSVal sampler])) | < -US/docs/Web/API/WebGL2RenderingContext.isSampler Mozilla WebGL2RenderingContext.isSampler documentation > isSampler :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLSampler -> m GLboolean isSampler self sampler = liftDOM ((self ^. jsf "isSampler" [toJSVal sampler]) >>= fromJSValUnchecked) | < -US/docs/Web/API/WebGL2RenderingContext.isSampler Mozilla WebGL2RenderingContext.isSampler documentation > isSampler_ :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLSampler -> m () isSampler_ self sampler = liftDOM (void (self ^. jsf "isSampler" [toJSVal sampler])) | < -US/docs/Web/API/WebGL2RenderingContext.bindSampler Mozilla WebGL2RenderingContext.bindSampler documentation > bindSampler :: (MonadDOM m) => WebGL2RenderingContext -> GLuint -> Maybe WebGLSampler -> m () bindSampler self unit sampler = liftDOM (void (self ^. jsf "bindSampler" [toJSVal unit, toJSVal sampler])) samplerParameteri :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLSampler -> GLenum -> GLint -> m () samplerParameteri self sampler pname param = liftDOM (void (self ^. jsf "samplerParameteri" [toJSVal sampler, toJSVal pname, toJSVal param])) | < -US/docs/Web/API/WebGL2RenderingContext.samplerParameterf Mozilla WebGL2RenderingContext.samplerParameterf documentation > samplerParameterf :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLSampler -> GLenum -> GLfloat -> m () samplerParameterf self sampler pname param = liftDOM (void (self ^. jsf "samplerParameterf" [toJSVal sampler, toJSVal pname, toJSVal param])) | < -US/docs/Web/API/WebGL2RenderingContext.getSamplerParameter Mozilla WebGL2RenderingContext.getSamplerParameter documentation > getSamplerParameter :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLSampler -> GLenum -> m JSVal getSamplerParameter self sampler pname = liftDOM ((self ^. jsf "getSamplerParameter" [toJSVal sampler, toJSVal pname]) >>= toJSVal) | < -US/docs/Web/API/WebGL2RenderingContext.getSamplerParameter Mozilla WebGL2RenderingContext.getSamplerParameter documentation > getSamplerParameter_ :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLSampler -> GLenum -> m () getSamplerParameter_ self sampler pname = liftDOM (void (self ^. jsf "getSamplerParameter" [toJSVal sampler, toJSVal pname])) | < -US/docs/Web/API/WebGL2RenderingContext.fenceSync Mozilla WebGL2RenderingContext.fenceSync documentation > fenceSync :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> GLbitfield -> m WebGLSync fenceSync self condition flags = liftDOM ((self ^. jsf "fenceSync" [toJSVal condition, toJSVal flags]) >>= fromJSValUnchecked) | < -US/docs/Web/API/WebGL2RenderingContext.fenceSync Mozilla WebGL2RenderingContext.fenceSync documentation > fenceSync_ :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> GLbitfield -> m () fenceSync_ self condition flags = liftDOM (void (self ^. jsf "fenceSync" [toJSVal condition, toJSVal flags])) | < -US/docs/Web/API/WebGL2RenderingContext.isSync Mozilla WebGL2RenderingContext.isSync documentation > isSync :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLSync -> m GLboolean isSync self sync = liftDOM ((self ^. jsf "isSync" [toJSVal sync]) >>= fromJSValUnchecked) | < -US/docs/Web/API/WebGL2RenderingContext.isSync Mozilla WebGL2RenderingContext.isSync documentation > isSync_ :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLSync -> m () isSync_ self sync = liftDOM (void (self ^. jsf "isSync" [toJSVal sync])) deleteSync :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLSync -> m () deleteSync self sync = liftDOM (void (self ^. jsf "deleteSync" [toJSVal sync])) clientWaitSync :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLSync -> GLbitfield -> GLuint64 -> m GLenum clientWaitSync self sync flags timeout = liftDOM ((self ^. jsf "clientWaitSync" [toJSVal sync, toJSVal flags, integralToDoubleToJSVal timeout]) >>= fromJSValUnchecked) clientWaitSync_ :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLSync -> GLbitfield -> GLuint64 -> m () clientWaitSync_ self sync flags timeout = liftDOM (void (self ^. jsf "clientWaitSync" [toJSVal sync, toJSVal flags, integralToDoubleToJSVal timeout])) | < -US/docs/Web/API/WebGL2RenderingContext.waitSync Mozilla WebGL2RenderingContext.waitSync documentation > waitSync :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLSync -> GLbitfield -> GLuint64 -> m () waitSync self sync flags timeout = liftDOM (void (self ^. jsf "waitSync" [toJSVal sync, toJSVal flags, integralToDoubleToJSVal timeout])) | < -US/docs/Web/API/WebGL2RenderingContext.getSyncParameter Mozilla WebGL2RenderingContext.getSyncParameter documentation > getSyncParameter :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLSync -> GLenum -> m JSVal getSyncParameter self sync pname = liftDOM ((self ^. jsf "getSyncParameter" [toJSVal sync, toJSVal pname]) >>= toJSVal) | < -US/docs/Web/API/WebGL2RenderingContext.getSyncParameter Mozilla WebGL2RenderingContext.getSyncParameter documentation > getSyncParameter_ :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLSync -> GLenum -> m () getSyncParameter_ self sync pname = liftDOM (void (self ^. jsf "getSyncParameter" [toJSVal sync, toJSVal pname])) createTransformFeedback :: (MonadDOM m) => WebGL2RenderingContext -> m WebGLTransformFeedback createTransformFeedback self = liftDOM ((self ^. jsf "createTransformFeedback" ()) >>= fromJSValUnchecked) createTransformFeedback_ :: (MonadDOM m) => WebGL2RenderingContext -> m () createTransformFeedback_ self = liftDOM (void (self ^. jsf "createTransformFeedback" ())) deleteTransformFeedback :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLTransformFeedback -> m () deleteTransformFeedback self id = liftDOM (void (self ^. jsf "deleteTransformFeedback" [toJSVal id])) | < -US/docs/Web/API/WebGL2RenderingContext.isTransformFeedback Mozilla WebGL2RenderingContext.isTransformFeedback documentation > isTransformFeedback :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLTransformFeedback -> m GLboolean isTransformFeedback self id = liftDOM ((self ^. jsf "isTransformFeedback" [toJSVal id]) >>= fromJSValUnchecked) | < -US/docs/Web/API/WebGL2RenderingContext.isTransformFeedback Mozilla WebGL2RenderingContext.isTransformFeedback documentation > isTransformFeedback_ :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLTransformFeedback -> m () isTransformFeedback_ self id = liftDOM (void (self ^. jsf "isTransformFeedback" [toJSVal id])) bindTransformFeedback :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> Maybe WebGLTransformFeedback -> m () bindTransformFeedback self target id = liftDOM (void (self ^. jsf "bindTransformFeedback" [toJSVal target, toJSVal id])) beginTransformFeedback :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> m () beginTransformFeedback self primitiveMode = liftDOM (void (self ^. jsf "beginTransformFeedback" [toJSVal primitiveMode])) | < -US/docs/Web/API/WebGL2RenderingContext.endTransformFeedback Mozilla WebGL2RenderingContext.endTransformFeedback documentation > endTransformFeedback :: (MonadDOM m) => WebGL2RenderingContext -> m () endTransformFeedback self = liftDOM (void (self ^. jsf "endTransformFeedback" ())) | < -US/docs/Web/API/WebGL2RenderingContext.transformFeedbackVaryings Mozilla WebGL2RenderingContext.transformFeedbackVaryings documentation > transformFeedbackVaryings :: (MonadDOM m, ToJSString varyings) => WebGL2RenderingContext -> Maybe WebGLProgram -> [varyings] -> GLenum -> m () transformFeedbackVaryings self program varyings bufferMode = liftDOM (void (self ^. jsf "transformFeedbackVaryings" [toJSVal program, toJSVal (array varyings), toJSVal bufferMode])) | < -US/docs/Web/API/WebGL2RenderingContext.getTransformFeedbackVarying Mozilla WebGL2RenderingContext.getTransformFeedbackVarying documentation > getTransformFeedbackVarying :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLProgram -> GLuint -> m WebGLActiveInfo getTransformFeedbackVarying self program index = liftDOM ((self ^. jsf "getTransformFeedbackVarying" [toJSVal program, toJSVal index]) >>= fromJSValUnchecked) | < -US/docs/Web/API/WebGL2RenderingContext.getTransformFeedbackVarying Mozilla WebGL2RenderingContext.getTransformFeedbackVarying documentation > getTransformFeedbackVarying_ :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLProgram -> GLuint -> m () getTransformFeedbackVarying_ self program index = liftDOM (void (self ^. jsf "getTransformFeedbackVarying" [toJSVal program, toJSVal index])) | < -US/docs/Web/API/WebGL2RenderingContext.pauseTransformFeedback Mozilla WebGL2RenderingContext.pauseTransformFeedback documentation > pauseTransformFeedback :: (MonadDOM m) => WebGL2RenderingContext -> m () pauseTransformFeedback self = liftDOM (void (self ^. jsf "pauseTransformFeedback" ())) resumeTransformFeedback :: (MonadDOM m) => WebGL2RenderingContext -> m () resumeTransformFeedback self = liftDOM (void (self ^. jsf "resumeTransformFeedback" ())) | < -US/docs/Web/API/WebGL2RenderingContext.bindBufferBase Mozilla WebGL2RenderingContext.bindBufferBase documentation > bindBufferBase :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> GLuint -> Maybe WebGLBuffer -> m () bindBufferBase self target index buffer = liftDOM (void (self ^. jsf "bindBufferBase" [toJSVal target, toJSVal index, toJSVal buffer])) | < -US/docs/Web/API/WebGL2RenderingContext.bindBufferRange Mozilla WebGL2RenderingContext.bindBufferRange documentation > bindBufferRange :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> GLuint -> Maybe WebGLBuffer -> GLintptr -> GLsizeiptr -> m () bindBufferRange self target index buffer offset size = liftDOM (void (self ^. jsf "bindBufferRange" [toJSVal target, toJSVal index, toJSVal buffer, integralToDoubleToJSVal offset, integralToDoubleToJSVal size])) | < WebGL2RenderingContext.getIndexedParameter documentation > getIndexedParameter :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> GLuint -> m JSVal getIndexedParameter self target index = liftDOM ((self ^. jsf "getIndexedParameter" [toJSVal target, toJSVal index]) >>= toJSVal) | < WebGL2RenderingContext.getIndexedParameter documentation > getIndexedParameter_ :: (MonadDOM m) => WebGL2RenderingContext -> GLenum -> GLuint -> m () getIndexedParameter_ self target index = liftDOM (void (self ^. jsf "getIndexedParameter" [toJSVal target, toJSVal index])) | < -US/docs/Web/API/WebGL2RenderingContext.getUniformIndices Mozilla WebGL2RenderingContext.getUniformIndices documentation > getUniformIndices :: (MonadDOM m, ToJSString uniformNames) => WebGL2RenderingContext -> Maybe WebGLProgram -> [uniformNames] -> m Uint32Array getUniformIndices self program uniformNames = liftDOM ((self ^. jsf "getUniformIndices" [toJSVal program, toJSVal (array uniformNames)]) >>= fromJSValUnchecked) | < -US/docs/Web/API/WebGL2RenderingContext.getUniformIndices Mozilla WebGL2RenderingContext.getUniformIndices documentation > getUniformIndices_ :: (MonadDOM m, ToJSString uniformNames) => WebGL2RenderingContext -> Maybe WebGLProgram -> [uniformNames] -> m () getUniformIndices_ self program uniformNames = liftDOM (void (self ^. jsf "getUniformIndices" [toJSVal program, toJSVal (array uniformNames)])) getActiveUniforms :: (MonadDOM m, IsUint32Array uniformIndices) => WebGL2RenderingContext -> Maybe WebGLProgram -> Maybe uniformIndices -> GLenum -> m Int32Array getActiveUniforms self program uniformIndices pname = liftDOM ((self ^. jsf "getActiveUniforms" [toJSVal program, toJSVal uniformIndices, toJSVal pname]) >>= fromJSValUnchecked) getActiveUniforms_ :: (MonadDOM m, IsUint32Array uniformIndices) => WebGL2RenderingContext -> Maybe WebGLProgram -> Maybe uniformIndices -> GLenum -> m () getActiveUniforms_ self program uniformIndices pname = liftDOM (void (self ^. jsf "getActiveUniforms" [toJSVal program, toJSVal uniformIndices, toJSVal pname])) | < -US/docs/Web/API/WebGL2RenderingContext.getUniformBlockIndex Mozilla WebGL2RenderingContext.getUniformBlockIndex documentation > getUniformBlockIndex :: (MonadDOM m, ToJSString uniformBlockName) => WebGL2RenderingContext -> Maybe WebGLProgram -> uniformBlockName -> m GLuint getUniformBlockIndex self program uniformBlockName = liftDOM ((self ^. jsf "getUniformBlockIndex" [toJSVal program, toJSVal uniformBlockName]) >>= fromJSValUnchecked) | < -US/docs/Web/API/WebGL2RenderingContext.getUniformBlockIndex Mozilla WebGL2RenderingContext.getUniformBlockIndex documentation > getUniformBlockIndex_ :: (MonadDOM m, ToJSString uniformBlockName) => WebGL2RenderingContext -> Maybe WebGLProgram -> uniformBlockName -> m () getUniformBlockIndex_ self program uniformBlockName = liftDOM (void (self ^. jsf "getUniformBlockIndex" [toJSVal program, toJSVal uniformBlockName])) | < -US/docs/Web/API/WebGL2RenderingContext.getActiveUniformBlockParameter Mozilla WebGL2RenderingContext.getActiveUniformBlockParameter documentation > getActiveUniformBlockParameter :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLProgram -> GLuint -> GLenum -> m JSVal getActiveUniformBlockParameter self program uniformBlockIndex pname = liftDOM ((self ^. jsf "getActiveUniformBlockParameter" [toJSVal program, toJSVal uniformBlockIndex, toJSVal pname]) >>= toJSVal) | < -US/docs/Web/API/WebGL2RenderingContext.getActiveUniformBlockParameter Mozilla WebGL2RenderingContext.getActiveUniformBlockParameter documentation > getActiveUniformBlockParameter_ :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLProgram -> GLuint -> GLenum -> m () getActiveUniformBlockParameter_ self program uniformBlockIndex pname = liftDOM (void (self ^. jsf "getActiveUniformBlockParameter" [toJSVal program, toJSVal uniformBlockIndex, toJSVal pname])) | < -US/docs/Web/API/WebGL2RenderingContext.getActiveUniformBlockName Mozilla WebGL2RenderingContext.getActiveUniformBlockName documentation > getActiveUniformBlockName :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLProgram -> GLuint -> m JSVal getActiveUniformBlockName self program uniformBlockIndex = liftDOM ((self ^. jsf "getActiveUniformBlockName" [toJSVal program, toJSVal uniformBlockIndex]) >>= toJSVal) | < -US/docs/Web/API/WebGL2RenderingContext.getActiveUniformBlockName Mozilla WebGL2RenderingContext.getActiveUniformBlockName documentation > getActiveUniformBlockName_ :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLProgram -> GLuint -> m () getActiveUniformBlockName_ self program uniformBlockIndex = liftDOM (void (self ^. jsf "getActiveUniformBlockName" [toJSVal program, toJSVal uniformBlockIndex])) | < -US/docs/Web/API/WebGL2RenderingContext.uniformBlockBinding Mozilla WebGL2RenderingContext.uniformBlockBinding documentation > uniformBlockBinding :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLProgram -> GLuint -> GLuint -> m () uniformBlockBinding self program uniformBlockIndex uniformBlockBinding = liftDOM (void (self ^. jsf "uniformBlockBinding" [toJSVal program, toJSVal uniformBlockIndex, toJSVal uniformBlockBinding])) | < -US/docs/Web/API/WebGL2RenderingContext.createVertexArray Mozilla WebGL2RenderingContext.createVertexArray documentation > createVertexArray :: (MonadDOM m) => WebGL2RenderingContext -> m WebGLVertexArrayObject createVertexArray self = liftDOM ((self ^. jsf "createVertexArray" ()) >>= fromJSValUnchecked) | < -US/docs/Web/API/WebGL2RenderingContext.createVertexArray Mozilla WebGL2RenderingContext.createVertexArray documentation > createVertexArray_ :: (MonadDOM m) => WebGL2RenderingContext -> m () createVertexArray_ self = liftDOM (void (self ^. jsf "createVertexArray" ())) | < -US/docs/Web/API/WebGL2RenderingContext.deleteVertexArray Mozilla WebGL2RenderingContext.deleteVertexArray documentation > deleteVertexArray :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLVertexArrayObject -> m () deleteVertexArray self vertexArray = liftDOM (void (self ^. jsf "deleteVertexArray" [toJSVal vertexArray])) | < -US/docs/Web/API/WebGL2RenderingContext.isVertexArray Mozilla WebGL2RenderingContext.isVertexArray documentation > isVertexArray :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLVertexArrayObject -> m GLboolean isVertexArray self vertexArray = liftDOM ((self ^. jsf "isVertexArray" [toJSVal vertexArray]) >>= fromJSValUnchecked) | < -US/docs/Web/API/WebGL2RenderingContext.isVertexArray Mozilla WebGL2RenderingContext.isVertexArray documentation > isVertexArray_ :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLVertexArrayObject -> m () isVertexArray_ self vertexArray = liftDOM (void (self ^. jsf "isVertexArray" [toJSVal vertexArray])) bindVertexArray :: (MonadDOM m) => WebGL2RenderingContext -> Maybe WebGLVertexArrayObject -> m () bindVertexArray self vertexArray = liftDOM (void (self ^. jsf "bindVertexArray" [toJSVal vertexArray])) pattern READ_BUFFER = 3074 pattern UNPACK_ROW_LENGTH = 3314 pattern UNPACK_SKIP_ROWS = 3315 pattern UNPACK_SKIP_PIXELS = 3316 pattern PACK_ROW_LENGTH = 3330 pattern PACK_SKIP_ROWS = 3331 pattern PACK_SKIP_PIXELS = 3332 pattern COLOR = 6144 pattern DEPTH = 6145 pattern STENCIL = 6146 pattern RED = 6403 pattern RGB8 = 32849 pattern RGBA8 = 32856 pattern RGB10_A2 = 32857 pattern TEXTURE_BINDING_3D = 32874 pattern UNPACK_SKIP_IMAGES = 32877 pattern UNPACK_IMAGE_HEIGHT = 32878 pattern TEXTURE_3D = 32879 pattern TEXTURE_WRAP_R = 32882 pattern MAX_3D_TEXTURE_SIZE = 32883 pattern UNSIGNED_INT_2_10_10_10_REV = 33640 pattern MAX_ELEMENTS_VERTICES = 33000 pattern MAX_ELEMENTS_INDICES = 33001 pattern TEXTURE_MIN_LOD = 33082 pattern TEXTURE_MAX_LOD = 33083 pattern TEXTURE_BASE_LEVEL = 33084 pattern TEXTURE_MAX_LEVEL = 33085 pattern MIN = 32775 pattern MAX = 32776 pattern DEPTH_COMPONENT24 = 33190 pattern MAX_TEXTURE_LOD_BIAS = 34045 pattern TEXTURE_COMPARE_MODE = 34892 pattern TEXTURE_COMPARE_FUNC = 34893 pattern CURRENT_QUERY = 34917 pattern QUERY_RESULT = 34918 pattern QUERY_RESULT_AVAILABLE = 34919 pattern STREAM_READ = 35041 pattern STREAM_COPY = 35042 pattern STATIC_READ = 35045 pattern STATIC_COPY = 35046 pattern DYNAMIC_READ = 35049 pattern DYNAMIC_COPY = 35050 pattern MAX_DRAW_BUFFERS = 34852 pattern DRAW_BUFFER0 = 34853 pattern DRAW_BUFFER1 = 34854 pattern DRAW_BUFFER2 = 34855 pattern DRAW_BUFFER3 = 34856 pattern DRAW_BUFFER4 = 34857 pattern DRAW_BUFFER5 = 34858 pattern DRAW_BUFFER6 = 34859 pattern DRAW_BUFFER7 = 34860 pattern DRAW_BUFFER8 = 34861 pattern DRAW_BUFFER9 = 34862 pattern DRAW_BUFFER10 = 34863 pattern DRAW_BUFFER11 = 34864 pattern DRAW_BUFFER12 = 34865 pattern DRAW_BUFFER13 = 34866 pattern DRAW_BUFFER14 = 34867 pattern DRAW_BUFFER15 = 34868 pattern MAX_FRAGMENT_UNIFORM_COMPONENTS = 35657 pattern MAX_VERTEX_UNIFORM_COMPONENTS = 35658 pattern SAMPLER_3D = 35679 pattern SAMPLER_2D_SHADOW = 35682 pattern FRAGMENT_SHADER_DERIVATIVE_HINT = 35723 pattern PIXEL_PACK_BUFFER = 35051 pattern PIXEL_UNPACK_BUFFER = 35052 pattern PIXEL_PACK_BUFFER_BINDING = 35053 pattern PIXEL_UNPACK_BUFFER_BINDING = 35055 pattern FLOAT_MAT2x3 = 35685 pattern FLOAT_MAT2x4 = 35686 pattern FLOAT_MAT3x2 = 35687 pattern FLOAT_MAT3x4 = 35688 pattern FLOAT_MAT4x2 = 35689 pattern FLOAT_MAT4x3 = 35690 pattern SRGB = 35904 pattern SRGB8 = 35905 pattern SRGB8_ALPHA8 = 35907 pattern COMPARE_REF_TO_TEXTURE = 34894 pattern RGBA32F = 34836 pattern RGB32F = 34837 pattern RGBA16F = 34842 pattern RGB16F = 34843 pattern VERTEX_ATTRIB_ARRAY_INTEGER = 35069 pattern MAX_ARRAY_TEXTURE_LAYERS = 35071 pattern MIN_PROGRAM_TEXEL_OFFSET = 35076 pattern MAX_PROGRAM_TEXEL_OFFSET = 35077 pattern MAX_VARYING_COMPONENTS = 35659 pattern TEXTURE_2D_ARRAY = 35866 pattern TEXTURE_BINDING_2D_ARRAY = 35869 pattern R11F_G11F_B10F = 35898 pattern UNSIGNED_INT_10F_11F_11F_REV = 35899 pattern RGB9_E5 = 35901 pattern UNSIGNED_INT_5_9_9_9_REV = 35902 pattern TRANSFORM_FEEDBACK_BUFFER_MODE = 35967 pattern MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS = 35968 pattern TRANSFORM_FEEDBACK_VARYINGS = 35971 pattern TRANSFORM_FEEDBACK_BUFFER_START = 35972 pattern TRANSFORM_FEEDBACK_BUFFER_SIZE = 35973 pattern TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN = 35976 pattern RASTERIZER_DISCARD = 35977 pattern MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS = 35978 pattern MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS = 35979 pattern INTERLEAVED_ATTRIBS = 35980 pattern SEPARATE_ATTRIBS = 35981 pattern TRANSFORM_FEEDBACK_BUFFER = 35982 pattern TRANSFORM_FEEDBACK_BUFFER_BINDING = 35983 pattern RGBA32UI = 36208 pattern RGB32UI = 36209 pattern RGBA16UI = 36214 pattern RGB16UI = 36215 pattern RGBA8UI = 36220 pattern RGB8UI = 36221 pattern RGBA32I = 36226 pattern RGB32I = 36227 pattern RGBA16I = 36232 pattern RGB16I = 36233 pattern RGBA8I = 36238 pattern RGB8I = 36239 pattern RED_INTEGER = 36244 pattern RGB_INTEGER = 36248 pattern RGBA_INTEGER = 36249 pattern SAMPLER_2D_ARRAY = 36289 pattern SAMPLER_2D_ARRAY_SHADOW = 36292 pattern SAMPLER_CUBE_SHADOW = 36293 pattern UNSIGNED_INT_VEC2 = 36294 pattern UNSIGNED_INT_VEC3 = 36295 pattern UNSIGNED_INT_VEC4 = 36296 pattern INT_SAMPLER_2D = 36298 pattern INT_SAMPLER_3D = 36299 pattern INT_SAMPLER_CUBE = 36300 pattern INT_SAMPLER_2D_ARRAY = 36303 pattern UNSIGNED_INT_SAMPLER_2D = 36306 pattern UNSIGNED_INT_SAMPLER_3D = 36307 pattern UNSIGNED_INT_SAMPLER_CUBE = 36308 pattern UNSIGNED_INT_SAMPLER_2D_ARRAY = 36311 pattern DEPTH_COMPONENT32F = 36012 pattern DEPTH32F_STENCIL8 = 36013 pattern FLOAT_32_UNSIGNED_INT_24_8_REV = 36269 pattern FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING = 33296 pattern FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE = 33297 pattern FRAMEBUFFER_ATTACHMENT_RED_SIZE = 33298 pattern FRAMEBUFFER_ATTACHMENT_GREEN_SIZE = 33299 pattern FRAMEBUFFER_ATTACHMENT_BLUE_SIZE = 33300 pattern FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE = 33301 pattern FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE = 33302 pattern FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE = 33303 pattern FRAMEBUFFER_DEFAULT = 33304 pattern DEPTH_STENCIL_ATTACHMENT = 33306 pattern DEPTH_STENCIL = 34041 pattern UNSIGNED_INT_24_8 = 34042 pattern DEPTH24_STENCIL8 = 35056 pattern UNSIGNED_NORMALIZED = 35863 pattern DRAW_FRAMEBUFFER_BINDING = 36006 pattern READ_FRAMEBUFFER = 36008 pattern DRAW_FRAMEBUFFER = 36009 pattern READ_FRAMEBUFFER_BINDING = 36010 pattern RENDERBUFFER_SAMPLES = 36011 pattern FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER = 36052 pattern MAX_COLOR_ATTACHMENTS = 36063 pattern COLOR_ATTACHMENT1 = 36065 pattern COLOR_ATTACHMENT2 = 36066 pattern COLOR_ATTACHMENT3 = 36067 pattern COLOR_ATTACHMENT4 = 36068 pattern COLOR_ATTACHMENT5 = 36069 pattern COLOR_ATTACHMENT6 = 36070 pattern COLOR_ATTACHMENT7 = 36071 pattern COLOR_ATTACHMENT8 = 36072 pattern COLOR_ATTACHMENT9 = 36073 pattern COLOR_ATTACHMENT10 = 36074 pattern COLOR_ATTACHMENT11 = 36075 pattern COLOR_ATTACHMENT12 = 36076 pattern COLOR_ATTACHMENT13 = 36077 pattern COLOR_ATTACHMENT14 = 36078 pattern COLOR_ATTACHMENT15 = 36079 pattern FRAMEBUFFER_INCOMPLETE_MULTISAMPLE = 36182 pattern MAX_SAMPLES = 36183 pattern HALF_FLOAT = 5131 pattern RG = 33319 pattern RG_INTEGER = 33320 pattern R8 = 33321 pattern RG8 = 33323 pattern R16F = 33325 pattern R32F = 33326 pattern RG16F = 33327 pattern RG32F = 33328 pattern R8I = 33329 pattern R8UI = 33330 pattern R16I = 33331 pattern R16UI = 33332 pattern R32I = 33333 pattern R32UI = 33334 pattern RG8I = 33335 pattern RG8UI = 33336 pattern RG16I = 33337 pattern RG16UI = 33338 pattern RG32I = 33339 pattern RG32UI = 33340 pattern VERTEX_ARRAY_BINDING = 34229 pattern R8_SNORM = 36756 pattern RG8_SNORM = 36757 pattern RGB8_SNORM = 36758 pattern RGBA8_SNORM = 36759 pattern SIGNED_NORMALIZED = 36764 pattern PRIMITIVE_RESTART_FIXED_INDEX = 36201 pattern COPY_READ_BUFFER = 36662 pattern COPY_WRITE_BUFFER = 36663 pattern COPY_READ_BUFFER_BINDING = 36662 pattern COPY_WRITE_BUFFER_BINDING = 36663 pattern UNIFORM_BUFFER = 35345 pattern UNIFORM_BUFFER_BINDING = 35368 pattern UNIFORM_BUFFER_START = 35369 pattern UNIFORM_BUFFER_SIZE = 35370 pattern MAX_VERTEX_UNIFORM_BLOCKS = 35371 pattern MAX_FRAGMENT_UNIFORM_BLOCKS = 35373 pattern MAX_COMBINED_UNIFORM_BLOCKS = 35374 pattern MAX_UNIFORM_BUFFER_BINDINGS = 35375 pattern MAX_UNIFORM_BLOCK_SIZE = 35376 pattern MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS = 35377 pattern MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS = 35379 pattern UNIFORM_BUFFER_OFFSET_ALIGNMENT = 35380 pattern ACTIVE_UNIFORM_BLOCKS = 35382 pattern UNIFORM_TYPE = 35383 pattern UNIFORM_SIZE = 35384 pattern UNIFORM_BLOCK_INDEX = 35386 pattern UNIFORM_OFFSET = 35387 pattern UNIFORM_ARRAY_STRIDE = 35388 pattern UNIFORM_MATRIX_STRIDE = 35389 pattern UNIFORM_IS_ROW_MAJOR = 35390 pattern UNIFORM_BLOCK_BINDING = 35391 pattern UNIFORM_BLOCK_DATA_SIZE = 35392 pattern UNIFORM_BLOCK_ACTIVE_UNIFORMS = 35394 pattern UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES = 35395 pattern UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER = 35396 pattern UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER = 35398 pattern INVALID_INDEX = 4294967295 pattern MAX_VERTEX_OUTPUT_COMPONENTS = 37154 pattern MAX_FRAGMENT_INPUT_COMPONENTS = 37157 pattern MAX_SERVER_WAIT_TIMEOUT = 37137 pattern OBJECT_TYPE = 37138 pattern SYNC_CONDITION = 37139 pattern SYNC_STATUS = 37140 pattern SYNC_FLAGS = 37141 pattern SYNC_FENCE = 37142 pattern SYNC_GPU_COMMANDS_COMPLETE = 37143 pattern UNSIGNALED = 37144 pattern SIGNALED = 37145 pattern ALREADY_SIGNALED = 37146 pattern TIMEOUT_EXPIRED = 37147 pattern CONDITION_SATISFIED = 37148 pattern WAIT_FAILED = 37149 pattern SYNC_FLUSH_COMMANDS_BIT = 1 pattern VERTEX_ATTRIB_ARRAY_DIVISOR = 35070 pattern ANY_SAMPLES_PASSED = 35887 pattern ANY_SAMPLES_PASSED_CONSERVATIVE = 36202 pattern SAMPLER_BINDING = 35097 pattern RGB10_A2UI = 36975 pattern TEXTURE_SWIZZLE_R = 36418 pattern TEXTURE_SWIZZLE_G = 36419 pattern TEXTURE_SWIZZLE_B = 36420 pattern TEXTURE_SWIZZLE_A = 36421 pattern GREEN = 6404 pattern BLUE = 6405 pattern INT_2_10_10_10_REV = 36255 pattern TRANSFORM_FEEDBACK = 36386 pattern TRANSFORM_FEEDBACK_PAUSED = 36387 pattern TRANSFORM_FEEDBACK_ACTIVE = 36388 pattern TRANSFORM_FEEDBACK_BINDING = 36389 pattern COMPRESSED_R11_EAC = 37488 pattern COMPRESSED_SIGNED_R11_EAC = 37489 pattern COMPRESSED_RG11_EAC = 37490 pattern COMPRESSED_SIGNED_RG11_EAC = 37491 pattern COMPRESSED_RGB8_ETC2 = 37492 pattern COMPRESSED_SRGB8_ETC2 = 37493 pattern COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 37494 pattern COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 37495 pattern COMPRESSED_RGBA8_ETC2_EAC = 37496 pattern COMPRESSED_SRGB8_ALPHA8_ETC2_EAC = 37497 pattern TEXTURE_IMMUTABLE_FORMAT = 37167 pattern MAX_ELEMENT_INDEX = 36203 pattern NUM_SAMPLE_COUNTS = 37760 pattern TEXTURE_IMMUTABLE_LEVELS = 33503 pattern VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE = 35070 pattern TIMEOUT_IGNORED = 18446744073709551615
c67f777e67b652d46ba3f0d95d52e9494039e8c0d95cf137adfa749106c5aadd
xh4/web-toolkit
macros.lisp
(in-package :alexandria) (defmacro with-gensyms (names &body forms) "Binds a set of variables to gensyms and evaluates the implicit progn FORMS. Each element within NAMES is either a symbol SYMBOL or a pair (SYMBOL STRING-DESIGNATOR). Bare symbols are equivalent to the pair (SYMBOL SYMBOL). Each pair (SYMBOL STRING-DESIGNATOR) specifies that the variable named by SYMBOL should be bound to a symbol constructed using GENSYM with the string designated by STRING-DESIGNATOR being its first argument." `(let ,(mapcar (lambda (name) (multiple-value-bind (symbol string) (etypecase name (symbol (values name (symbol-name name))) ((cons symbol (cons string-designator null)) (values (first name) (string (second name))))) `(,symbol (gensym ,string)))) names) ,@forms)) (defmacro with-unique-names (names &body forms) "Alias for WITH-GENSYMS." `(with-gensyms ,names ,@forms)) (defmacro once-only (specs &body forms) "Constructs code whose primary goal is to help automate the handling of multiple evaluation within macros. Multiple evaluation is handled by introducing intermediate variables, in order to reuse the result of an expression. The returned value is a list of the form (let ((<gensym-1> <expr-1>) ... (<gensym-n> <expr-n>)) <res>) where GENSYM-1, ..., GENSYM-N are the intermediate variables introduced in order to evaluate EXPR-1, ..., EXPR-N once, only. RES is code that is the result of evaluating the implicit progn FORMS within a special context determined by SPECS. RES should make use of (reference) the intermediate variables. Each element within SPECS is either a symbol SYMBOL or a pair (SYMBOL INITFORM). Bare symbols are equivalent to the pair (SYMBOL SYMBOL). Each pair (SYMBOL INITFORM) specifies a single intermediate variable: - INITFORM is an expression evaluated to produce EXPR-i - SYMBOL is the name of the variable that will be bound around FORMS to the corresponding gensym GENSYM-i, in order for FORMS to generate RES that references the intermediate variable The evaluation of INITFORMs and binding of SYMBOLs resembles LET. INITFORMs of all the pairs are evaluated before binding SYMBOLs and evaluating FORMS. Example: The following expression (let ((x '(incf y))) (once-only (x) `(cons ,x ,x))) ;;; => ( let ( ( # 1=#:X123 ( incf y ) ) ) ( cons # 1 # # 1 # ) ) could be used within a macro to avoid multiple evaluation like so (defmacro cons1 (x) (once-only (x) `(cons ,x ,x))) (let ((y 0)) (cons1 (incf y))) = > ( 1 . 1 ) Example: The following expression demonstrates the usage of the INITFORM field (let ((expr '(incf y))) (once-only ((var `(1+ ,expr))) `(list ',expr ,var ,var))) ;;; => ( let ( ( # 1=#:VAR123 ( 1 + ( incf y ) ) ) ) ( list ' ( incf y ) # 1 # # 1 ) ) which could be used like so (defmacro print-succ-twice (expr) (once-only ((var `(1+ ,expr))) `(format t \"Expr: ~s, Once: ~s, Twice: ~s~%\" ',expr ,var ,var))) (let ((y 10)) (print-succ-twice (incf y))) ;;; >> Expr : ( INCF Y ) , Once : 12 , Twice : 12 " (let ((gensyms (make-gensym-list (length specs) "ONCE-ONLY")) (names-and-forms (mapcar (lambda (spec) (etypecase spec (list (destructuring-bind (name form) spec (cons name form))) (symbol (cons spec spec)))) specs))) ;; bind in user-macro `(let ,(mapcar (lambda (g n) (list g `(gensym ,(string (car n))))) gensyms names-and-forms) ;; bind in final expansion `(let (,,@(mapcar (lambda (g n) ``(,,g ,,(cdr n))) gensyms names-and-forms)) ;; bind in user-macro ,(let ,(mapcar (lambda (n g) (list (car n) g)) names-and-forms gensyms) ,@forms))))) (defun parse-body (body &key documentation whole) "Parses BODY into (values remaining-forms declarations doc-string). Documentation strings are recognized only if DOCUMENTATION is true. Syntax errors in body are signalled and WHOLE is used in the signal arguments when given." (let ((doc nil) (decls nil) (current nil)) (tagbody :declarations (setf current (car body)) (when (and documentation (stringp current) (cdr body)) (if doc (error "Too many documentation strings in ~S." (or whole body)) (setf doc (pop body))) (go :declarations)) (when (and (listp current) (eql (first current) 'declare)) (push (pop body) decls) (go :declarations))) (values body (nreverse decls) doc))) (defun parse-ordinary-lambda-list (lambda-list &key (normalize t) allow-specializers (normalize-optional normalize) (normalize-keyword normalize) (normalize-auxilary normalize)) "Parses an ordinary lambda-list, returning as multiple values: 1. Required parameters. 2. Optional parameter specifications, normalized into form: (name init suppliedp) 3. Name of the rest parameter, or NIL. 4. Keyword parameter specifications, normalized into form: ((keyword-name name) init suppliedp) 5. Boolean indicating &ALLOW-OTHER-KEYS presence. 6. &AUX parameter specifications, normalized into form (name init). 7. Existence of &KEY in the lambda-list. Signals a PROGRAM-ERROR is the lambda-list is malformed." (let ((state :required) (allow-other-keys nil) (auxp nil) (required nil) (optional nil) (rest nil) (keys nil) (keyp nil) (aux nil)) (labels ((fail (elt) (simple-program-error "Misplaced ~S in ordinary lambda-list:~% ~S" elt lambda-list)) (check-variable (elt what &optional (allow-specializers allow-specializers)) (unless (and (or (symbolp elt) (and allow-specializers (consp elt) (= 2 (length elt)) (symbolp (first elt)))) (not (constantp elt))) (simple-program-error "Invalid ~A ~S in ordinary lambda-list:~% ~S" what elt lambda-list))) (check-spec (spec what) (destructuring-bind (init suppliedp) spec (declare (ignore init)) (check-variable suppliedp what nil)))) (dolist (elt lambda-list) (case elt (&optional (if (eq state :required) (setf state elt) (fail elt))) (&rest (if (member state '(:required &optional)) (setf state elt) (fail elt))) (&key (if (member state '(:required &optional :after-rest)) (setf state elt) (fail elt)) (setf keyp t)) (&allow-other-keys (if (eq state '&key) (setf allow-other-keys t state elt) (fail elt))) (&aux (cond ((eq state '&rest) (fail elt)) (auxp (simple-program-error "Multiple ~S in ordinary lambda-list:~% ~S" elt lambda-list)) (t (setf auxp t state elt)) )) (otherwise (when (member elt '#.(set-difference lambda-list-keywords '(&optional &rest &key &allow-other-keys &aux))) (simple-program-error "Bad lambda-list keyword ~S in ordinary lambda-list:~% ~S" elt lambda-list)) (case state (:required (check-variable elt "required parameter") (push elt required)) (&optional (cond ((consp elt) (destructuring-bind (name &rest tail) elt (check-variable name "optional parameter") (cond ((cdr tail) (check-spec tail "optional-supplied-p parameter")) ((and normalize-optional tail) (setf elt (append elt '(nil)))) (normalize-optional (setf elt (append elt '(nil nil))))))) (t (check-variable elt "optional parameter") (when normalize-optional (setf elt (cons elt '(nil nil)))))) (push (ensure-list elt) optional)) (&rest (check-variable elt "rest parameter") (setf rest elt state :after-rest)) (&key (cond ((consp elt) (destructuring-bind (var-or-kv &rest tail) elt (cond ((consp var-or-kv) (destructuring-bind (keyword var) var-or-kv (unless (symbolp keyword) (simple-program-error "Invalid keyword name ~S in ordinary ~ lambda-list:~% ~S" keyword lambda-list)) (check-variable var "keyword parameter"))) (t (check-variable var-or-kv "keyword parameter") (when normalize-keyword (setf var-or-kv (list (make-keyword var-or-kv) var-or-kv))))) (cond ((cdr tail) (check-spec tail "keyword-supplied-p parameter")) ((and normalize-keyword tail) (setf tail (append tail '(nil)))) (normalize-keyword (setf tail '(nil nil)))) (setf elt (cons var-or-kv tail)))) (t (check-variable elt "keyword parameter") (setf elt (if normalize-keyword (list (list (make-keyword elt) elt) nil nil) elt)))) (push elt keys)) (&aux (if (consp elt) (destructuring-bind (var &optional init) elt (declare (ignore init)) (check-variable var "&aux parameter")) (progn (check-variable elt "&aux parameter") (setf elt (list* elt (when normalize-auxilary '(nil)))))) (push elt aux)) (t (simple-program-error "Invalid ordinary lambda-list:~% ~S" lambda-list))))))) (values (nreverse required) (nreverse optional) rest (nreverse keys) allow-other-keys (nreverse aux) keyp))) ;;;; DESTRUCTURING-*CASE (defun expand-destructuring-case (key clauses case) (once-only (key) `(if (typep ,key 'cons) (,case (car ,key) ,@(mapcar (lambda (clause) (destructuring-bind ((keys . lambda-list) &body body) clause `(,keys (destructuring-bind ,lambda-list (cdr ,key) ,@body)))) clauses)) (error "Invalid key to DESTRUCTURING-~S: ~S" ',case ,key)))) (defmacro destructuring-case (keyform &body clauses) "DESTRUCTURING-CASE, -CCASE, and -ECASE are a combination of CASE and DESTRUCTURING-BIND. KEYFORM must evaluate to a CONS. Clauses are of the form: ((CASE-KEYS . DESTRUCTURING-LAMBDA-LIST) FORM*) The clause whose CASE-KEYS matches CAR of KEY, as if by CASE, CCASE, or ECASE, is selected, and FORMs are then executed with CDR of KEY is destructured and bound by the DESTRUCTURING-LAMBDA-LIST. Example: (defun dcase (x) (destructuring-case x ((:foo a b) (format nil \"foo: ~S, ~S\" a b)) ((:bar &key a b) (format nil \"bar: ~S, ~S\" a b)) (((:alt1 :alt2) a) (format nil \"alt: ~S\" a)) ((t &rest rest) (format nil \"unknown: ~S\" rest)))) = > \"foo : 1 , 2\ " = > \"bar : 1 , 2\ " = > \"alt : 1\ " = > \"alt : 2\ " = > \"unknown : 1 , 2 , 3\ " (defun decase (x) (destructuring-case x ((:foo a b) (format nil \"foo: ~S, ~S\" a b)) ((:bar &key a b) (format nil \"bar: ~S, ~S\" a b)) (((:alt1 :alt2) a) (format nil \"alt: ~S\" a)))) = > \"foo : 1 , 2\ " = > \"bar : 1 , 2\ " = > \"alt : 1\ " = > \"alt : 2\ " (decase (list :quux 1 2 3)) ; =| error " (expand-destructuring-case keyform clauses 'case)) (defmacro destructuring-ccase (keyform &body clauses) (expand-destructuring-case keyform clauses 'ccase)) (defmacro destructuring-ecase (keyform &body clauses) (expand-destructuring-case keyform clauses 'ecase)) (dolist (name '(destructuring-ccase destructuring-ecase)) (setf (documentation name 'function) (documentation 'destructuring-case 'function)))
null
https://raw.githubusercontent.com/xh4/web-toolkit/e510d44a25b36ca8acd66734ed1ee9f5fe6ecd09/vendor/alexandria-20191227-git/macros.lisp
lisp
=> => >> bind in user-macro bind in final expansion bind in user-macro DESTRUCTURING-*CASE =| error
(in-package :alexandria) (defmacro with-gensyms (names &body forms) "Binds a set of variables to gensyms and evaluates the implicit progn FORMS. Each element within NAMES is either a symbol SYMBOL or a pair (SYMBOL STRING-DESIGNATOR). Bare symbols are equivalent to the pair (SYMBOL SYMBOL). Each pair (SYMBOL STRING-DESIGNATOR) specifies that the variable named by SYMBOL should be bound to a symbol constructed using GENSYM with the string designated by STRING-DESIGNATOR being its first argument." `(let ,(mapcar (lambda (name) (multiple-value-bind (symbol string) (etypecase name (symbol (values name (symbol-name name))) ((cons symbol (cons string-designator null)) (values (first name) (string (second name))))) `(,symbol (gensym ,string)))) names) ,@forms)) (defmacro with-unique-names (names &body forms) "Alias for WITH-GENSYMS." `(with-gensyms ,names ,@forms)) (defmacro once-only (specs &body forms) "Constructs code whose primary goal is to help automate the handling of multiple evaluation within macros. Multiple evaluation is handled by introducing intermediate variables, in order to reuse the result of an expression. The returned value is a list of the form (let ((<gensym-1> <expr-1>) ... (<gensym-n> <expr-n>)) <res>) where GENSYM-1, ..., GENSYM-N are the intermediate variables introduced in order to evaluate EXPR-1, ..., EXPR-N once, only. RES is code that is the result of evaluating the implicit progn FORMS within a special context determined by SPECS. RES should make use of (reference) the intermediate variables. Each element within SPECS is either a symbol SYMBOL or a pair (SYMBOL INITFORM). Bare symbols are equivalent to the pair (SYMBOL SYMBOL). Each pair (SYMBOL INITFORM) specifies a single intermediate variable: - INITFORM is an expression evaluated to produce EXPR-i - SYMBOL is the name of the variable that will be bound around FORMS to the corresponding gensym GENSYM-i, in order for FORMS to generate RES that references the intermediate variable The evaluation of INITFORMs and binding of SYMBOLs resembles LET. INITFORMs of all the pairs are evaluated before binding SYMBOLs and evaluating FORMS. Example: The following expression (let ((x '(incf y))) (once-only (x) `(cons ,x ,x))) ( let ( ( # 1=#:X123 ( incf y ) ) ) ( cons # 1 # # 1 # ) ) could be used within a macro to avoid multiple evaluation like so (defmacro cons1 (x) (once-only (x) `(cons ,x ,x))) (let ((y 0)) (cons1 (incf y))) = > ( 1 . 1 ) Example: The following expression demonstrates the usage of the INITFORM field (let ((expr '(incf y))) (once-only ((var `(1+ ,expr))) `(list ',expr ,var ,var))) ( let ( ( # 1=#:VAR123 ( 1 + ( incf y ) ) ) ) ( list ' ( incf y ) # 1 # # 1 ) ) which could be used like so (defmacro print-succ-twice (expr) (once-only ((var `(1+ ,expr))) `(format t \"Expr: ~s, Once: ~s, Twice: ~s~%\" ',expr ,var ,var))) (let ((y 10)) (print-succ-twice (incf y))) Expr : ( INCF Y ) , Once : 12 , Twice : 12 " (let ((gensyms (make-gensym-list (length specs) "ONCE-ONLY")) (names-and-forms (mapcar (lambda (spec) (etypecase spec (list (destructuring-bind (name form) spec (cons name form))) (symbol (cons spec spec)))) specs))) `(let ,(mapcar (lambda (g n) (list g `(gensym ,(string (car n))))) gensyms names-and-forms) `(let (,,@(mapcar (lambda (g n) ``(,,g ,,(cdr n))) gensyms names-and-forms)) ,(let ,(mapcar (lambda (n g) (list (car n) g)) names-and-forms gensyms) ,@forms))))) (defun parse-body (body &key documentation whole) "Parses BODY into (values remaining-forms declarations doc-string). Documentation strings are recognized only if DOCUMENTATION is true. Syntax errors in body are signalled and WHOLE is used in the signal arguments when given." (let ((doc nil) (decls nil) (current nil)) (tagbody :declarations (setf current (car body)) (when (and documentation (stringp current) (cdr body)) (if doc (error "Too many documentation strings in ~S." (or whole body)) (setf doc (pop body))) (go :declarations)) (when (and (listp current) (eql (first current) 'declare)) (push (pop body) decls) (go :declarations))) (values body (nreverse decls) doc))) (defun parse-ordinary-lambda-list (lambda-list &key (normalize t) allow-specializers (normalize-optional normalize) (normalize-keyword normalize) (normalize-auxilary normalize)) "Parses an ordinary lambda-list, returning as multiple values: 1. Required parameters. 2. Optional parameter specifications, normalized into form: (name init suppliedp) 3. Name of the rest parameter, or NIL. 4. Keyword parameter specifications, normalized into form: ((keyword-name name) init suppliedp) 5. Boolean indicating &ALLOW-OTHER-KEYS presence. 6. &AUX parameter specifications, normalized into form (name init). 7. Existence of &KEY in the lambda-list. Signals a PROGRAM-ERROR is the lambda-list is malformed." (let ((state :required) (allow-other-keys nil) (auxp nil) (required nil) (optional nil) (rest nil) (keys nil) (keyp nil) (aux nil)) (labels ((fail (elt) (simple-program-error "Misplaced ~S in ordinary lambda-list:~% ~S" elt lambda-list)) (check-variable (elt what &optional (allow-specializers allow-specializers)) (unless (and (or (symbolp elt) (and allow-specializers (consp elt) (= 2 (length elt)) (symbolp (first elt)))) (not (constantp elt))) (simple-program-error "Invalid ~A ~S in ordinary lambda-list:~% ~S" what elt lambda-list))) (check-spec (spec what) (destructuring-bind (init suppliedp) spec (declare (ignore init)) (check-variable suppliedp what nil)))) (dolist (elt lambda-list) (case elt (&optional (if (eq state :required) (setf state elt) (fail elt))) (&rest (if (member state '(:required &optional)) (setf state elt) (fail elt))) (&key (if (member state '(:required &optional :after-rest)) (setf state elt) (fail elt)) (setf keyp t)) (&allow-other-keys (if (eq state '&key) (setf allow-other-keys t state elt) (fail elt))) (&aux (cond ((eq state '&rest) (fail elt)) (auxp (simple-program-error "Multiple ~S in ordinary lambda-list:~% ~S" elt lambda-list)) (t (setf auxp t state elt)) )) (otherwise (when (member elt '#.(set-difference lambda-list-keywords '(&optional &rest &key &allow-other-keys &aux))) (simple-program-error "Bad lambda-list keyword ~S in ordinary lambda-list:~% ~S" elt lambda-list)) (case state (:required (check-variable elt "required parameter") (push elt required)) (&optional (cond ((consp elt) (destructuring-bind (name &rest tail) elt (check-variable name "optional parameter") (cond ((cdr tail) (check-spec tail "optional-supplied-p parameter")) ((and normalize-optional tail) (setf elt (append elt '(nil)))) (normalize-optional (setf elt (append elt '(nil nil))))))) (t (check-variable elt "optional parameter") (when normalize-optional (setf elt (cons elt '(nil nil)))))) (push (ensure-list elt) optional)) (&rest (check-variable elt "rest parameter") (setf rest elt state :after-rest)) (&key (cond ((consp elt) (destructuring-bind (var-or-kv &rest tail) elt (cond ((consp var-or-kv) (destructuring-bind (keyword var) var-or-kv (unless (symbolp keyword) (simple-program-error "Invalid keyword name ~S in ordinary ~ lambda-list:~% ~S" keyword lambda-list)) (check-variable var "keyword parameter"))) (t (check-variable var-or-kv "keyword parameter") (when normalize-keyword (setf var-or-kv (list (make-keyword var-or-kv) var-or-kv))))) (cond ((cdr tail) (check-spec tail "keyword-supplied-p parameter")) ((and normalize-keyword tail) (setf tail (append tail '(nil)))) (normalize-keyword (setf tail '(nil nil)))) (setf elt (cons var-or-kv tail)))) (t (check-variable elt "keyword parameter") (setf elt (if normalize-keyword (list (list (make-keyword elt) elt) nil nil) elt)))) (push elt keys)) (&aux (if (consp elt) (destructuring-bind (var &optional init) elt (declare (ignore init)) (check-variable var "&aux parameter")) (progn (check-variable elt "&aux parameter") (setf elt (list* elt (when normalize-auxilary '(nil)))))) (push elt aux)) (t (simple-program-error "Invalid ordinary lambda-list:~% ~S" lambda-list))))))) (values (nreverse required) (nreverse optional) rest (nreverse keys) allow-other-keys (nreverse aux) keyp))) (defun expand-destructuring-case (key clauses case) (once-only (key) `(if (typep ,key 'cons) (,case (car ,key) ,@(mapcar (lambda (clause) (destructuring-bind ((keys . lambda-list) &body body) clause `(,keys (destructuring-bind ,lambda-list (cdr ,key) ,@body)))) clauses)) (error "Invalid key to DESTRUCTURING-~S: ~S" ',case ,key)))) (defmacro destructuring-case (keyform &body clauses) "DESTRUCTURING-CASE, -CCASE, and -ECASE are a combination of CASE and DESTRUCTURING-BIND. KEYFORM must evaluate to a CONS. Clauses are of the form: ((CASE-KEYS . DESTRUCTURING-LAMBDA-LIST) FORM*) The clause whose CASE-KEYS matches CAR of KEY, as if by CASE, CCASE, or ECASE, is selected, and FORMs are then executed with CDR of KEY is destructured and bound by the DESTRUCTURING-LAMBDA-LIST. Example: (defun dcase (x) (destructuring-case x ((:foo a b) (format nil \"foo: ~S, ~S\" a b)) ((:bar &key a b) (format nil \"bar: ~S, ~S\" a b)) (((:alt1 :alt2) a) (format nil \"alt: ~S\" a)) ((t &rest rest) (format nil \"unknown: ~S\" rest)))) = > \"foo : 1 , 2\ " = > \"bar : 1 , 2\ " = > \"alt : 1\ " = > \"alt : 2\ " = > \"unknown : 1 , 2 , 3\ " (defun decase (x) (destructuring-case x ((:foo a b) (format nil \"foo: ~S, ~S\" a b)) ((:bar &key a b) (format nil \"bar: ~S, ~S\" a b)) (((:alt1 :alt2) a) (format nil \"alt: ~S\" a)))) = > \"foo : 1 , 2\ " = > \"bar : 1 , 2\ " = > \"alt : 1\ " = > \"alt : 2\ " " (expand-destructuring-case keyform clauses 'case)) (defmacro destructuring-ccase (keyform &body clauses) (expand-destructuring-case keyform clauses 'ccase)) (defmacro destructuring-ecase (keyform &body clauses) (expand-destructuring-case keyform clauses 'ecase)) (dolist (name '(destructuring-ccase destructuring-ecase)) (setf (documentation name 'function) (documentation 'destructuring-case 'function)))
02ff6cd221007d6bc1e043fb10e504eb0230e953b47f600d62b21637e93ea2ac
input-output-hk/plutus-apps
Tx.hs
{-# LANGUAGE DataKinds #-} # LANGUAGE DerivingVia # # LANGUAGE FlexibleInstances # # LANGUAGE GADTs # # LANGUAGE LambdaCase # # LANGUAGE NamedFieldPuns # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE PolyKinds # {-# LANGUAGE RankNTypes #-} # LANGUAGE ScopedTypeVariables # # LANGUAGE TupleSections # {-| The chain index' version of a transaction -} module Plutus.ChainIndex.Tx( ChainIndexTx(..) , ChainIndexTxOutputs(..) , ChainIndexTxOut(..) , ReferenceScript(..) , Address(..) , OutputDatum(..) , Value(..) , fromOnChainTx , txOuts , txOutRefs , txOutsWithRef , txOutRefMap , txOutRefMapForAddr , txRedeemersWithHash , validityFromChainIndex -- ** Lenses , citxTxId , citxInputs , citxOutputs , citxValidRange , citxData , citxRedeemers , citxScripts , citxCardanoTx , _InvalidTx , _ValidTx ) where import Data.Map (Map) import Data.Map qualified as Map import Data.Tuple (swap) import Ledger (CardanoTx (CardanoTx), OnChainTx (..), TxOutRef (..)) import Ledger.Address (CardanoAddress) import Ledger.Scripts (Redeemer, RedeemerHash) import Plutus.ChainIndex.Types import Plutus.Contract.CardanoAPI (fromCardanoTx, setValidity) import Plutus.Script.Utils.Scripts (redeemerHash) import Plutus.V2.Ledger.Api (Address (..), OutputDatum (..), Value (..)) | Get tx outputs from tx . txOuts :: ChainIndexTx -> [ChainIndexTxOut] txOuts ChainIndexTx { _citxOutputs = ValidTx outputs } = outputs txOuts ChainIndexTx { _citxOutputs = InvalidTx (Just output) } = [ output ] txOuts ChainIndexTx { _citxOutputs = InvalidTx Nothing } = [] | Get tx output references from tx . txOutRefs :: ChainIndexTx -> [TxOutRef] txOutRefs tx = [ TxOutRef (_citxTxId tx) (fromIntegral idx) | idx <- [0 .. length (txOuts tx) - 1] ] | Get tx output references and tx outputs from tx . txOutsWithRef :: ChainIndexTx -> [(ChainIndexTxOut, TxOutRef)] txOutsWithRef tx = zip (txOuts tx) (txOutRefs tx) | Get ' Map ' of tx outputs references to tx . txOutRefMap :: ChainIndexTx -> Map TxOutRef (ChainIndexTxOut, ChainIndexTx) txOutRefMap tx = fmap (, tx) $ Map.fromList $ fmap swap $ txOutsWithRef tx | Get ' Map ' of tx outputs from tx for a specific address . txOutRefMapForAddr :: CardanoAddress -> ChainIndexTx -> Map TxOutRef (ChainIndexTxOut, ChainIndexTx) txOutRefMapForAddr addr tx = Map.filter ((==) addr . citoAddress . fst) $ txOutRefMap tx validityFromChainIndex :: ChainIndexTx -> TxValidity validityFromChainIndex tx = case _citxOutputs tx of InvalidTx _ -> TxInvalid ValidTx _ -> TxValid -- | Convert a 'OnChainTx' to a 'ChainIndexTx'. An invalid 'OnChainTx' will not -- produce any 'ChainIndexTx' outputs and the collateral inputs of the -- 'OnChainTx' will be the inputs of the 'ChainIndexTx'. -- -- Cardano api transactions store validity internally. Our emulated blockchain stores validity outside of the transactions, -- so we need to make sure these match up. fromOnChainTx :: OnChainTx -> ChainIndexTx fromOnChainTx = \case Valid (CardanoTx tx era) -> fromCardanoTx era $ setValidity True tx Invalid (CardanoTx tx era) -> fromCardanoTx era $ setValidity False tx txRedeemersWithHash :: ChainIndexTx -> Map RedeemerHash Redeemer txRedeemersWithHash ChainIndexTx{_citxRedeemers} = Map.fromList $ fmap (\r -> (redeemerHash r, r)) $ Map.elems _citxRedeemers
null
https://raw.githubusercontent.com/input-output-hk/plutus-apps/b80116b9dd97e83b61f016924f83ad4284212796/plutus-chain-index-core/src/Plutus/ChainIndex/Tx.hs
haskell
# LANGUAGE DataKinds # # LANGUAGE OverloadedStrings # # LANGUAGE RankNTypes # | The chain index' version of a transaction ** Lenses | Convert a 'OnChainTx' to a 'ChainIndexTx'. An invalid 'OnChainTx' will not produce any 'ChainIndexTx' outputs and the collateral inputs of the 'OnChainTx' will be the inputs of the 'ChainIndexTx'. Cardano api transactions store validity internally. Our emulated blockchain stores validity outside of the transactions, so we need to make sure these match up.
# LANGUAGE DerivingVia # # LANGUAGE FlexibleInstances # # LANGUAGE GADTs # # LANGUAGE LambdaCase # # LANGUAGE NamedFieldPuns # # LANGUAGE PolyKinds # # LANGUAGE ScopedTypeVariables # # LANGUAGE TupleSections # module Plutus.ChainIndex.Tx( ChainIndexTx(..) , ChainIndexTxOutputs(..) , ChainIndexTxOut(..) , ReferenceScript(..) , Address(..) , OutputDatum(..) , Value(..) , fromOnChainTx , txOuts , txOutRefs , txOutsWithRef , txOutRefMap , txOutRefMapForAddr , txRedeemersWithHash , validityFromChainIndex , citxTxId , citxInputs , citxOutputs , citxValidRange , citxData , citxRedeemers , citxScripts , citxCardanoTx , _InvalidTx , _ValidTx ) where import Data.Map (Map) import Data.Map qualified as Map import Data.Tuple (swap) import Ledger (CardanoTx (CardanoTx), OnChainTx (..), TxOutRef (..)) import Ledger.Address (CardanoAddress) import Ledger.Scripts (Redeemer, RedeemerHash) import Plutus.ChainIndex.Types import Plutus.Contract.CardanoAPI (fromCardanoTx, setValidity) import Plutus.Script.Utils.Scripts (redeemerHash) import Plutus.V2.Ledger.Api (Address (..), OutputDatum (..), Value (..)) | Get tx outputs from tx . txOuts :: ChainIndexTx -> [ChainIndexTxOut] txOuts ChainIndexTx { _citxOutputs = ValidTx outputs } = outputs txOuts ChainIndexTx { _citxOutputs = InvalidTx (Just output) } = [ output ] txOuts ChainIndexTx { _citxOutputs = InvalidTx Nothing } = [] | Get tx output references from tx . txOutRefs :: ChainIndexTx -> [TxOutRef] txOutRefs tx = [ TxOutRef (_citxTxId tx) (fromIntegral idx) | idx <- [0 .. length (txOuts tx) - 1] ] | Get tx output references and tx outputs from tx . txOutsWithRef :: ChainIndexTx -> [(ChainIndexTxOut, TxOutRef)] txOutsWithRef tx = zip (txOuts tx) (txOutRefs tx) | Get ' Map ' of tx outputs references to tx . txOutRefMap :: ChainIndexTx -> Map TxOutRef (ChainIndexTxOut, ChainIndexTx) txOutRefMap tx = fmap (, tx) $ Map.fromList $ fmap swap $ txOutsWithRef tx | Get ' Map ' of tx outputs from tx for a specific address . txOutRefMapForAddr :: CardanoAddress -> ChainIndexTx -> Map TxOutRef (ChainIndexTxOut, ChainIndexTx) txOutRefMapForAddr addr tx = Map.filter ((==) addr . citoAddress . fst) $ txOutRefMap tx validityFromChainIndex :: ChainIndexTx -> TxValidity validityFromChainIndex tx = case _citxOutputs tx of InvalidTx _ -> TxInvalid ValidTx _ -> TxValid fromOnChainTx :: OnChainTx -> ChainIndexTx fromOnChainTx = \case Valid (CardanoTx tx era) -> fromCardanoTx era $ setValidity True tx Invalid (CardanoTx tx era) -> fromCardanoTx era $ setValidity False tx txRedeemersWithHash :: ChainIndexTx -> Map RedeemerHash Redeemer txRedeemersWithHash ChainIndexTx{_citxRedeemers} = Map.fromList $ fmap (\r -> (redeemerHash r, r)) $ Map.elems _citxRedeemers
e9b9ac5cac049275efedcf2191ff8f20b59570573b62213444902e4225eba134
roosta/herb
code.cljs
(ns site.components.code (:require [reagent.core :as r] [cljsjs.highlight] [cljsjs.highlight.langs.clojure] [cljsjs.highlight.langs.xml] )) (defn code [{:keys [lang]} content] (let [el (r/atom nil)] (r/create-class {:component-did-mount #(.highlightBlock js/hljs @el) :reagent-render (fn [] [:pre {:class (name lang) :ref #(reset! el %)} [:code content]])})))
null
https://raw.githubusercontent.com/roosta/herb/64afb133a7bf51d7171a3c5260584c09dbe4e504/site/src/site/components/code.cljs
clojure
(ns site.components.code (:require [reagent.core :as r] [cljsjs.highlight] [cljsjs.highlight.langs.clojure] [cljsjs.highlight.langs.xml] )) (defn code [{:keys [lang]} content] (let [el (r/atom nil)] (r/create-class {:component-did-mount #(.highlightBlock js/hljs @el) :reagent-render (fn [] [:pre {:class (name lang) :ref #(reset! el %)} [:code content]])})))
e0cda0d4f1defa93c6eb1f96b485477b5eac267a5f03aeffdff0bfeda02278e6
christian-marie/git-vogue
git-vogue-ghc-mod.hs
-- Copyright © 2013 - 2015 Anchor Systems , Pty Ltd and Others -- -- The code in this file, and the program it is a part of, is -- made available to you by its authors as open source software: -- you can redistribute it and/or modify it under the terms of the 3 - clause BSD licence . -- # LANGUAGE LambdaCase # -- | Description: Check with "cabal check". module Main where import Control.Applicative import Control.Monad import Data.Char import Data.Foldable import Data.List hiding (and) import Data.Maybe import Data.Monoid import Data.Traversable import GhcMod import GhcMod.Monad import Git.Vogue.PluginCommon import Prelude hiding (and) import System.Exit main :: IO () main = f =<< getPluginCommand "Check your Haskell project for ghc-mod problems." "git-vogue-ghc-mod - check for ghc-mod problems" where f CmdName = putStrLn "ghc-mod" f (CmdCheck check_fs_list all_fs_list) = do check_fs <- read <$> readFile check_fs_list all_fs <- read <$> readFile all_fs_list Have to change to the project directory for each ghc - mod run or it -- will be sad. -- We run ghcModCheck in each , which will exit on the first failure . rs <- forProjects (hsProjects check_fs all_fs) $ \fs -> -- HLint.hs is weird and more of a config file than a source file, so ghc - mod does n't like it . -- -- Setup.hs can import cabal things magically, without requiring it to be mentioned in cabal ( which ghc - mod hates ) ghcModCheck $ filter (\x -> not ("HLint.hs" `isSuffixOf` x) && not ("Setup.hs" `isSuffixOf` x) && ".hs" `isSuffixOf` x) fs unless (and rs) exitFailure f CmdFix{} = do outputBad $ "There are outstanding ghc-mod failures, you need to fix this " <> "manually and then re-run check" exitFailure -- | Try to help the user out with some munging of error messages explain :: String -> String explain s -- A terrible heuristic, but it may help some people | "test" `isInfixOf` fmap toLower s && "hidden package" `isInfixOf` s = s <> "\n\tSuggestion: cabal configure --enable-tests\n" | "bench" `isInfixOf` fmap toLower s && "hidden package" `isInfixOf` s = s <> "\n\tSuggestion: cabal configure --enable-benchmarks\n" | "hGetContents: invalid argument" `isInfixOf` s = s <> "\n\tSuggestion: use cabal < 1.22\n" | otherwise = s -- | ghc-mod check all of the given files from the current directory -- -- This will print out output, and return a bool representing success. ghcModCheck :: [FilePath] -> IO Bool ghcModCheck files = do We ca n't actually check all at once , or ghc - mod gets confused , so we -- traverse (r,_) <- runGmOutT defaultOptions $ runGhcModT defaultOptions (traverse (check . pure) files) Seriously guys ? within eithers ? warn_errs <- case r of -- This is some kind of outer-error, we don't fail on it. Left e -> do outputUnfortunate . lineWrap 74 $ show e return [] -- And these are the warnings and errors. Right rs -> return rs Traverse the errors , picking errors and warnings out maybe_ws <- for warn_errs $ \case -- Errors in files Left e -> return . Just $ explain e -- Warnings, sometimes empty strings Right warn -> return $ if null warn then Nothing else Just warn let warns = catMaybes maybe_ws if null warns then do outputGood $ "Checked " <> show (length files) <> " file(s)" return True else do traverse_ outputBad warns return False
null
https://raw.githubusercontent.com/christian-marie/git-vogue/b9e9c5f0e0dc8d47bd0f397dea6fc64f41e04a8c/src/git-vogue-ghc-mod.hs
haskell
The code in this file, and the program it is a part of, is made available to you by its authors as open source software: you can redistribute it and/or modify it under the terms of | Description: Check with "cabal check". will be sad. HLint.hs is weird and more of a config file than a source file, so Setup.hs can import cabal things magically, without requiring it to | Try to help the user out with some munging of error messages A terrible heuristic, but it may help some people | ghc-mod check all of the given files from the current directory This will print out output, and return a bool representing success. traverse This is some kind of outer-error, we don't fail on it. And these are the warnings and errors. Errors in files Warnings, sometimes empty strings
Copyright © 2013 - 2015 Anchor Systems , Pty Ltd and Others the 3 - clause BSD licence . # LANGUAGE LambdaCase # module Main where import Control.Applicative import Control.Monad import Data.Char import Data.Foldable import Data.List hiding (and) import Data.Maybe import Data.Monoid import Data.Traversable import GhcMod import GhcMod.Monad import Git.Vogue.PluginCommon import Prelude hiding (and) import System.Exit main :: IO () main = f =<< getPluginCommand "Check your Haskell project for ghc-mod problems." "git-vogue-ghc-mod - check for ghc-mod problems" where f CmdName = putStrLn "ghc-mod" f (CmdCheck check_fs_list all_fs_list) = do check_fs <- read <$> readFile check_fs_list all_fs <- read <$> readFile all_fs_list Have to change to the project directory for each ghc - mod run or it We run ghcModCheck in each , which will exit on the first failure . rs <- forProjects (hsProjects check_fs all_fs) $ \fs -> ghc - mod does n't like it . be mentioned in cabal ( which ghc - mod hates ) ghcModCheck $ filter (\x -> not ("HLint.hs" `isSuffixOf` x) && not ("Setup.hs" `isSuffixOf` x) && ".hs" `isSuffixOf` x) fs unless (and rs) exitFailure f CmdFix{} = do outputBad $ "There are outstanding ghc-mod failures, you need to fix this " <> "manually and then re-run check" exitFailure explain :: String -> String explain s | "test" `isInfixOf` fmap toLower s && "hidden package" `isInfixOf` s = s <> "\n\tSuggestion: cabal configure --enable-tests\n" | "bench" `isInfixOf` fmap toLower s && "hidden package" `isInfixOf` s = s <> "\n\tSuggestion: cabal configure --enable-benchmarks\n" | "hGetContents: invalid argument" `isInfixOf` s = s <> "\n\tSuggestion: use cabal < 1.22\n" | otherwise = s ghcModCheck :: [FilePath] -> IO Bool ghcModCheck files = do We ca n't actually check all at once , or ghc - mod gets confused , so we (r,_) <- runGmOutT defaultOptions $ runGhcModT defaultOptions (traverse (check . pure) files) Seriously guys ? within eithers ? warn_errs <- case r of Left e -> do outputUnfortunate . lineWrap 74 $ show e return [] Right rs -> return rs Traverse the errors , picking errors and warnings out maybe_ws <- for warn_errs $ \case Left e -> return . Just $ explain e Right warn -> return $ if null warn then Nothing else Just warn let warns = catMaybes maybe_ws if null warns then do outputGood $ "Checked " <> show (length files) <> " file(s)" return True else do traverse_ outputBad warns return False
3fdccf2a606f8273ec06af7998507de5014f0f6760393a7a19d7c567402f760e
unison-code/uni-instr-sel
UniTarGen.hs
Main authors : < > Main authors: Gabriel Hjort Blindell <> -} Copyright ( c ) 2012 - 2017 , < > 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 . 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 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) 2012-2017, Gabriel Hjort Blindell <> 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. 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. -} import UniTarGen.Drivers import qualified UniTarGen.Drivers.GenerateTargetMachine as GenerateTM import Language.InstrSel.Utils.JSON import Language.InstrSel.Utils.IO import Data.Maybe ( fromJust , isNothing ) import System.Console.CmdArgs import System.Directory ( createDirectoryIfMissing ) import System.Exit ( exitWith ) ------------- -- Functions ------------- parseArgs :: Options parseArgs = Options { machDescFile = def &= name "m" &= name "machine-description" &= explicit &= typFile &= help "File containing a machine description." , parentModule = def &= name "p" &= name "parent-module" &= explicit &= help ( "Parent module to contain the generated module(s)." ) &= typDir , outDir = def &= name "o" &= name "output" &= explicit &= help ( "Directory that will contain the output." ) &= typDir , maxInstructionsPerSubModule = def &= name "max-instr-per-submodule" &= explicit &= help ( "Limits the maximum number of instructions per target-machine\ \submodule (default is " ++ show defaultMaxInstructionsPerSubModule ++ "). Lower this\ \number in case the submodules are too large to compiler." ) &= typ "INT" , prettyPrint = def &= name "pretty-print" &= explicit &= help ( "Pretty-print the output. Note that pretty printing \ \significantly increases the time it takes to generate the \ \output." ) } &= helpArg [ help "Displays this message." , name "h" , name "help" , explicit , groupname "Other flags" ] &= versionArg [ ignore ] &= program "uni-targen" &= summary ( "Unison (target machine generator) tool\n" ++ "Gabriel Hjort Blindell <>" ) -- | Returns output directory specified on the command line. Reports error if no -- directory is specified. getOutDir :: Options -> IO FilePath getOutDir opts = do let d = outDir opts when (isNothing d) $ reportErrorAndExit "No output directory provided." return $ (fromJust d) ++ "/" -- | If an output file is given as part of the options, then the returned -- function will emit all data to the output file with the output ID suffixed -- to the output file name (this may mean that several output files are -- produced). Otherwise the data will be emit to @STDOUT@. mkEmitFunction :: Options -> IO (Output -> IO ()) mkEmitFunction opts = do dir <- getOutDir opts return $ (\o -> do createDirectoryIfMissing True (dir ++ "/") emitToFile dir o) ---------------- Main program ---------------- main :: IO () main = do opts <- cmdArgs parseArgs output <- GenerateTM.run opts emit <- mkEmitFunction opts mapM_ emit output exitWith $ oExitCode $ last output
null
https://raw.githubusercontent.com/unison-code/uni-instr-sel/2edb2f3399ea43e75f33706261bd6b93bedc6762/uni-targen/UniTarGen.hs
haskell
----------- Functions ----------- | Returns output directory specified on the command line. Reports error if no directory is specified. | If an output file is given as part of the options, then the returned function will emit all data to the output file with the output ID suffixed to the output file name (this may mean that several output files are produced). Otherwise the data will be emit to @STDOUT@. -------------- --------------
Main authors : < > Main authors: Gabriel Hjort Blindell <> -} Copyright ( c ) 2012 - 2017 , < > 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 . 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 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) 2012-2017, Gabriel Hjort Blindell <> 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. 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. -} import UniTarGen.Drivers import qualified UniTarGen.Drivers.GenerateTargetMachine as GenerateTM import Language.InstrSel.Utils.JSON import Language.InstrSel.Utils.IO import Data.Maybe ( fromJust , isNothing ) import System.Console.CmdArgs import System.Directory ( createDirectoryIfMissing ) import System.Exit ( exitWith ) parseArgs :: Options parseArgs = Options { machDescFile = def &= name "m" &= name "machine-description" &= explicit &= typFile &= help "File containing a machine description." , parentModule = def &= name "p" &= name "parent-module" &= explicit &= help ( "Parent module to contain the generated module(s)." ) &= typDir , outDir = def &= name "o" &= name "output" &= explicit &= help ( "Directory that will contain the output." ) &= typDir , maxInstructionsPerSubModule = def &= name "max-instr-per-submodule" &= explicit &= help ( "Limits the maximum number of instructions per target-machine\ \submodule (default is " ++ show defaultMaxInstructionsPerSubModule ++ "). Lower this\ \number in case the submodules are too large to compiler." ) &= typ "INT" , prettyPrint = def &= name "pretty-print" &= explicit &= help ( "Pretty-print the output. Note that pretty printing \ \significantly increases the time it takes to generate the \ \output." ) } &= helpArg [ help "Displays this message." , name "h" , name "help" , explicit , groupname "Other flags" ] &= versionArg [ ignore ] &= program "uni-targen" &= summary ( "Unison (target machine generator) tool\n" ++ "Gabriel Hjort Blindell <>" ) getOutDir :: Options -> IO FilePath getOutDir opts = do let d = outDir opts when (isNothing d) $ reportErrorAndExit "No output directory provided." return $ (fromJust d) ++ "/" mkEmitFunction :: Options -> IO (Output -> IO ()) mkEmitFunction opts = do dir <- getOutDir opts return $ (\o -> do createDirectoryIfMissing True (dir ++ "/") emitToFile dir o) Main program main :: IO () main = do opts <- cmdArgs parseArgs output <- GenerateTM.run opts emit <- mkEmitFunction opts mapM_ emit output exitWith $ oExitCode $ last output
d6772a87674c211863e04ca82ca9afa5ad2133c8b95402b894fa506588366e43
bennn/dissertation
include.rkt
#lang racket/base (require (except-in greenman-thesis #%module-begin) re - use 's doclang2 module - begin to sort everything ;; into a doc binding (only-in scribble/doclang2 #%module-begin)) (provide (all-from-out greenman-thesis) #%module-begin)
null
https://raw.githubusercontent.com/bennn/dissertation/779bfe6f8fee19092849b7e2cfc476df33e9357b/dissertation/scrbl/include.rkt
racket
into a doc binding
#lang racket/base (require (except-in greenman-thesis #%module-begin) re - use 's doclang2 module - begin to sort everything (only-in scribble/doclang2 #%module-begin)) (provide (all-from-out greenman-thesis) #%module-begin)
acae0732cc93080bebd616e9e0706c3d4f767bc4ba962b3a7cc4d31c570fbca5
afiniate/aws_async
ddb_describetable.mli
open Core.Std open Async.Std val exec: Ddb_system.t -> String.t -> (Ddb_system.t * Ddb_describetable_t.result, Exn.t) Deferred.Result.t
null
https://raw.githubusercontent.com/afiniate/aws_async/44c27bf9f18f76e9e6405c2252098c4aa3d9a8bc/lib/dynamodb/ddb_describetable.mli
ocaml
open Core.Std open Async.Std val exec: Ddb_system.t -> String.t -> (Ddb_system.t * Ddb_describetable_t.result, Exn.t) Deferred.Result.t
7ca61d0d09d08610c6d42e66a5e602fd2f60b6be7f67b5f3b63f928bc1bbeb39
maybevoid/casimir
EffFunctor.hs
# LANGUAGE UndecidableInstances # module Casimir.Base.EffFunctor ( EffFunctor (..) ) where import Data.Kind import Casimir.Base.Lift import Casimir.Base.Effect class EffFunctor (lift :: (Type -> Type) -> (Type -> Type) -> Type) (comp :: (Type -> Type) -> Type) where effmap :: forall eff1 eff2 . (Effect eff1, Effect eff2) => lift eff1 eff2 -> comp eff1 -> comp eff2 instance {-# OVERLAPPABLE #-} ( EffFunctor Lift comp ) => EffFunctor HigherLift comp where effmap :: forall eff1 eff2 . (Effect eff1, Effect eff2) => HigherLift eff1 eff2 -> comp eff1 -> comp eff2 effmap (HigherLift lift _) comp = effmap (Lift lift) comp
null
https://raw.githubusercontent.com/maybevoid/casimir/ebbfa403739d6f258e6ac6793549006a0e8bff42/casimir/src/lib/Casimir/Base/EffFunctor.hs
haskell
# OVERLAPPABLE #
# LANGUAGE UndecidableInstances # module Casimir.Base.EffFunctor ( EffFunctor (..) ) where import Data.Kind import Casimir.Base.Lift import Casimir.Base.Effect class EffFunctor (lift :: (Type -> Type) -> (Type -> Type) -> Type) (comp :: (Type -> Type) -> Type) where effmap :: forall eff1 eff2 . (Effect eff1, Effect eff2) => lift eff1 eff2 -> comp eff1 -> comp eff2 ( EffFunctor Lift comp ) => EffFunctor HigherLift comp where effmap :: forall eff1 eff2 . (Effect eff1, Effect eff2) => HigherLift eff1 eff2 -> comp eff1 -> comp eff2 effmap (HigherLift lift _) comp = effmap (Lift lift) comp
38532232ef0d9589200543f90e5bd835879ca2083fda8dfdc7496c9adcf27798
eeng/shevek
es.cljs
(ns shevek.locales.es) (def translations {:sessions {:logout "Salir"} :home {:menu "Inicio" :title "Bienvenido!" :subtitle "Qué te gustaría analizar hoy?"} :cubes {:title "Cubos" :subtitle "Cubos de datos disponibles" :name "Nombre" :description "Descripción" :missing "No hay cubos definidos." :data-range "Rango de datos disponibles" :unauthorized-title "Cubo Inexistente" :unauthorized "El cubo ya no está disponible o no estás autorizado para verlo. Por favor, contactá al administrador para más información."} :dashboards {:title "Dashboards" :subtitle "Administrar dashboards" :search-hint "Filtrar por nombre o descripción" :missing "No has creado ningún dashboard todavía." :deleted "Dashboard '{1}' eliminado correctamente" :report-count #(cond (zero? %) "Sin reportes" (= 1 %) "1 reporte" :else "{1} reportes") :updated-at "Última Actualización" :new "Nuevo Dashboard" :name "Nombre" :description "Descripción"} :dashboard {:add-panel "Agregar Panel" :edit-panel "Modificar Panel" :duplicate-panel "Duplicar Panel" :fullscreen-panel "Maximizar/Minimizar" :remove-panel "Quitar Panel" :select-cube "Seleccioná un cubo para el reporte" :saved "Dashboard guardado correctamente" :share-disabled "<b>Compartir deshabilitado</b><br/>Debe guardar el dashboard antes de poder compartirlo." :share-hint "Este link es una referencia de sólo lectura a su dashboard. Cualquier cambio posterior será visible por los usuarios que posean en el link." :import "Importar Dashboard" :import-as-link "Importar como Link" :import-as-link-desc "El dashboard se guardará como un link al original. Cualquier cambio que el propietario realice sobre el original se verá reflejado en tu copia, pero no podrás realizar modificaciones." :import-as-copy "Importar como Copia" :import-as-copy-desc "Genera una copia completa del dashboard, lo cual te permitirá hacerle modificaciones. No recibirás actualizaciones posteriores realizadas sobre dashboard original." :import-name "Podés darle otro nombre aquí" :imported "Dashboard importado!"} :reports {:title "Reportes" :subtitle "Administrar reportes" :recent "Reportes Recientes" :missing "No has creado ningún reporte todavía. Seleccioná un cubo para crear uno y luego guardalo para que aparezca aquí." :name "Nombre" :description "Descripción" :updated-at "Última actualización" :saved "Reporte guardado correctamente" :deleted "Reporte '{1}' eliminado correctamente" :download-csv "Descargar en formato CSV" :new "Nuevo Reporte" :share-hint "Este link es una copia de su reporte. Cualquier cambio posterior no se verá reflejado en el reporte compartido."} :designer {:dimensions "Dimensiones" :measures "Métricas" :filters "Filtros" :split-on "Colocar En" :rows "Filas" :columns "Columnas" :limit "Límite" :sort-by "Ordenar Por" :granularity "Granularidad" :no-pinned "Arrastre dimensiones aquí para acceso rápido" :no-measures "Por favor seleccione al menos una métrica" :no-results "No se encontraron resultados que coincidan con los criterios especificados" :split-required "Se necesita al menos una dimensión en el split ver los datos en forma de {1}" :too-many-splits-for-chart "Para visualización de gráficos debe haber como máximo dos splits" :chart-with-second-split-on-rows "Debe colocar el segundo split en las columnas para poder generar el gráfico" :maximize "Maximizar Panel de Resultados" :minimize "Minimizar Panel de Resultados" :grand-total "Total General" :go-back "Volver al Dashboard"} :designer.period {:relative "Relativo" :specific "Específico" :latest "Ultimo" :latest-hour "Ultima Hora" :latest-day "Ultimo Día" :latest-7days "Ultimos 7 Días" :latest-30days "Ultimos 30 Días" :latest-90days "Ultimos 90 Días" :current "Actual" :current-day "Día de Hoy" :current-week "Esta Semana" :current-month "Este Mes" :current-quarter "Este Trimestre" :current-year "Este Año" :previous "Previo" :previous-day "Día de Ayer" :previous-week "Semana Pasada" :previous-month "Mes Pasado" :previous-quarter "Trimestre Pasado" :previous-year "Año Pasado" :from "Desde" :to "Hasta"} :designer.operator {:include "Incluir" :exclude "Excluir"} :designer.viztype {:totals "totales" :table "tabla" :bar-chart "barras" :line-chart "línea" :pie-chart "torta"} :send-to-dashboard {:title "Enviar a Dashboard" :label "Elegí el dashboard destino" :desc "Esta acción insertará una copia del reporte actual en el dashboard seleccionado." :success "El reporte fue enviado al dashboard seleccionado"} :share {:title "Compartir" :label "Link para compartir" :copy "Copiar" :copied "Link copiado!"} :raw-data {:menu "Ver datos desagregados" :title "Datos Desagregados" :showing "Primeros {1} eventos según filtro: " :button "Datos Desagregados"} :configuration {:menu "Configuración de la Aplicación, Gestionar Usuarios" :title "Configuración" :subtitle "Gestionar usuarios" :users "Usuarios"} :profile {:menu "Preferencias del Usuario, Cambiar Password" :preferences "Preferencias" :password "Cambiar Password"} :preferences {:lang "Lenguaje" :abbreviations "Abreviaturas de Números" :abbreviations-opts (fn [] [["User formato por defecto" "default"] ["No abreviar nada" "no"] ["Abreviar todo" "yes"]]) :saved "Preferencias guardadas!" :refresh-every "Refrescar cada" :refresh-every-opts (fn [] {0 "Nunca" 10 "10s" 30 "30s" 60 "1m" 600 "10m" 1800 "30m"}) :refresh-now "Actualizar Ahora"} :account {:current-password "Password Actual" :new-password "Nuevo Password" :saved "Tu cuenta se grabó correctamente" :invalid-current-password "es incorrecto"} :admin {:menu "Configurar Usuarios" :title "Administración" :subtitle "Configure los usuarios que podrán acceder al sistema y sus permisos" :users "Usuarios"} :users {:username "Usuario" :fullname "Nombre" :email "Email" :password-confirmation "Confirmación de Password" :invalid-credentials "Usuario y/o password incorrecto" :session-expired "Sesión expirada, por favor ingrese nuevamente" :password-hint "Dejar en blanco para no cambiarlo" :unauthorized "No tenés permisos suficientes para realizar esta acción. Por favor, contactá al administrador para más información." :basic-info "Información Básica" :permissions "Permisos" :search-hint "Filtrar por usuario o nombre" :deleted "Usuario eliminado!"} :permissions {:allowed-cubes "Cubes Visibles" :admin-all-cubes "Administradores pueden ver todo" :all-cubes "Puede ver todos los cubos" :no-cubes "No puede ver ningún cubo" :only-cubes-selected "Puede ver sólo los siguientes cubos" :all-measures "Todas las métricas serán visibles" :only-measures-selected "Sólo las siguientes métricas serán visibles" :select-measures "Seleccioná las métricas permitidas" :no-measures "Ninguna" :add-filter "Agregar Filtro"} :date-formats {:second "dd/MM/yyyy HH:mm:ss" :minute "dd/MM HH:mm" :hour "dd/MM/yy H 'hs'" :day "dd/MM/yy" :month "MM/yy"} :calendar {:days ["D" "L" "M" "M" "J" "V" "S"] :months ["Enero" "Febrero" "Marzo" "Abril" "Mayo" "Junio" "Julio" "Agosto" "Septiembre" "Octubre" "Noviembre" "Diciembre"] :monthsShort ["Ene" "Feb" "Mar" "Abr" "May" "Jun" "Jul" "Ago" "Sep" "Oct" "Nov" "Dic"] :today "Hoy" :now "Ahora" :dayNames ["Domingo" "Lunes" "Martes" "Miércoles" "Jueves" "Viernes" "Sábado"]} :actions {:ok "Aceptar" :cancel "Cancelar" :edit "Editar" :save "Guardar" :save-as "Guardar Como" :new "Crear" :delete "Eliminar" :close "Cerrar" :select "Seleccionar" :hold-delete "Clickee el botón y mantenga presionado por un segundo para confirmar" :search "Buscar" :confirm "Confirmar" :manage "Gestionar" :refresh "Refrescar" :import "Importar" :double-click-edit "Double click para editar"} :validation {:required "este campo es obligatorio" :email "no es una dirección válida" :password "debería tener al menos 7 letras y números (o símbolos)" :confirmation "no coincide con el valor anterior"} :boolean {:true "Si" :false "No"} :errors {:no-results "No se encontraron resultados." :no-desc "Sin descripción" :bad-gateway "El sistema no está disponible en este momento. Por favor, intente nuevamente más tarde." :unexpected "Lo sentimos pero algo salió mal. Hemos sido notificados y lo estaremos resolviendo a la brevedad." :page-not-found "La página solicitada no existe. Esto puede deberse a un error en la dirección ingresada o quizás la página fue movida."}})
null
https://raw.githubusercontent.com/eeng/shevek/7783b8037303b8dd5f320f35edee3bfbb2b41c02/src/cljs/shevek/locales/es.cljs
clojure
(ns shevek.locales.es) (def translations {:sessions {:logout "Salir"} :home {:menu "Inicio" :title "Bienvenido!" :subtitle "Qué te gustaría analizar hoy?"} :cubes {:title "Cubos" :subtitle "Cubos de datos disponibles" :name "Nombre" :description "Descripción" :missing "No hay cubos definidos." :data-range "Rango de datos disponibles" :unauthorized-title "Cubo Inexistente" :unauthorized "El cubo ya no está disponible o no estás autorizado para verlo. Por favor, contactá al administrador para más información."} :dashboards {:title "Dashboards" :subtitle "Administrar dashboards" :search-hint "Filtrar por nombre o descripción" :missing "No has creado ningún dashboard todavía." :deleted "Dashboard '{1}' eliminado correctamente" :report-count #(cond (zero? %) "Sin reportes" (= 1 %) "1 reporte" :else "{1} reportes") :updated-at "Última Actualización" :new "Nuevo Dashboard" :name "Nombre" :description "Descripción"} :dashboard {:add-panel "Agregar Panel" :edit-panel "Modificar Panel" :duplicate-panel "Duplicar Panel" :fullscreen-panel "Maximizar/Minimizar" :remove-panel "Quitar Panel" :select-cube "Seleccioná un cubo para el reporte" :saved "Dashboard guardado correctamente" :share-disabled "<b>Compartir deshabilitado</b><br/>Debe guardar el dashboard antes de poder compartirlo." :share-hint "Este link es una referencia de sólo lectura a su dashboard. Cualquier cambio posterior será visible por los usuarios que posean en el link." :import "Importar Dashboard" :import-as-link "Importar como Link" :import-as-link-desc "El dashboard se guardará como un link al original. Cualquier cambio que el propietario realice sobre el original se verá reflejado en tu copia, pero no podrás realizar modificaciones." :import-as-copy "Importar como Copia" :import-as-copy-desc "Genera una copia completa del dashboard, lo cual te permitirá hacerle modificaciones. No recibirás actualizaciones posteriores realizadas sobre dashboard original." :import-name "Podés darle otro nombre aquí" :imported "Dashboard importado!"} :reports {:title "Reportes" :subtitle "Administrar reportes" :recent "Reportes Recientes" :missing "No has creado ningún reporte todavía. Seleccioná un cubo para crear uno y luego guardalo para que aparezca aquí." :name "Nombre" :description "Descripción" :updated-at "Última actualización" :saved "Reporte guardado correctamente" :deleted "Reporte '{1}' eliminado correctamente" :download-csv "Descargar en formato CSV" :new "Nuevo Reporte" :share-hint "Este link es una copia de su reporte. Cualquier cambio posterior no se verá reflejado en el reporte compartido."} :designer {:dimensions "Dimensiones" :measures "Métricas" :filters "Filtros" :split-on "Colocar En" :rows "Filas" :columns "Columnas" :limit "Límite" :sort-by "Ordenar Por" :granularity "Granularidad" :no-pinned "Arrastre dimensiones aquí para acceso rápido" :no-measures "Por favor seleccione al menos una métrica" :no-results "No se encontraron resultados que coincidan con los criterios especificados" :split-required "Se necesita al menos una dimensión en el split ver los datos en forma de {1}" :too-many-splits-for-chart "Para visualización de gráficos debe haber como máximo dos splits" :chart-with-second-split-on-rows "Debe colocar el segundo split en las columnas para poder generar el gráfico" :maximize "Maximizar Panel de Resultados" :minimize "Minimizar Panel de Resultados" :grand-total "Total General" :go-back "Volver al Dashboard"} :designer.period {:relative "Relativo" :specific "Específico" :latest "Ultimo" :latest-hour "Ultima Hora" :latest-day "Ultimo Día" :latest-7days "Ultimos 7 Días" :latest-30days "Ultimos 30 Días" :latest-90days "Ultimos 90 Días" :current "Actual" :current-day "Día de Hoy" :current-week "Esta Semana" :current-month "Este Mes" :current-quarter "Este Trimestre" :current-year "Este Año" :previous "Previo" :previous-day "Día de Ayer" :previous-week "Semana Pasada" :previous-month "Mes Pasado" :previous-quarter "Trimestre Pasado" :previous-year "Año Pasado" :from "Desde" :to "Hasta"} :designer.operator {:include "Incluir" :exclude "Excluir"} :designer.viztype {:totals "totales" :table "tabla" :bar-chart "barras" :line-chart "línea" :pie-chart "torta"} :send-to-dashboard {:title "Enviar a Dashboard" :label "Elegí el dashboard destino" :desc "Esta acción insertará una copia del reporte actual en el dashboard seleccionado." :success "El reporte fue enviado al dashboard seleccionado"} :share {:title "Compartir" :label "Link para compartir" :copy "Copiar" :copied "Link copiado!"} :raw-data {:menu "Ver datos desagregados" :title "Datos Desagregados" :showing "Primeros {1} eventos según filtro: " :button "Datos Desagregados"} :configuration {:menu "Configuración de la Aplicación, Gestionar Usuarios" :title "Configuración" :subtitle "Gestionar usuarios" :users "Usuarios"} :profile {:menu "Preferencias del Usuario, Cambiar Password" :preferences "Preferencias" :password "Cambiar Password"} :preferences {:lang "Lenguaje" :abbreviations "Abreviaturas de Números" :abbreviations-opts (fn [] [["User formato por defecto" "default"] ["No abreviar nada" "no"] ["Abreviar todo" "yes"]]) :saved "Preferencias guardadas!" :refresh-every "Refrescar cada" :refresh-every-opts (fn [] {0 "Nunca" 10 "10s" 30 "30s" 60 "1m" 600 "10m" 1800 "30m"}) :refresh-now "Actualizar Ahora"} :account {:current-password "Password Actual" :new-password "Nuevo Password" :saved "Tu cuenta se grabó correctamente" :invalid-current-password "es incorrecto"} :admin {:menu "Configurar Usuarios" :title "Administración" :subtitle "Configure los usuarios que podrán acceder al sistema y sus permisos" :users "Usuarios"} :users {:username "Usuario" :fullname "Nombre" :email "Email" :password-confirmation "Confirmación de Password" :invalid-credentials "Usuario y/o password incorrecto" :session-expired "Sesión expirada, por favor ingrese nuevamente" :password-hint "Dejar en blanco para no cambiarlo" :unauthorized "No tenés permisos suficientes para realizar esta acción. Por favor, contactá al administrador para más información." :basic-info "Información Básica" :permissions "Permisos" :search-hint "Filtrar por usuario o nombre" :deleted "Usuario eliminado!"} :permissions {:allowed-cubes "Cubes Visibles" :admin-all-cubes "Administradores pueden ver todo" :all-cubes "Puede ver todos los cubos" :no-cubes "No puede ver ningún cubo" :only-cubes-selected "Puede ver sólo los siguientes cubos" :all-measures "Todas las métricas serán visibles" :only-measures-selected "Sólo las siguientes métricas serán visibles" :select-measures "Seleccioná las métricas permitidas" :no-measures "Ninguna" :add-filter "Agregar Filtro"} :date-formats {:second "dd/MM/yyyy HH:mm:ss" :minute "dd/MM HH:mm" :hour "dd/MM/yy H 'hs'" :day "dd/MM/yy" :month "MM/yy"} :calendar {:days ["D" "L" "M" "M" "J" "V" "S"] :months ["Enero" "Febrero" "Marzo" "Abril" "Mayo" "Junio" "Julio" "Agosto" "Septiembre" "Octubre" "Noviembre" "Diciembre"] :monthsShort ["Ene" "Feb" "Mar" "Abr" "May" "Jun" "Jul" "Ago" "Sep" "Oct" "Nov" "Dic"] :today "Hoy" :now "Ahora" :dayNames ["Domingo" "Lunes" "Martes" "Miércoles" "Jueves" "Viernes" "Sábado"]} :actions {:ok "Aceptar" :cancel "Cancelar" :edit "Editar" :save "Guardar" :save-as "Guardar Como" :new "Crear" :delete "Eliminar" :close "Cerrar" :select "Seleccionar" :hold-delete "Clickee el botón y mantenga presionado por un segundo para confirmar" :search "Buscar" :confirm "Confirmar" :manage "Gestionar" :refresh "Refrescar" :import "Importar" :double-click-edit "Double click para editar"} :validation {:required "este campo es obligatorio" :email "no es una dirección válida" :password "debería tener al menos 7 letras y números (o símbolos)" :confirmation "no coincide con el valor anterior"} :boolean {:true "Si" :false "No"} :errors {:no-results "No se encontraron resultados." :no-desc "Sin descripción" :bad-gateway "El sistema no está disponible en este momento. Por favor, intente nuevamente más tarde." :unexpected "Lo sentimos pero algo salió mal. Hemos sido notificados y lo estaremos resolviendo a la brevedad." :page-not-found "La página solicitada no existe. Esto puede deberse a un error en la dirección ingresada o quizás la página fue movida."}})
47be4c8fcdbe3a3b555eda2b17476946ebd77c0b5c92a2a3b6c0c9b6ddf7c264
bpoweski/consul-clojure
project.clj
(defproject consul-clojure "0.7.2" :description "A Consul client for Clojure applications." :url "-clojure" :license {:name "Eclipse Public License" :url "-v10.html"} :dependencies [[camel-snake-kebab "0.3.1" :exclusions [org.clojure/clojure com.keminglabs/cljx]] [cheshire "5.5.0"] [clj-http-lite "0.3.0" :exclusions [org.clojure/clojure]]] :profiles {:dev {:dependencies [[org.clojure/clojure "1.7.0"] [org.clojure/core.async "0.1.346.0-17112a-alpha"]]}})
null
https://raw.githubusercontent.com/bpoweski/consul-clojure/11627a538eabf3c2e8a9b0e3caf6d1944291ffd6/project.clj
clojure
(defproject consul-clojure "0.7.2" :description "A Consul client for Clojure applications." :url "-clojure" :license {:name "Eclipse Public License" :url "-v10.html"} :dependencies [[camel-snake-kebab "0.3.1" :exclusions [org.clojure/clojure com.keminglabs/cljx]] [cheshire "5.5.0"] [clj-http-lite "0.3.0" :exclusions [org.clojure/clojure]]] :profiles {:dev {:dependencies [[org.clojure/clojure "1.7.0"] [org.clojure/core.async "0.1.346.0-17112a-alpha"]]}})
7da83cbfe9560302c25096366fc7b0ef47a6ee66dd51df28fa3fd9385c406cdf
tschady/advent-of-code
d05.clj
(ns aoc.2017.d05 (:require [aoc.file-util :as file-util])) (def input (->> "2017/d05.txt" file-util/read-lines (mapv #(Integer/parseInt %)))) (defn steps-to-exit [tape update-fn] (loop [loc 0 tape tape steps 1] (let [cur-val (get tape loc) new-loc (+ loc cur-val) new-tape (update tape loc update-fn)] (if (>= new-loc (count tape)) steps (recur new-loc new-tape (inc steps)))))) (defn p2-offset-fn [n] (if (> n 2) (dec n) (inc n))) (defn part-1 [input] (steps-to-exit input inc)) (defn part-2 [input] (steps-to-exit input p2-offset-fn))
null
https://raw.githubusercontent.com/tschady/advent-of-code/1e4a95ef580c3bf635837eff52aa998b0acfc666/src/aoc/2017/d05.clj
clojure
(ns aoc.2017.d05 (:require [aoc.file-util :as file-util])) (def input (->> "2017/d05.txt" file-util/read-lines (mapv #(Integer/parseInt %)))) (defn steps-to-exit [tape update-fn] (loop [loc 0 tape tape steps 1] (let [cur-val (get tape loc) new-loc (+ loc cur-val) new-tape (update tape loc update-fn)] (if (>= new-loc (count tape)) steps (recur new-loc new-tape (inc steps)))))) (defn p2-offset-fn [n] (if (> n 2) (dec n) (inc n))) (defn part-1 [input] (steps-to-exit input inc)) (defn part-2 [input] (steps-to-exit input p2-offset-fn))
47f38856d42de9270cf573dfe7f154971e12e814f02090ce6ee5f0aa18b859ce
exercism/ocaml
test.ml
open OUnit2 open Connect let show_player = function | Some X -> "X" | Some O -> "O" | None -> "None" let ae exp got = assert_equal ~printer:show_player exp got let tests = [ "an empty board has no winner" >::(fun _ctxt -> let board = [ ". . . . ."; " . . . . ."; " . . . . ."; " . . . . ."; " . . . . ."; ] in ae None (connect board) ); "X can win on a 1x1 board" >::(fun _ctxt -> let board = ["X"] in ae (Some X) (connect board) ); "O can win on a 1x1 board" >::(fun _ctxt -> let board = ["O"] in ae (Some O) (connect board) ); "only edges does not make a winner" >::(fun _ctxt -> let board = [ "O O O X"; " X . . X"; " X . . X"; " X O O O"; ] in ae None (connect board) ); "illegal diagonal does not make a winner" >::(fun _ctxt -> let board = [ "X O . ."; " O X X X"; " O X O ."; " . O X ."; " X X O O"; ] in ae None (connect board) ); "nobody wins crossing adjacent angles" >::(fun _ctxt -> let board = [ "X . . ."; " . X O ."; " O . X O"; " . O . X"; " . . O ."; ] in ae None (connect board) ); "X wins crossing from left to right" >::(fun _ctxt -> let board = [ ". O . ."; " O X X X"; " O X O ."; " X X O X"; " . O X ."; ] in ae (Some X) (connect board) ); "O wins crossing from top to bottom" >::(fun _ctxt -> let board = [ ". O . ."; " O X X X"; " O O O ."; " X X O X"; " . O X ."; ] in ae (Some O) (connect board) ); "X wins using a convoluted path" >::(fun _ctxt -> let board = [ ". X X . ."; " X . X . X"; " . X . X ."; " . X X . ."; " O O O O O"; ] in ae (Some X) (connect board) ); "X wins using a spiral path" >::(fun _ctxt -> let board = [ "O X X X X X X X X"; " O X O O O O O O O"; " O X O X X X X X O"; " O X O X O O O X O"; " O X O X X X O X O"; " O X O O O X O X O"; " O X X X X X O X O"; " O O O O O O O X O"; " X X X X X X X X O"; ] in ae (Some X) (connect board) ); ] let () = run_test_tt_main ("connect tests" >::: tests)
null
https://raw.githubusercontent.com/exercism/ocaml/bfd6121f757817865a34db06c3188b5e0ccab518/exercises/practice/connect/test.ml
ocaml
open OUnit2 open Connect let show_player = function | Some X -> "X" | Some O -> "O" | None -> "None" let ae exp got = assert_equal ~printer:show_player exp got let tests = [ "an empty board has no winner" >::(fun _ctxt -> let board = [ ". . . . ."; " . . . . ."; " . . . . ."; " . . . . ."; " . . . . ."; ] in ae None (connect board) ); "X can win on a 1x1 board" >::(fun _ctxt -> let board = ["X"] in ae (Some X) (connect board) ); "O can win on a 1x1 board" >::(fun _ctxt -> let board = ["O"] in ae (Some O) (connect board) ); "only edges does not make a winner" >::(fun _ctxt -> let board = [ "O O O X"; " X . . X"; " X . . X"; " X O O O"; ] in ae None (connect board) ); "illegal diagonal does not make a winner" >::(fun _ctxt -> let board = [ "X O . ."; " O X X X"; " O X O ."; " . O X ."; " X X O O"; ] in ae None (connect board) ); "nobody wins crossing adjacent angles" >::(fun _ctxt -> let board = [ "X . . ."; " . X O ."; " O . X O"; " . O . X"; " . . O ."; ] in ae None (connect board) ); "X wins crossing from left to right" >::(fun _ctxt -> let board = [ ". O . ."; " O X X X"; " O X O ."; " X X O X"; " . O X ."; ] in ae (Some X) (connect board) ); "O wins crossing from top to bottom" >::(fun _ctxt -> let board = [ ". O . ."; " O X X X"; " O O O ."; " X X O X"; " . O X ."; ] in ae (Some O) (connect board) ); "X wins using a convoluted path" >::(fun _ctxt -> let board = [ ". X X . ."; " X . X . X"; " . X . X ."; " . X X . ."; " O O O O O"; ] in ae (Some X) (connect board) ); "X wins using a spiral path" >::(fun _ctxt -> let board = [ "O X X X X X X X X"; " O X O O O O O O O"; " O X O X X X X X O"; " O X O X O O O X O"; " O X O X X X O X O"; " O X O O O X O X O"; " O X X X X X O X O"; " O O O O O O O X O"; " X X X X X X X X O"; ] in ae (Some X) (connect board) ); ] let () = run_test_tt_main ("connect tests" >::: tests)
b6cf0e5307b390e294cd6b001440daa1c9902516b92e0d4215ddd99aeaa963da
davexunit/guile-allegro5
image.scm
(define-module (allegro addons image) #:use-module (system foreign) #:use-module (allegro utils) #:export (al-init-image-addon al-shutdown-image-addon al-get-allegro-image-version)) (define liballegro-image (dynamic-link "liballegro_image")) (define-syntax-rule (define-foreign name ret string-name args) (define name (pointer->procedure ret (dynamic-func string-name liballegro-image) args))) (define-foreign %al-init-image-addon uint8 "al_init_image_addon" '()) (define-foreign al-shutdown-image-addon void "al_shutdown_image_addon" '()) (define-foreign al-get-allegro-image-version uint32 "al_get_allegro_image_version" '()) (define (al-init-image-addon) (number->boolean (%al-init-image-addon)))
null
https://raw.githubusercontent.com/davexunit/guile-allegro5/614ecc978e034f7b7ba5bd23e27111c8fef81b56/allegro/addons/image.scm
scheme
(define-module (allegro addons image) #:use-module (system foreign) #:use-module (allegro utils) #:export (al-init-image-addon al-shutdown-image-addon al-get-allegro-image-version)) (define liballegro-image (dynamic-link "liballegro_image")) (define-syntax-rule (define-foreign name ret string-name args) (define name (pointer->procedure ret (dynamic-func string-name liballegro-image) args))) (define-foreign %al-init-image-addon uint8 "al_init_image_addon" '()) (define-foreign al-shutdown-image-addon void "al_shutdown_image_addon" '()) (define-foreign al-get-allegro-image-version uint32 "al_get_allegro_image_version" '()) (define (al-init-image-addon) (number->boolean (%al-init-image-addon)))
d941258742a1f644c44b3f97392ab218a91b4fd50e37de7e6b01e99fbc606e39
erlang/otp
ssl_key_update_SUITE.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 2020 - 2022 . All Rights Reserved . %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. %% %% %CopyrightEnd% %% -module(ssl_key_update_SUITE). -behaviour(ct_suite). %% Callback functions -export([all/0, groups/0, init_per_suite/1, end_per_suite/1, init_per_group/2, end_per_group/2, init_per_testcase/2, end_per_testcase/2]). %% Testcases -export([key_update_at_client/0, key_update_at_client/1, key_update_at_server/0, key_update_at_server/1, explicit_key_update/0, explicit_key_update/1]). -include_lib("common_test/include/ct.hrl"). -include_lib("ssl/src/ssl_api.hrl"). -include_lib("ssl/src/ssl_connection.hrl"). all() -> [{group, 'tlsv1.3'}]. groups() -> [{'tlsv1.3', [], tls_1_3_tests()}]. tls_1_3_tests() -> [key_update_at_client, key_update_at_server, explicit_key_update]. init_per_suite(Config0) -> catch crypto:stop(), try crypto:start() of ok -> ssl_test_lib:clean_start(), case proplists:get_bool(ecdh, proplists:get_value(public_keys, crypto:supports())) of true -> ssl_test_lib:make_ecdsa_cert(Config0); false -> {skip, "Missing EC crypto support"} end catch _:_ -> {skip, "Crypto did not start"} end. end_per_suite(_Config) -> ssl:stop(), application:unload(ssl), application:stop(crypto). init_per_group(GroupName, Config) -> ssl_test_lib:init_per_group(GroupName, Config). end_per_group(GroupName, Config) -> ssl_test_lib:end_per_group(GroupName, Config). init_per_testcase(_TestCase, Config) -> ssl_test_lib:ct_log_supported_protocol_versions(Config), ct:timetrap({seconds, 10}), Config. end_per_testcase(_TestCase, Config) -> Config. %%-------------------------------------------------------------------- %% Test Cases -------------------------------------------------------- %%-------------------------------------------------------------------- key_update_at_client() -> [{doc,"Test option 'key_update_at' between erlang client and erlang server." "Client initiating the update."}]. key_update_at_client(Config) -> key_update_at(Config, client). key_update_at_server() -> [{doc,"Test option 'key_update_at' between erlang client and erlang server." "Server initiating the update."}]. key_update_at_server(Config) -> key_update_at(Config, server). key_update_at(Config, Role) -> 15 bytes Server = ssl_test_lib:start_server(erlang, [{options, [{key_update_at, 14}]}], Config), Port = ssl_test_lib:inet_port(Server), {Client, #sslsocket{pid = [ClientReceiverPid, ClientSenderPid]}} = ssl_test_lib:start_client(erlang, [return_socket, {port, Port}, {options, [{key_update_at, 14}]}], Config), Server ! get_socket, #sslsocket{pid = [ServerReceiverPid, ServerSenderPid]} = receive {Server, {socket, S}} -> S end, Keys0 = get_keys(ClientReceiverPid, ClientSenderPid, ServerReceiverPid, ServerSenderPid), {Sender, Receiver} = case Role of client -> {Client, Server}; server -> {Server, Client} end, %% Sending bytes over limit triggers key update ssl_test_lib:send(Sender, Data), Data = ssl_test_lib:check_active_receive(Receiver, Data), TODO check if key has been updated ( needs debug logging of secrets ) ct:sleep(500), Keys1 = get_keys(ClientReceiverPid, ClientSenderPid, ServerReceiverPid, ServerSenderPid), verify_key_update(Keys0, Keys1), %% Test mechanism to prevent infinite loop of key updates 100 bytes ok = ssl_test_lib:send(Sender, BigData), ct:sleep(500), Keys2 = get_keys(ClientReceiverPid, ClientSenderPid, ServerReceiverPid, ServerSenderPid), verify_key_update(Keys1, Keys2), ssl_test_lib:close(Server), ssl_test_lib:close(Client). get_keys(ClientReceiverPid, ClientSenderPid, ServerReceiverPid, ServerSenderPid) -> F = fun(Pid) -> {connection, D} = sys:get_state(Pid), M0 = element(3, D), Cr = maps:get(current_write, M0), {Pid, {maps:get(security_parameters, Cr), maps:get(cipher_state, Cr)}} end, SendersKeys = [F(P) || P <- [ClientSenderPid, ServerSenderPid]], G = fun(Pid) -> {connection, D} = sys:get_state(Pid), #state{connection_states = Cs} = D, Cr = maps:get(current_read, Cs), {Pid, {maps:get(security_parameters,Cr), maps:get(cipher_state, Cr)}} end, ReceiversKeys = [G(P) || P <- [ClientReceiverPid, ServerReceiverPid]], maps:from_list(SendersKeys ++ ReceiversKeys). verify_key_update(Keys0, Keys1) -> V = fun(Pid, CurrentKeys) -> BaseKeys = maps:get(Pid, Keys0), ct:log("Pid = ~p~nBaseKeys = ~p~nCurrentKeys = ~p", [Pid, BaseKeys, CurrentKeys], [esc_chars]), case BaseKeys == CurrentKeys of true -> ct:fail("Keys don't differ for ~w", [Pid]); false -> ok end end, maps:foreach(V, Keys1). explicit_key_update() -> [{doc,"Test ssl:update_key/2 between erlang client and erlang server."}]. explicit_key_update(Config) -> 15 bytes Server = ssl_test_lib:start_server(erlang, [], Config), Port = ssl_test_lib:inet_port(Server), Client = ssl_test_lib:start_client(erlang, [{port, Port}], Config), ssl_test_lib:send_recv_result_active(Client, Server, Data), ssl_test_lib:update_keys(Client, write), ssl_test_lib:update_keys(Client, read_write), ssl_test_lib:send_recv_result_active(Client, Server, Data), ssl_test_lib:update_keys(Server, write), ssl_test_lib:update_keys(Server, read_write), ssl_test_lib:send_recv_result_active(Client, Server, Data), TODO check if key has been updated ( needs debug logging of secrets ) ssl_test_lib:close(Server), ssl_test_lib:close(Client).
null
https://raw.githubusercontent.com/erlang/otp/32f6ee47b1b55c3e4aec1273fb259fdcbfdbcf07/lib/ssl/test/ssl_key_update_SUITE.erl
erlang
%CopyrightBegin% you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. %CopyrightEnd% Callback functions Testcases -------------------------------------------------------------------- Test Cases -------------------------------------------------------- -------------------------------------------------------------------- Sending bytes over limit triggers key update Test mechanism to prevent infinite loop of key updates
Copyright Ericsson AB 2020 - 2022 . All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(ssl_key_update_SUITE). -behaviour(ct_suite). -export([all/0, groups/0, init_per_suite/1, end_per_suite/1, init_per_group/2, end_per_group/2, init_per_testcase/2, end_per_testcase/2]). -export([key_update_at_client/0, key_update_at_client/1, key_update_at_server/0, key_update_at_server/1, explicit_key_update/0, explicit_key_update/1]). -include_lib("common_test/include/ct.hrl"). -include_lib("ssl/src/ssl_api.hrl"). -include_lib("ssl/src/ssl_connection.hrl"). all() -> [{group, 'tlsv1.3'}]. groups() -> [{'tlsv1.3', [], tls_1_3_tests()}]. tls_1_3_tests() -> [key_update_at_client, key_update_at_server, explicit_key_update]. init_per_suite(Config0) -> catch crypto:stop(), try crypto:start() of ok -> ssl_test_lib:clean_start(), case proplists:get_bool(ecdh, proplists:get_value(public_keys, crypto:supports())) of true -> ssl_test_lib:make_ecdsa_cert(Config0); false -> {skip, "Missing EC crypto support"} end catch _:_ -> {skip, "Crypto did not start"} end. end_per_suite(_Config) -> ssl:stop(), application:unload(ssl), application:stop(crypto). init_per_group(GroupName, Config) -> ssl_test_lib:init_per_group(GroupName, Config). end_per_group(GroupName, Config) -> ssl_test_lib:end_per_group(GroupName, Config). init_per_testcase(_TestCase, Config) -> ssl_test_lib:ct_log_supported_protocol_versions(Config), ct:timetrap({seconds, 10}), Config. end_per_testcase(_TestCase, Config) -> Config. key_update_at_client() -> [{doc,"Test option 'key_update_at' between erlang client and erlang server." "Client initiating the update."}]. key_update_at_client(Config) -> key_update_at(Config, client). key_update_at_server() -> [{doc,"Test option 'key_update_at' between erlang client and erlang server." "Server initiating the update."}]. key_update_at_server(Config) -> key_update_at(Config, server). key_update_at(Config, Role) -> 15 bytes Server = ssl_test_lib:start_server(erlang, [{options, [{key_update_at, 14}]}], Config), Port = ssl_test_lib:inet_port(Server), {Client, #sslsocket{pid = [ClientReceiverPid, ClientSenderPid]}} = ssl_test_lib:start_client(erlang, [return_socket, {port, Port}, {options, [{key_update_at, 14}]}], Config), Server ! get_socket, #sslsocket{pid = [ServerReceiverPid, ServerSenderPid]} = receive {Server, {socket, S}} -> S end, Keys0 = get_keys(ClientReceiverPid, ClientSenderPid, ServerReceiverPid, ServerSenderPid), {Sender, Receiver} = case Role of client -> {Client, Server}; server -> {Server, Client} end, ssl_test_lib:send(Sender, Data), Data = ssl_test_lib:check_active_receive(Receiver, Data), TODO check if key has been updated ( needs debug logging of secrets ) ct:sleep(500), Keys1 = get_keys(ClientReceiverPid, ClientSenderPid, ServerReceiverPid, ServerSenderPid), verify_key_update(Keys0, Keys1), 100 bytes ok = ssl_test_lib:send(Sender, BigData), ct:sleep(500), Keys2 = get_keys(ClientReceiverPid, ClientSenderPid, ServerReceiverPid, ServerSenderPid), verify_key_update(Keys1, Keys2), ssl_test_lib:close(Server), ssl_test_lib:close(Client). get_keys(ClientReceiverPid, ClientSenderPid, ServerReceiverPid, ServerSenderPid) -> F = fun(Pid) -> {connection, D} = sys:get_state(Pid), M0 = element(3, D), Cr = maps:get(current_write, M0), {Pid, {maps:get(security_parameters, Cr), maps:get(cipher_state, Cr)}} end, SendersKeys = [F(P) || P <- [ClientSenderPid, ServerSenderPid]], G = fun(Pid) -> {connection, D} = sys:get_state(Pid), #state{connection_states = Cs} = D, Cr = maps:get(current_read, Cs), {Pid, {maps:get(security_parameters,Cr), maps:get(cipher_state, Cr)}} end, ReceiversKeys = [G(P) || P <- [ClientReceiverPid, ServerReceiverPid]], maps:from_list(SendersKeys ++ ReceiversKeys). verify_key_update(Keys0, Keys1) -> V = fun(Pid, CurrentKeys) -> BaseKeys = maps:get(Pid, Keys0), ct:log("Pid = ~p~nBaseKeys = ~p~nCurrentKeys = ~p", [Pid, BaseKeys, CurrentKeys], [esc_chars]), case BaseKeys == CurrentKeys of true -> ct:fail("Keys don't differ for ~w", [Pid]); false -> ok end end, maps:foreach(V, Keys1). explicit_key_update() -> [{doc,"Test ssl:update_key/2 between erlang client and erlang server."}]. explicit_key_update(Config) -> 15 bytes Server = ssl_test_lib:start_server(erlang, [], Config), Port = ssl_test_lib:inet_port(Server), Client = ssl_test_lib:start_client(erlang, [{port, Port}], Config), ssl_test_lib:send_recv_result_active(Client, Server, Data), ssl_test_lib:update_keys(Client, write), ssl_test_lib:update_keys(Client, read_write), ssl_test_lib:send_recv_result_active(Client, Server, Data), ssl_test_lib:update_keys(Server, write), ssl_test_lib:update_keys(Server, read_write), ssl_test_lib:send_recv_result_active(Client, Server, Data), TODO check if key has been updated ( needs debug logging of secrets ) ssl_test_lib:close(Server), ssl_test_lib:close(Client).
d02eefc04afbcfe8791ba276db8d517b37c9fff2269e87a15de54f15b00da8e1
ocaml-ppx/ocamlformat
foo.ml
val a : aaa -> bbb -> ccc -> ddd -> eee -> fff -> ggg
null
https://raw.githubusercontent.com/ocaml-ppx/ocamlformat/5ce32d2aeb1f7ca38b0bbc65d5d77eb64f78484e/test/rpc/big_margin/foo.ml
ocaml
val a : aaa -> bbb -> ccc -> ddd -> eee -> fff -> ggg
586d1b56362b2774f50b5586b7c9f6d33ce0da4f7fc526c66eacd9a4555da4da
mirage/ocaml-xenstore-server
interdomain.mli
* Copyright ( C ) Citrix Systems Inc. * * 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 ; version 2.1 only . with the special * exception on linking described in file LICENSE . * * 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 . * Copyright (C) Citrix Systems Inc. * * 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; version 2.1 only. with the special * exception on linking described in file LICENSE. * * 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. *) open Xenstore include S.SERVER
null
https://raw.githubusercontent.com/mirage/ocaml-xenstore-server/2a8ae397d2f9291107b5d9e9cfc6085fde8c0982/userspace/interdomain.mli
ocaml
* Copyright ( C ) Citrix Systems Inc. * * 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 ; version 2.1 only . with the special * exception on linking described in file LICENSE . * * 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 . * Copyright (C) Citrix Systems Inc. * * 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; version 2.1 only. with the special * exception on linking described in file LICENSE. * * 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. *) open Xenstore include S.SERVER
3a944d431f61eb847f91d735ff233b190bc2c17f100ff7efcb77bc573cc6dce8
whilo/denisovan
core_test.clj
(ns denisovan.core-test (:use [clojure test] [clojure.core.matrix]) (:require [clojure.core.matrix.protocols :refer [norm] :as p] [denisovan.core :as d] [clojure.core.matrix.compliance-tester])) (set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (set-current-implementation :neanderthal) (deftest instance-tests (clojure.core.matrix.compliance-tester/instance-test (array :neanderthal [[1 2 3] [4 5 6]])) (clojure.core.matrix.compliance-tester/instance-test (array :neanderthal [1 2 3 4 5]))) (deftest compliance-test (clojure.core.matrix.compliance-tester/compliance-test (array :neanderthal [1 2]))) (def eps 1e-8) (deftest additional-operations (testing "Operations tested additional to compliance tests." (is (<= (norm (sub (sub 1.0 (matrix [1 2 3])) (matrix [0 -1 -2])) 2) eps)) (is (<= (norm (sub (scale-add! (matrix [1 2]) 3 (matrix [11 17]) 5 0.0) (matrix [58 91])) 2) eps)) (let [m (matrix [[1 2] [3 4]])] (is (<= (norm (sub (mmul (d/svd-inv m) m) (identity-matrix 2)) 2) eps)))))
null
https://raw.githubusercontent.com/whilo/denisovan/fd6eabaec4f3d91f598332a97208e6268fe32196/test/denisovan/core_test.clj
clojure
(ns denisovan.core-test (:use [clojure test] [clojure.core.matrix]) (:require [clojure.core.matrix.protocols :refer [norm] :as p] [denisovan.core :as d] [clojure.core.matrix.compliance-tester])) (set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (set-current-implementation :neanderthal) (deftest instance-tests (clojure.core.matrix.compliance-tester/instance-test (array :neanderthal [[1 2 3] [4 5 6]])) (clojure.core.matrix.compliance-tester/instance-test (array :neanderthal [1 2 3 4 5]))) (deftest compliance-test (clojure.core.matrix.compliance-tester/compliance-test (array :neanderthal [1 2]))) (def eps 1e-8) (deftest additional-operations (testing "Operations tested additional to compliance tests." (is (<= (norm (sub (sub 1.0 (matrix [1 2 3])) (matrix [0 -1 -2])) 2) eps)) (is (<= (norm (sub (scale-add! (matrix [1 2]) 3 (matrix [11 17]) 5 0.0) (matrix [58 91])) 2) eps)) (let [m (matrix [[1 2] [3 4]])] (is (<= (norm (sub (mmul (d/svd-inv m) m) (identity-matrix 2)) 2) eps)))))
dae268d724337069fc938429eb9392e93026b2ae01ca0a06eda2af2a69e5d155
Lysxia/test-monad-laws
Mutants.hs
# LANGUAGE FlexibleInstances # module Test.Monad.Trans.Mutants where import Control.Monad.Trans import Control.Monad.Trans.Maybe import Data.Functor (($>)) import Test.Mutants -- | An general way to get 'MonadTrans' wrong is to run the base -- computation twice. data LiftTwice instance {-# OVERLAPPING #-} MonadTrans t => MonadTrans (Mutant LiftTwice t) where lift m = lift (m >> m) -- Other kinds of mistakes are difficult to make, by parametricity. State : -- lift :: m a -> (s -> m (a, s)) -- Except: -- lift :: m a -> m (Either e a) -- Writer: -- lift :: m a -> m (w, a) -- Reader: -- lift :: m a -> (r -> m a) -- Maybe: -- lift :: m a -> m (Maybe a) -- | Forget the computation. data LiftMaybeNothing instance {-# OVERLAPPING #-} MonadTrans (Mutant LiftMaybeNothing MaybeT) where lift _ = Mutant . MaybeT $ return Nothing -- | Run the computation but forget the result. data LiftMaybeDiscard instance {-# OVERLAPPING #-} MonadTrans (Mutant LiftMaybeDiscard MaybeT) where lift m = Mutant . MaybeT $ m $> Nothing
null
https://raw.githubusercontent.com/Lysxia/test-monad-laws/1cb9e116769771cb49fbd1614f50b05e120a2709/src/Test/Monad/Trans/Mutants.hs
haskell
| An general way to get 'MonadTrans' wrong is to run the base computation twice. # OVERLAPPING # Other kinds of mistakes are difficult to make, by parametricity. lift :: m a -> (s -> m (a, s)) Except: lift :: m a -> m (Either e a) Writer: lift :: m a -> m (w, a) Reader: lift :: m a -> (r -> m a) Maybe: lift :: m a -> m (Maybe a) | Forget the computation. # OVERLAPPING # | Run the computation but forget the result. # OVERLAPPING #
# LANGUAGE FlexibleInstances # module Test.Monad.Trans.Mutants where import Control.Monad.Trans import Control.Monad.Trans.Maybe import Data.Functor (($>)) import Test.Mutants data LiftTwice MonadTrans t => MonadTrans (Mutant LiftTwice t) where lift m = lift (m >> m) State : data LiftMaybeNothing MonadTrans (Mutant LiftMaybeNothing MaybeT) where lift _ = Mutant . MaybeT $ return Nothing data LiftMaybeDiscard MonadTrans (Mutant LiftMaybeDiscard MaybeT) where lift m = Mutant . MaybeT $ m $> Nothing
f6a26f163945754782f8d3619e763aa7c287410e58e493a5c78ab0af8924e4f2
tsloughter/rebar3_tests
db_manager.erl
-module(db_manager). -behaviour(gen_server). %% API functions -export([start_link/1 ,get_metric_type/1 ,get_metric_fd/1 ,get_metric_fd/2 ,get_metric_maps/0 ,load_metric_map/1 ,pre_process_metric/1 ]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). %-record(state, {}). %%%=================================================================== %%% API functions %%%=================================================================== get_metric_type(Mn) -> [{_, Val}] = fetch_fd({Mn, any}), {metric_type, Mt} = lists:keyfind(metric_type, 1, Val), {ok, Mt}. get_metric_fd({Mn , Cn , Mt } ) - > { ok , CacheFd , LiveMetricFd } . get_metric_fd(Mid) -> get_metric_fd(Mid, live). %% metric storing seconds is assumed to be live get_metric_fd(Mid, sec) -> get_metric_fd(Mid, live); get_metric_fd({Mn, Cn, Mt}, Granularity) -> {ok, MapList} = get_metric_maps({Mn, Cn, Mt}, Granularity), case graph_utils:get_args(MapList, [cache_fd, {db_fd, Granularity}]) of {error_params_missing, _} -> io : format("~n metric do n't exits calling gen_server ~p ~p ~ n " , [ Granularity , MapList ] ) , gen_server:call(?MODULE, {get_metric_fd, {Mn, Cn}, Granularity}); {ok, [CacheFd, DbFd]} -> {ok, CacheFd, DbFd} end. %% return all metric maps get_metric_maps() -> MetricData = lists:map(fun([{K,V}]) -> {K,V} end, ets:match(?MODULE, '$1')), {ok, MetricData}. get_metric_maps({Mn, Cn, Mt}, Granularity) -> case ets : lookup(?MODULE , { Mn , Cn } ) of TODO send udpates to graph_db_server reg each incomming cilent case fetch_fd({Mn, Cn}) of [] when Granularity =:= live -> io : do n't exits calling gen_server ~p ~ n " , [ { Cn , self ( ) } ] ) , gen_server:call(?MODULE, {get_metric_fd, {Mn, Cn, Mt}, live}), ets : lookup(?MODULE , { Mn , Cn } ) , {ok, Value}; %% if the Granularity req was not for live it means that metric should %% have been create by manager earlier but since it is not in its state %% so it will throw error [] -> {false, error}; [{_Key, Value}] -> {ok, Value} end. load_metric_map({Mn, Cn}) -> case fetch_fd({Mn, Cn}) of [] -> {false, error_no_metric_map}; [{_Key, Value}] -> {ok, Value} end. %%-------------------------------------------------------------------- %% @doc %% Starts the server %% ( ) - > { ok , Pid } | ignore | { error , Error } %% @end %%-------------------------------------------------------------------- start_link(Args) -> gen_server:start_link({local, ?MODULE}, ?MODULE, [Args], []). %%%=================================================================== %%% gen_server callbacks %%%=================================================================== %%-------------------------------------------------------------------- @private %% @doc %% Initializes the server %% ) - > { ok , State } | { ok , State , Timeout } | %% ignore | %% {stop, Reason} %% @end %%-------------------------------------------------------------------- init([Args]) -> process_flag(trap_exit, true), {ok, Dir} = application:get_env(graph_db, storage_dir), {ok, [DbMod, CacheMod]} = graph_utils:get_args(Args, [db_mod, cache_mod]), %% db_manager stores metric meta data in ets table and saves it to disk %% for persistance and to handle crash. reload_state(DbMod, CacheMod, Dir), {ok, StateSaveTimeout} = application:get_env(graph_db, db_manager_state_dump_timeout), timer:send_interval(StateSaveTimeout, {save_state}), {ok, #{db => DbMod ,cache => CacheMod ,storage_dir => Dir}}. %% reload db_manager state from disk reload_state(DbMod, CacheMod, Dir) -> case ets:info(?MODULE) of undefined -> {ok, success} = load_prev_state(DbMod, CacheMod, Dir); _ -> {ok, success} end. %% load db_manager ets dump from disk load_prev_state(DbMod, CacheMod, Dir) -> Path = erlang:binary_to_list(<<Dir/binary, "db_manager.dat">>), Pid = graph_db_sup:ets_sup_pid(), ets:new(?MODULE, [set, public, named_table ,{heir, Pid, none} ,{write_concurrency, false} ,{read_concurrency, true}]), case file:open(Path, [read]) of {error,enoent} -> {ok, success}; {ok, Fd} -> init_db_handlers(Fd, {DbMod, CacheMod, Dir}) end. %% initalize metric cache from db_manager state init_db_handlers(Fd, {DbMod, CacheMod, Dir}) -> case file:read_line(Fd) of {ok, Data} -> {ok, [Mn, Mt]} = extract_args(Data), [ RMn , RMt ] = string : tokens(string : strip(Data , both , ) , " , " ) , %% Mn = erlang:list_to_binary(string:strip(RMn)), %% Mt = erlang:list_to_binary(string:strip(RMt)), io:format("starting metric ~p ~p~n", [Mn, Mt]), Cn = <<"metric">>, MetricName = db_utils:to_metric_name({Mn, Cn}), bootstrap_metric({Mn, Cn, Mt}, MetricName, {DbMod, open_db, live}, {CacheMod, open_db}, Dir), init_db_handlers(Fd, {DbMod, CacheMod, Dir}); eof -> {ok, success} end. %% ets:foldl( fun({{Mn , Cn } , { MetricName , Mt } } , Acc ) - > bootstrap_metric({Mn , Cn , Mt } , MetricName , { DbMod , , live } , { CacheMod , open_db } , ) , Acc %% end, 0, ?MODULE). %%-------------------------------------------------------------------- @private %% @doc %% Handling call messages %% , From , State ) - > %% {reply, Reply, State} | { reply , Reply , State , Timeout } | { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, Reply, State} | %% {stop, Reason, State} %% @end %%-------------------------------------------------------------------- %% metric maps is of the format: [{{Mid, Cn}, MetricName}, ...] %% creates a cache db if it doesn't exist already else return the state of the %% cache metric. handle_call({get_metric_fd, {Mid, Cn, Mt}, live}, From, State) -> #{db := DbMod ,cache := CacheMod ,storage_dir := Dir} = State, MetricName = db_utils:to_metric_name({Mid, Cn}), case ets : lookup(?MODULE , { Mid , Cn } ) of case fetch_fd({Mid, Cn}) of [] -> io:format("[+] bootstraping metric: ~p ~p~n", [MetricName, From]), bootstrap_metric({Mid, Cn, Mt}, MetricName, {DbMod, init_db, live}, {CacheMod, open_db}, Dir), ets : lookup(?MODULE , { Mid , Cn } ) , {ok, [CacheFd, DbFd]} = graph_utils:get_args(Metric, [cache_fd, {db_fd, live}]), {reply, {ok, CacheFd, DbFd}, State}; [{_, MetricData}] -> {ok, [CacheFd, DbFd]} = graph_utils:get_args(MetricData, [cache_fd, {db_fd, live}]), {reply, {ok, CacheFd, DbFd}, State} end; handle_call({get_metric_fd, {Mn, Cn}, Granularity}, _From, State) -> #{db := DbMod ,storage_dir := Dir} = State, BaseName = db_utils:to_metric_name({Mn, Cn}), MetricName = db_utils:get_metric_name(Granularity, BaseName), %% we expect that the live db are up and running so we will already have %% the {Mid,Cn} entry in the state. ets : lookup(?MODULE , { Mn , Cn } ) , {ok, [CacheFd]} = graph_utils:get_args(MetricData, [cache_fd]), case graph_utils:get_args(MetricData, [{db_fd, Granularity}]) of {error_params_missing, _Error} -> {ok, DbFd} = create_db(DbMod, init_db, {MetricName, Dir}), MetricDataN = lists:keystore({db_fd, Granularity}, 1, MetricData, {{db_fd,Granularity}, DbFd}), store_fd({Key, MetricDataN}), ets : insert(?MODULE , { { Mn , Cn } , MetricDataN } ) , {reply, {ok, CacheFd, DbFd}, State}; {ok, [DbFd]} -> {reply, {ok, CacheFd, DbFd}, State} end; handle_call({get_metric_maps } , _ From , State ) - > MapList = ets : , ' $ 1 ' ) , { reply , { ok , MapList } , State } ; handle_call(_Request, _From, State) -> Reply = ok, {reply, Reply, State}. %%-------------------------------------------------------------------- @private %% @doc %% Handling cast messages %% @spec handle_cast(Msg , State ) - > { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, State} %% @end %%-------------------------------------------------------------------- handle_cast(_Msg, State) -> {noreply, State}. %%-------------------------------------------------------------------- @private %% @doc %% Handling all non call/cast messages %% , State ) - > { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, State} %% @end %%-------------------------------------------------------------------- %% dump metric cache to disk handle_info({cache_to_disk, MetricId}, State) -> db_worker:dump_data(MetricId), {noreply, State}; handle_info({save_state}, State) -> io:format("~n[+] periodically saving db_manager state~n", []), dump_state(), {noreply, State}; handle_info(_Info, State) -> {noreply, State}. %%-------------------------------------------------------------------- @private %% @doc %% This function is called by a gen_server when it is about to %% terminate. It should be the opposite of Module:init/1 and do any %% necessary cleaning up. When it returns, the gen_server terminates with . The return value is ignored . %% , State ) - > void ( ) %% @end %%-------------------------------------------------------------------- terminate(Reason, #{db := DbMod, cache := CacheMod}) -> %% write state to disk while crashing or terminating io:format("~n[+] Saving db_manager state ... reason ~p~n", [Reason]), case Reason of shutdown -> Metrics = ets:match(?MODULE, '$1'), CleanMetric = fun([{_Key, Value}]) -> {ok, [Name ,CacheFd ,DbFd ,Tref]} = graph_utils:get_args(Value, [name ,cache_fd ,{db_fd, live} ,tref]), %% store cache before shutting down timer:cancel(Tref), {ok, Data} = CacheMod:read_all(CacheFd), [DbMod:insert_many(DbFd, Client, Points) || {Client, Points} <- Data ], CacheMod:close_db(CacheFd), %% if Reason =:= shutdown -> graph_db_sup:ets_sup_stop_child(Name); true -> ok end, graph_db_sup:ets_sup_stop_child(Name), [DbMod:close_db(Fd) || {{db_fd, _Type}, Fd} <- Value] ets : insert(?MODULE , { Key , { Name , } } ) end, graph_utils:run_threads(8, Metrics, CleanMetric); _ -> ok end, %% write to file dump_state(), if Reason =:= shutdown -> graph_db_sup:stop_ets_sup(); true -> ok end, ok. dump_state() -> %% write to file {ok, Dir} = application:get_env(graph_db, storage_dir), FilePath = erlang:binary_to_list(<<Dir/binary, "db_manager.dat">>), {ok, FFd} = file:open(FilePath, [write]), ets:foldl( fun({{Mn, _Cn}, Value}, _Acc) -> {ok, [Mt]} = graph_utils:get_args(Value, [metric_type]), file:write(FFd, erlang:binary_to_list( <<Mn/binary, ", ", Mt/binary, "\n">>)) end, 0, ?MODULE), file:close(FFd). %%-------------------------------------------------------------------- @private %% @doc %% Convert process state when code is changed %% , State , Extra ) - > { ok , NewState } %% @end %%-------------------------------------------------------------------- code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== Internal functions %%%=================================================================== %% initalize metric ram and db instances bootstrap_metric({Mid, Cn, Mt}, MetricName, {DbMod, DFun, Type}, {CacheMod, CFun}, Dir) -> %% create ets table as direct children of graph_db_sup {ok, CacheFd} = get_cache_fd(Mid, {CacheMod, CFun, Dir}), {ok, DbFd} = create_db(DbMod, DFun, {MetricName, Dir}), {ok, Timeout} = application:get_env(graph_db, cache_to_disk_timeout), {ok, Tref} = timer:send_interval(Timeout, {cache_to_disk, {Mid, Cn, Mt}}), MetricState = {{Mid, Cn}, [{{db_fd, Type}, DbFd} ,{name,MetricName} ,{metric_type, Mt} ,{tref, Tref} ,{cache_fd, CacheFd}]}, ets:insert(?MODULE, MetricState). get_cache_fd(Mid, {CacheMod, CFun, Dir}) -> case ets:match(?MODULE, {{Mid, '_'}, '$1'}, 1) of '$end_of_table' -> graph_db_sup:init_metric_cache(erlang:binary_to_atom(Mid, utf8), {CacheMod, CFun, Dir}); {[[Val]], _} -> {cache_fd, CacheFd} = lists:keyfind(cache_fd, 1, Val), {ok, CacheFd} end. create_db(Mod, Fun, {MetricName, Dir}) -> erlang:apply(Mod, Fun, [ MetricName, [{storage_dir, Dir}] ]). fetch_fd({Mn, _}) -> case ets:match(?MODULE, {{Mn, '$1'}, '$2'}) of [] -> []; [[Cn, Val]] -> [{{Mn, Cn}, Val}] end. store_fd({Key, Val}) -> ets:insert(?MODULE, {Key, Val}). %% pre_process_metric/1 : input is a comma seperated file where each line %% contains metrics name (eg active_users_online) and the metric type. Eg. %% === FILE STARTS === %% %% active_users_online, p %% cpu_usage, p concurrent_connections , p %% %% === FILE ENDS === %% %% It is advisable to NOT have any space in the metric name. %% the file name should be absolute path pre_process_metric(FilePath) -> {ok, Fd} = file:open(FilePath, [read]), read_file(Fd), file:close(Fd). read_file(Fd) -> case file:read_line(Fd) of {ok, Data} -> [ RMn , RMt ] = string : tokens(string : strip(Data , both , ) , " , " ) , %% Mn = erlang:list_to_binary(string:strip(RMn)), %% Mt = erlang:list_to_binary(string:strip(RMt)), {ok, [Mn, Mt]} = extract_args(Data), io:format("starting metric ~p ~p~n", [Mn, Mt]), db_manager:get_metric_fd({Mn, <<"metric">>, Mt}), read_file(Fd); eof -> ok end. extract_args(Data) -> [RMn, RMt] = string:tokens(string:strip(Data, both, $\n ), ","), Mn = erlang:list_to_binary(string:strip(RMn)), Mt = erlang:list_to_binary(string:strip(RMt)), {ok, [Mn, Mt]}. %% testing %% create_metrics(N) -> %% lists:map( %% fun(I) -> %% Cn = list_to_binary("www.server" ++ integer_to_list(I) ++ ".com"), %% db_manager:get_metric_fd({<<"cpu_usage">>, Cn, <<"g">>}) end , lists : seq(1 , N ) ) .
null
https://raw.githubusercontent.com/tsloughter/rebar3_tests/090bfef7d3a4790bb6b16e4c38df6e4c0460b4b2/sub_app_eleveldb/apps/graph_db/src/db_manager.erl
erlang
API functions gen_server callbacks -record(state, {}). =================================================================== API functions =================================================================== metric storing seconds is assumed to be live return all metric maps if the Granularity req was not for live it means that metric should have been create by manager earlier but since it is not in its state so it will throw error -------------------------------------------------------------------- @doc Starts the server @end -------------------------------------------------------------------- =================================================================== gen_server callbacks =================================================================== -------------------------------------------------------------------- @doc Initializes the server ignore | {stop, Reason} @end -------------------------------------------------------------------- db_manager stores metric meta data in ets table and saves it to disk for persistance and to handle crash. reload db_manager state from disk load db_manager ets dump from disk initalize metric cache from db_manager state Mn = erlang:list_to_binary(string:strip(RMn)), Mt = erlang:list_to_binary(string:strip(RMt)), ets:foldl( end, 0, ?MODULE). -------------------------------------------------------------------- @doc Handling call messages {reply, Reply, State} | {stop, Reason, Reply, State} | {stop, Reason, State} @end -------------------------------------------------------------------- metric maps is of the format: [{{Mid, Cn}, MetricName}, ...] creates a cache db if it doesn't exist already else return the state of the cache metric. we expect that the live db are up and running so we will already have the {Mid,Cn} entry in the state. -------------------------------------------------------------------- @doc Handling cast messages {stop, Reason, State} @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Handling all non call/cast messages {stop, Reason, State} @end -------------------------------------------------------------------- dump metric cache to disk -------------------------------------------------------------------- @doc This function is called by a gen_server when it is about to terminate. It should be the opposite of Module:init/1 and do any necessary cleaning up. When it returns, the gen_server terminates @end -------------------------------------------------------------------- write state to disk while crashing or terminating store cache before shutting down if Reason =:= shutdown -> graph_db_sup:ets_sup_stop_child(Name); true -> ok end, write to file write to file -------------------------------------------------------------------- @doc Convert process state when code is changed @end -------------------------------------------------------------------- =================================================================== =================================================================== initalize metric ram and db instances create ets table as direct children of graph_db_sup pre_process_metric/1 : input is a comma seperated file where each line contains metrics name (eg active_users_online) and the metric type. Eg. === FILE STARTS === active_users_online, p cpu_usage, p === FILE ENDS === It is advisable to NOT have any space in the metric name. the file name should be absolute path Mn = erlang:list_to_binary(string:strip(RMn)), Mt = erlang:list_to_binary(string:strip(RMt)), testing create_metrics(N) -> lists:map( fun(I) -> Cn = list_to_binary("www.server" ++ integer_to_list(I) ++ ".com"), db_manager:get_metric_fd({<<"cpu_usage">>, Cn, <<"g">>})
-module(db_manager). -behaviour(gen_server). -export([start_link/1 ,get_metric_type/1 ,get_metric_fd/1 ,get_metric_fd/2 ,get_metric_maps/0 ,load_metric_map/1 ,pre_process_metric/1 ]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). get_metric_type(Mn) -> [{_, Val}] = fetch_fd({Mn, any}), {metric_type, Mt} = lists:keyfind(metric_type, 1, Val), {ok, Mt}. get_metric_fd({Mn , Cn , Mt } ) - > { ok , CacheFd , LiveMetricFd } . get_metric_fd(Mid) -> get_metric_fd(Mid, live). get_metric_fd(Mid, sec) -> get_metric_fd(Mid, live); get_metric_fd({Mn, Cn, Mt}, Granularity) -> {ok, MapList} = get_metric_maps({Mn, Cn, Mt}, Granularity), case graph_utils:get_args(MapList, [cache_fd, {db_fd, Granularity}]) of {error_params_missing, _} -> io : format("~n metric do n't exits calling gen_server ~p ~p ~ n " , [ Granularity , MapList ] ) , gen_server:call(?MODULE, {get_metric_fd, {Mn, Cn}, Granularity}); {ok, [CacheFd, DbFd]} -> {ok, CacheFd, DbFd} end. get_metric_maps() -> MetricData = lists:map(fun([{K,V}]) -> {K,V} end, ets:match(?MODULE, '$1')), {ok, MetricData}. get_metric_maps({Mn, Cn, Mt}, Granularity) -> case ets : lookup(?MODULE , { Mn , Cn } ) of TODO send udpates to graph_db_server reg each incomming cilent case fetch_fd({Mn, Cn}) of [] when Granularity =:= live -> io : do n't exits calling gen_server ~p ~ n " , [ { Cn , self ( ) } ] ) , gen_server:call(?MODULE, {get_metric_fd, {Mn, Cn, Mt}, live}), ets : lookup(?MODULE , { Mn , Cn } ) , {ok, Value}; [] -> {false, error}; [{_Key, Value}] -> {ok, Value} end. load_metric_map({Mn, Cn}) -> case fetch_fd({Mn, Cn}) of [] -> {false, error_no_metric_map}; [{_Key, Value}] -> {ok, Value} end. ( ) - > { ok , Pid } | ignore | { error , Error } start_link(Args) -> gen_server:start_link({local, ?MODULE}, ?MODULE, [Args], []). @private ) - > { ok , State } | { ok , State , Timeout } | init([Args]) -> process_flag(trap_exit, true), {ok, Dir} = application:get_env(graph_db, storage_dir), {ok, [DbMod, CacheMod]} = graph_utils:get_args(Args, [db_mod, cache_mod]), reload_state(DbMod, CacheMod, Dir), {ok, StateSaveTimeout} = application:get_env(graph_db, db_manager_state_dump_timeout), timer:send_interval(StateSaveTimeout, {save_state}), {ok, #{db => DbMod ,cache => CacheMod ,storage_dir => Dir}}. reload_state(DbMod, CacheMod, Dir) -> case ets:info(?MODULE) of undefined -> {ok, success} = load_prev_state(DbMod, CacheMod, Dir); _ -> {ok, success} end. load_prev_state(DbMod, CacheMod, Dir) -> Path = erlang:binary_to_list(<<Dir/binary, "db_manager.dat">>), Pid = graph_db_sup:ets_sup_pid(), ets:new(?MODULE, [set, public, named_table ,{heir, Pid, none} ,{write_concurrency, false} ,{read_concurrency, true}]), case file:open(Path, [read]) of {error,enoent} -> {ok, success}; {ok, Fd} -> init_db_handlers(Fd, {DbMod, CacheMod, Dir}) end. init_db_handlers(Fd, {DbMod, CacheMod, Dir}) -> case file:read_line(Fd) of {ok, Data} -> {ok, [Mn, Mt]} = extract_args(Data), [ RMn , RMt ] = string : tokens(string : strip(Data , both , ) , " , " ) , io:format("starting metric ~p ~p~n", [Mn, Mt]), Cn = <<"metric">>, MetricName = db_utils:to_metric_name({Mn, Cn}), bootstrap_metric({Mn, Cn, Mt}, MetricName, {DbMod, open_db, live}, {CacheMod, open_db}, Dir), init_db_handlers(Fd, {DbMod, CacheMod, Dir}); eof -> {ok, success} end. fun({{Mn , Cn } , { MetricName , Mt } } , Acc ) - > bootstrap_metric({Mn , Cn , Mt } , MetricName , { DbMod , , live } , { CacheMod , open_db } , ) , Acc @private , From , State ) - > { reply , Reply , State , Timeout } | { noreply , State } | { noreply , State , Timeout } | handle_call({get_metric_fd, {Mid, Cn, Mt}, live}, From, State) -> #{db := DbMod ,cache := CacheMod ,storage_dir := Dir} = State, MetricName = db_utils:to_metric_name({Mid, Cn}), case ets : lookup(?MODULE , { Mid , Cn } ) of case fetch_fd({Mid, Cn}) of [] -> io:format("[+] bootstraping metric: ~p ~p~n", [MetricName, From]), bootstrap_metric({Mid, Cn, Mt}, MetricName, {DbMod, init_db, live}, {CacheMod, open_db}, Dir), ets : lookup(?MODULE , { Mid , Cn } ) , {ok, [CacheFd, DbFd]} = graph_utils:get_args(Metric, [cache_fd, {db_fd, live}]), {reply, {ok, CacheFd, DbFd}, State}; [{_, MetricData}] -> {ok, [CacheFd, DbFd]} = graph_utils:get_args(MetricData, [cache_fd, {db_fd, live}]), {reply, {ok, CacheFd, DbFd}, State} end; handle_call({get_metric_fd, {Mn, Cn}, Granularity}, _From, State) -> #{db := DbMod ,storage_dir := Dir} = State, BaseName = db_utils:to_metric_name({Mn, Cn}), MetricName = db_utils:get_metric_name(Granularity, BaseName), ets : lookup(?MODULE , { Mn , Cn } ) , {ok, [CacheFd]} = graph_utils:get_args(MetricData, [cache_fd]), case graph_utils:get_args(MetricData, [{db_fd, Granularity}]) of {error_params_missing, _Error} -> {ok, DbFd} = create_db(DbMod, init_db, {MetricName, Dir}), MetricDataN = lists:keystore({db_fd, Granularity}, 1, MetricData, {{db_fd,Granularity}, DbFd}), store_fd({Key, MetricDataN}), ets : insert(?MODULE , { { Mn , Cn } , MetricDataN } ) , {reply, {ok, CacheFd, DbFd}, State}; {ok, [DbFd]} -> {reply, {ok, CacheFd, DbFd}, State} end; handle_call({get_metric_maps } , _ From , State ) - > MapList = ets : , ' $ 1 ' ) , { reply , { ok , MapList } , State } ; handle_call(_Request, _From, State) -> Reply = ok, {reply, Reply, State}. @private @spec handle_cast(Msg , State ) - > { noreply , State } | { noreply , State , Timeout } | handle_cast(_Msg, State) -> {noreply, State}. @private , State ) - > { noreply , State } | { noreply , State , Timeout } | handle_info({cache_to_disk, MetricId}, State) -> db_worker:dump_data(MetricId), {noreply, State}; handle_info({save_state}, State) -> io:format("~n[+] periodically saving db_manager state~n", []), dump_state(), {noreply, State}; handle_info(_Info, State) -> {noreply, State}. @private with . The return value is ignored . , State ) - > void ( ) terminate(Reason, #{db := DbMod, cache := CacheMod}) -> io:format("~n[+] Saving db_manager state ... reason ~p~n", [Reason]), case Reason of shutdown -> Metrics = ets:match(?MODULE, '$1'), CleanMetric = fun([{_Key, Value}]) -> {ok, [Name ,CacheFd ,DbFd ,Tref]} = graph_utils:get_args(Value, [name ,cache_fd ,{db_fd, live} ,tref]), timer:cancel(Tref), {ok, Data} = CacheMod:read_all(CacheFd), [DbMod:insert_many(DbFd, Client, Points) || {Client, Points} <- Data ], CacheMod:close_db(CacheFd), graph_db_sup:ets_sup_stop_child(Name), [DbMod:close_db(Fd) || {{db_fd, _Type}, Fd} <- Value] ets : insert(?MODULE , { Key , { Name , } } ) end, graph_utils:run_threads(8, Metrics, CleanMetric); _ -> ok end, dump_state(), if Reason =:= shutdown -> graph_db_sup:stop_ets_sup(); true -> ok end, ok. dump_state() -> {ok, Dir} = application:get_env(graph_db, storage_dir), FilePath = erlang:binary_to_list(<<Dir/binary, "db_manager.dat">>), {ok, FFd} = file:open(FilePath, [write]), ets:foldl( fun({{Mn, _Cn}, Value}, _Acc) -> {ok, [Mt]} = graph_utils:get_args(Value, [metric_type]), file:write(FFd, erlang:binary_to_list( <<Mn/binary, ", ", Mt/binary, "\n">>)) end, 0, ?MODULE), file:close(FFd). @private , State , Extra ) - > { ok , NewState } code_change(_OldVsn, State, _Extra) -> {ok, State}. Internal functions bootstrap_metric({Mid, Cn, Mt}, MetricName, {DbMod, DFun, Type}, {CacheMod, CFun}, Dir) -> {ok, CacheFd} = get_cache_fd(Mid, {CacheMod, CFun, Dir}), {ok, DbFd} = create_db(DbMod, DFun, {MetricName, Dir}), {ok, Timeout} = application:get_env(graph_db, cache_to_disk_timeout), {ok, Tref} = timer:send_interval(Timeout, {cache_to_disk, {Mid, Cn, Mt}}), MetricState = {{Mid, Cn}, [{{db_fd, Type}, DbFd} ,{name,MetricName} ,{metric_type, Mt} ,{tref, Tref} ,{cache_fd, CacheFd}]}, ets:insert(?MODULE, MetricState). get_cache_fd(Mid, {CacheMod, CFun, Dir}) -> case ets:match(?MODULE, {{Mid, '_'}, '$1'}, 1) of '$end_of_table' -> graph_db_sup:init_metric_cache(erlang:binary_to_atom(Mid, utf8), {CacheMod, CFun, Dir}); {[[Val]], _} -> {cache_fd, CacheFd} = lists:keyfind(cache_fd, 1, Val), {ok, CacheFd} end. create_db(Mod, Fun, {MetricName, Dir}) -> erlang:apply(Mod, Fun, [ MetricName, [{storage_dir, Dir}] ]). fetch_fd({Mn, _}) -> case ets:match(?MODULE, {{Mn, '$1'}, '$2'}) of [] -> []; [[Cn, Val]] -> [{{Mn, Cn}, Val}] end. store_fd({Key, Val}) -> ets:insert(?MODULE, {Key, Val}). concurrent_connections , p pre_process_metric(FilePath) -> {ok, Fd} = file:open(FilePath, [read]), read_file(Fd), file:close(Fd). read_file(Fd) -> case file:read_line(Fd) of {ok, Data} -> [ RMn , RMt ] = string : tokens(string : strip(Data , both , ) , " , " ) , {ok, [Mn, Mt]} = extract_args(Data), io:format("starting metric ~p ~p~n", [Mn, Mt]), db_manager:get_metric_fd({Mn, <<"metric">>, Mt}), read_file(Fd); eof -> ok end. extract_args(Data) -> [RMn, RMt] = string:tokens(string:strip(Data, both, $\n ), ","), Mn = erlang:list_to_binary(string:strip(RMn)), Mt = erlang:list_to_binary(string:strip(RMt)), {ok, [Mn, Mt]}. end , lists : seq(1 , N ) ) .
0e81b47686c75e17c88ec6da0ae26e4c688b0c64afa3caae03b34dd8f397711b
evertedsphere/silica
Internal.hs
# LANGUAGE CPP # ----------------------------------------------------------------------------- -- | -- Module : Silica.Internal Copyright : ( C ) 2012 - 16 -- License : BSD-style (see the file LICENSE) Maintainer : < > -- Stability : experimental -- Portability : Rank2Types -- -- These are some of the explicit 'Functor' instances that leak into the type signatures of You should n't need to import this -- module directly for most use-cases. -- ---------------------------------------------------------------------------- module Silica.Internal ( module Silica.Internal.Bazaar , module Silica.Internal.Context , module Silica.Internal.Fold , module Silica.Internal.Getter , module Silica.Internal.Indexed , module Silica.Internal.Iso , module Silica.Internal.Level , module Silica.Internal.Magma , module Silica.Internal.Prism , module Silica.Internal.Review , module Silica.Internal.Setter , module Silica.Internal.Zoom ) where import Silica.Internal.Bazaar import Silica.Internal.Context import Silica.Internal.Fold import Silica.Internal.Getter import Silica.Internal.Indexed import Silica.Internal.Instances () import Silica.Internal.Iso import Silica.Internal.Level import Silica.Internal.Magma import Silica.Internal.Prism import Silica.Internal.Review import Silica.Internal.Setter import Silica.Internal.Zoom #ifdef HLINT {-# ANN module "HLint: ignore Use import/export shortcut" #-} #endif
null
https://raw.githubusercontent.com/evertedsphere/silica/346006f7b58142c6479395e93338134f541034cc/src/Silica/Internal.hs
haskell
--------------------------------------------------------------------------- | Module : Silica.Internal License : BSD-style (see the file LICENSE) Stability : experimental Portability : Rank2Types These are some of the explicit 'Functor' instances that leak into the module directly for most use-cases. -------------------------------------------------------------------------- # ANN module "HLint: ignore Use import/export shortcut" #
# LANGUAGE CPP # Copyright : ( C ) 2012 - 16 Maintainer : < > type signatures of You should n't need to import this module Silica.Internal ( module Silica.Internal.Bazaar , module Silica.Internal.Context , module Silica.Internal.Fold , module Silica.Internal.Getter , module Silica.Internal.Indexed , module Silica.Internal.Iso , module Silica.Internal.Level , module Silica.Internal.Magma , module Silica.Internal.Prism , module Silica.Internal.Review , module Silica.Internal.Setter , module Silica.Internal.Zoom ) where import Silica.Internal.Bazaar import Silica.Internal.Context import Silica.Internal.Fold import Silica.Internal.Getter import Silica.Internal.Indexed import Silica.Internal.Instances () import Silica.Internal.Iso import Silica.Internal.Level import Silica.Internal.Magma import Silica.Internal.Prism import Silica.Internal.Review import Silica.Internal.Setter import Silica.Internal.Zoom #ifdef HLINT #endif
30fe9077a78c719512f18af43fdf76320f610305effcce781bc365516865fab2
MarcoPolo/iso-country-codes
project.clj
(defproject iso-country-codes "0.1.0-SNAPSHOT" :description "FIXME: write description" :url "" :license {:name "Eclipse Public License" :url "-v10.html"} :dependencies [[org.clojure/clojure "1.4.0"] [org.clojure/data.json "0.2.1"]])
null
https://raw.githubusercontent.com/MarcoPolo/iso-country-codes/489fd3ad50e175714955e567917c07ceea7907df/project.clj
clojure
(defproject iso-country-codes "0.1.0-SNAPSHOT" :description "FIXME: write description" :url "" :license {:name "Eclipse Public License" :url "-v10.html"} :dependencies [[org.clojure/clojure "1.4.0"] [org.clojure/data.json "0.2.1"]])
b9f3b25fc1b8e33b5f9e72c2d4d7de8716ecb2ad965cec34ef26a226d646688c
logseq/logseq
namespaces.cljc
(ns ^:no-doc frontend.namespaces #?(:cljs (:require-macros [frontend.namespaces]))) ;; copy from -commons/potemkin/issues/31#issuecomment-110689951 (defmacro import-def "import a single fn or var (import-def a b) => (def b a/b) " [from-ns def-name] (let [from-sym# (symbol (str from-ns) (str def-name))] `(def ~def-name ~from-sym#))) (defmacro import-vars "import multiple defs from multiple namespaces works for vars and fns. not macros. (same syntax as potemkin.namespaces/import-vars) (import-vars [m.n.ns1 a b] [x.y.ns2 d e f]) => (def a m.n.ns1/a) (def b m.n.ns1/b) ... (def d m.n.ns2/d) ... etc " [& imports] (let [expanded-imports (for [[from-ns & defs] imports d defs] `(import-def ~from-ns ~d))] `(do ~@expanded-imports))) ;; FIXME: #_(defmacro import-ns "import all the public defs from multiple namespaces works for vars and fns. not macros. (import-ns m.n.ns1 x.y.ns2) => (def a m.n.ns1/a) (def b m.n.ns1/b) ... (def d m.n.ns2/d) ... etc " [& namespaces] (let [expanded-imports (for [from-ns namespaces d ((ns-resolve 'cljs.analyzer.api 'ns-publics) from-ns)] `(import-def ~from-ns ~d))] `(do ~@expanded-imports)))
null
https://raw.githubusercontent.com/logseq/logseq/9c7b4ea2016fb28b16ee42a7136c73dd52d8ce4b/src/main/frontend/namespaces.cljc
clojure
copy from -commons/potemkin/issues/31#issuecomment-110689951 FIXME:
(ns ^:no-doc frontend.namespaces #?(:cljs (:require-macros [frontend.namespaces]))) (defmacro import-def "import a single fn or var (import-def a b) => (def b a/b) " [from-ns def-name] (let [from-sym# (symbol (str from-ns) (str def-name))] `(def ~def-name ~from-sym#))) (defmacro import-vars "import multiple defs from multiple namespaces works for vars and fns. not macros. (same syntax as potemkin.namespaces/import-vars) (import-vars [m.n.ns1 a b] [x.y.ns2 d e f]) => (def a m.n.ns1/a) (def b m.n.ns1/b) ... (def d m.n.ns2/d) ... etc " [& imports] (let [expanded-imports (for [[from-ns & defs] imports d defs] `(import-def ~from-ns ~d))] `(do ~@expanded-imports))) #_(defmacro import-ns "import all the public defs from multiple namespaces works for vars and fns. not macros. (import-ns m.n.ns1 x.y.ns2) => (def a m.n.ns1/a) (def b m.n.ns1/b) ... (def d m.n.ns2/d) ... etc " [& namespaces] (let [expanded-imports (for [from-ns namespaces d ((ns-resolve 'cljs.analyzer.api 'ns-publics) from-ns)] `(import-def ~from-ns ~d))] `(do ~@expanded-imports)))
51c032dae8484cf0755bbb425e138fb495962903c5c397598e7020ede7a55d90
reiddraper/knockbox
core.clj
(ns knockbox.test.core (:use [knockbox.core]) (:use [clojure.test]))
null
https://raw.githubusercontent.com/reiddraper/knockbox/ed22221759d0d3dbe4f1b1f83355e95e945de729/test/knockbox/test/core.clj
clojure
(ns knockbox.test.core (:use [knockbox.core]) (:use [clojure.test]))
0662d4575d8f7a45cdeabde33939cd02de261f317bb6defd396315b398981d22
gpwwjr/LISA
strategies.lisp
This file is part of LISA , the Lisp - based Intelligent Software ;;; Agents platform. Copyright ( C ) 2000 ( ) ;;; 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 . ;;; 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 . ;;; File: strategies.lisp ;;; Description: Classes that implement the various default conflict resolution strategies for Lisa 's RETE implementation . $ I d : strategies.lisp , v 1.1 2006/04/14 16:44:37 youngde Exp $ (in-package "LISA") (defclass strategy () () (:documentation "Serves as the base class for all classes implementing conflict resolution strategies.")) (defgeneric add-activation (strategy activation)) (defgeneric find-activation (strategy rule token)) (defgeneric find-all-activations (strategy rule)) (defgeneric next-activation (strategy)) (defgeneric remove-activations (strategy)) (defgeneric list-activations (strategy)) (defclass indexed-priority-list () ((priority-vector :reader get-priority-vector) (inodes :initform '() :accessor get-inodes) (delta :accessor get-delta) (insertion-function :initarg :insertion-function :reader get-insertion-function)) (:documentation "Utility class that implements an indexed priority 'queue' to manage activations. Employed by various types of conflict resolution strategies, particularly DEPTH-FIRST-STRATEGY and BREADTH-FIRST-STRATEGY.")) (defmethod initialize-instance :after ((self indexed-priority-list) &key (priorities 500)) (setf (slot-value self 'priority-vector) (make-array (1+ priorities) :initial-element nil)) (setf (slot-value self 'delta) (/ priorities 2))) (defun reset-activations (self) (declare (type indexed-priority-list self)) (let ((queue (get-priority-vector self))) (mapc #'(lambda (inode) (setf (aref queue inode) nil)) (get-inodes self)) (setf (get-inodes self) '()))) (defun insert-activation (plist activation) (declare (type indexed-priority-list plist)) (flet ((index-salience (priority) (declare (type fixnum priority)) (with-accessors ((inodes get-inodes)) plist (setf inodes (sort (pushnew priority inodes) #'(lambda (p1 p2) (> p1 p2))))))) (with-accessors ((vector get-priority-vector) (activations get-activations)) plist (let* ((salience (rule-salience (activation-rule activation))) (inode (+ salience (get-delta plist))) (queue (aref vector inode))) (when (null queue) (index-salience inode)) (setf (aref vector inode) (apply (get-insertion-function plist) `(,activation ,queue))))))) (defun lookup-activation (self rule tokens) (declare (type indexed-priority-list self)) (find-if #'(lambda (act) (and (equal (hash-key act) (hash-key tokens)) (eq (activation-rule act) rule))) (aref (get-priority-vector self) (+ (rule-salience rule) (get-delta self))))) (defun lookup-activations (self rule) (declare (type indexed-priority-list self)) (loop for activation in (aref (get-priority-vector self) (+ (rule-salience rule) (get-delta self))) if (eq rule (activation-rule activation)) collect activation)) (defun get-next-activation (plist) (declare (type indexed-priority-list plist)) (with-accessors ((inodes get-inodes) (vector get-priority-vector)) plist (let ((inode (first inodes))) (cond ((null inode) nil) (t (let ((activation (pop (aref vector inode)))) (when (null (aref vector inode)) (pop inodes)) activation)))))) (defun get-all-activations (plist) (let ((activations (list))) (with-accessors ((queue get-priority-vector)) plist (mapc #'(lambda (inode) (mapc #'(lambda (act) (when (eligible-p act) (push act activations))) (aref queue inode))) (get-inodes plist))) (nreverse activations))) (defun make-indexed-priority-list (insert-func) (make-instance 'indexed-priority-list :insertion-function insert-func)) (defclass builtin-strategy (strategy) ((priority-queue :reader get-priority-queue)) (:documentation "A base class for all LISA builtin conflict resolution strategies.")) (defmethod add-activation ((self builtin-strategy) activation) (insert-activation (get-priority-queue self) activation)) (defmethod find-activation ((self builtin-strategy) rule token) (cl:assert nil nil "Why are we calling FIND-ACTIVATION?") (lookup-activation (get-priority-queue self) rule token)) (defmethod find-all-activations ((self builtin-strategy) rule) (lookup-activations (get-priority-queue self) rule)) (defmethod next-activation ((self builtin-strategy)) (get-next-activation (get-priority-queue self))) (defmethod remove-activations ((self builtin-strategy)) (reset-activations (get-priority-queue self))) (defmethod list-activations ((self builtin-strategy)) (get-all-activations (get-priority-queue self))) (defclass depth-first-strategy (builtin-strategy) () (:documentation "A depth-first conflict resolution strategy.")) (defmethod initialize-instance :after ((self depth-first-strategy) &rest args) (declare (ignore args)) (setf (slot-value self 'priority-queue) (make-indexed-priority-list #'(lambda (obj place) (push obj place))))) (defun make-depth-first-strategy () (make-instance 'depth-first-strategy)) (defclass breadth-first-strategy (builtin-strategy) ((tail :initform nil :accessor tail)) (:documentation "A breadth-first conflict resolution strategy.")) (defmethod initialize-instance :after ((self breadth-first-strategy) &rest args) (declare (ignore args)) (setf (slot-value self 'priority-queue) (make-indexed-priority-list #'(lambda (obj place) (with-accessors ((p tail)) self (cond ((null place) (setf place (list obj)) (setf p place)) (t (setf p (nconc p (list obj))) (setf p (cdr p)))) place))))) (defun make-breadth-first-strategy () (make-instance 'breadth-first-strategy))
null
https://raw.githubusercontent.com/gpwwjr/LISA/bc7f54b3a9b901d5648d7e9de358e29d3b794c78/src/core/strategies.lisp
lisp
Agents platform. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License either version 2.1 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 along with this library; if not, write to the Free Software File: strategies.lisp Description: Classes that implement the various default conflict
This file is part of LISA , the Lisp - based Intelligent Software Copyright ( C ) 2000 ( ) of the License , or ( at your option ) any later version . GNU Lesser General Public License for more details . You should have received a copy of the GNU Lesser General Public License Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . resolution strategies for Lisa 's RETE implementation . $ I d : strategies.lisp , v 1.1 2006/04/14 16:44:37 youngde Exp $ (in-package "LISA") (defclass strategy () () (:documentation "Serves as the base class for all classes implementing conflict resolution strategies.")) (defgeneric add-activation (strategy activation)) (defgeneric find-activation (strategy rule token)) (defgeneric find-all-activations (strategy rule)) (defgeneric next-activation (strategy)) (defgeneric remove-activations (strategy)) (defgeneric list-activations (strategy)) (defclass indexed-priority-list () ((priority-vector :reader get-priority-vector) (inodes :initform '() :accessor get-inodes) (delta :accessor get-delta) (insertion-function :initarg :insertion-function :reader get-insertion-function)) (:documentation "Utility class that implements an indexed priority 'queue' to manage activations. Employed by various types of conflict resolution strategies, particularly DEPTH-FIRST-STRATEGY and BREADTH-FIRST-STRATEGY.")) (defmethod initialize-instance :after ((self indexed-priority-list) &key (priorities 500)) (setf (slot-value self 'priority-vector) (make-array (1+ priorities) :initial-element nil)) (setf (slot-value self 'delta) (/ priorities 2))) (defun reset-activations (self) (declare (type indexed-priority-list self)) (let ((queue (get-priority-vector self))) (mapc #'(lambda (inode) (setf (aref queue inode) nil)) (get-inodes self)) (setf (get-inodes self) '()))) (defun insert-activation (plist activation) (declare (type indexed-priority-list plist)) (flet ((index-salience (priority) (declare (type fixnum priority)) (with-accessors ((inodes get-inodes)) plist (setf inodes (sort (pushnew priority inodes) #'(lambda (p1 p2) (> p1 p2))))))) (with-accessors ((vector get-priority-vector) (activations get-activations)) plist (let* ((salience (rule-salience (activation-rule activation))) (inode (+ salience (get-delta plist))) (queue (aref vector inode))) (when (null queue) (index-salience inode)) (setf (aref vector inode) (apply (get-insertion-function plist) `(,activation ,queue))))))) (defun lookup-activation (self rule tokens) (declare (type indexed-priority-list self)) (find-if #'(lambda (act) (and (equal (hash-key act) (hash-key tokens)) (eq (activation-rule act) rule))) (aref (get-priority-vector self) (+ (rule-salience rule) (get-delta self))))) (defun lookup-activations (self rule) (declare (type indexed-priority-list self)) (loop for activation in (aref (get-priority-vector self) (+ (rule-salience rule) (get-delta self))) if (eq rule (activation-rule activation)) collect activation)) (defun get-next-activation (plist) (declare (type indexed-priority-list plist)) (with-accessors ((inodes get-inodes) (vector get-priority-vector)) plist (let ((inode (first inodes))) (cond ((null inode) nil) (t (let ((activation (pop (aref vector inode)))) (when (null (aref vector inode)) (pop inodes)) activation)))))) (defun get-all-activations (plist) (let ((activations (list))) (with-accessors ((queue get-priority-vector)) plist (mapc #'(lambda (inode) (mapc #'(lambda (act) (when (eligible-p act) (push act activations))) (aref queue inode))) (get-inodes plist))) (nreverse activations))) (defun make-indexed-priority-list (insert-func) (make-instance 'indexed-priority-list :insertion-function insert-func)) (defclass builtin-strategy (strategy) ((priority-queue :reader get-priority-queue)) (:documentation "A base class for all LISA builtin conflict resolution strategies.")) (defmethod add-activation ((self builtin-strategy) activation) (insert-activation (get-priority-queue self) activation)) (defmethod find-activation ((self builtin-strategy) rule token) (cl:assert nil nil "Why are we calling FIND-ACTIVATION?") (lookup-activation (get-priority-queue self) rule token)) (defmethod find-all-activations ((self builtin-strategy) rule) (lookup-activations (get-priority-queue self) rule)) (defmethod next-activation ((self builtin-strategy)) (get-next-activation (get-priority-queue self))) (defmethod remove-activations ((self builtin-strategy)) (reset-activations (get-priority-queue self))) (defmethod list-activations ((self builtin-strategy)) (get-all-activations (get-priority-queue self))) (defclass depth-first-strategy (builtin-strategy) () (:documentation "A depth-first conflict resolution strategy.")) (defmethod initialize-instance :after ((self depth-first-strategy) &rest args) (declare (ignore args)) (setf (slot-value self 'priority-queue) (make-indexed-priority-list #'(lambda (obj place) (push obj place))))) (defun make-depth-first-strategy () (make-instance 'depth-first-strategy)) (defclass breadth-first-strategy (builtin-strategy) ((tail :initform nil :accessor tail)) (:documentation "A breadth-first conflict resolution strategy.")) (defmethod initialize-instance :after ((self breadth-first-strategy) &rest args) (declare (ignore args)) (setf (slot-value self 'priority-queue) (make-indexed-priority-list #'(lambda (obj place) (with-accessors ((p tail)) self (cond ((null place) (setf place (list obj)) (setf p place)) (t (setf p (nconc p (list obj))) (setf p (cdr p)))) place))))) (defun make-breadth-first-strategy () (make-instance 'breadth-first-strategy))
15df06200ba085faac45db5d78850049af78a7c5242e76ca5178f2e68824e759
reenberg/wobot
LiftN.hs
# LANGUAGE CPP # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE FunctionalDependencies # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE MultiParamTypeClasses # # LANGUAGE QuasiQuotes # {-# LANGUAGE RankNTypes #-} # LANGUAGE ScopedTypeVariables # # LANGUAGE TemplateHaskell # Copyright ( c ) 2008 The President and Fellows of Harvard College . -- -- 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 . Neither the name of the University 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 UNIVERSITY 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 UNIVERSITY 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. -------------------------------------------------------------------------------- -- | Module : . Copyright : ( c ) Harvard University 2008 -- License : BSD-style -- Maintainer : -- -------------------------------------------------------------------------------- module Fladuino.LiftN where import Prelude hiding (exp) import Control.Monad.State import Control.Monad.CGen import Control.Monad.ContextException import Control.Monad.Exception import Data.Loc import Data.Name import qualified Language.Hs.Syntax import qualified Language.Hs as H import Language.Hs.Quote import Language.C.Syntax import Language.C.Quote import Text.PrettyPrint.Mainland import qualified Transform.Hs.Desugar as Desugar import qualified Transform.Hs.Rename as Rename import Fladuino.Driver import Fladuino.Exceptions import Fladuino.Monad import Fladuino.Reify |A value of type @N a@ represents node - level code of type The @LiftN@ -- type class allows us to lift either C or "Red" code to node-level code. newtype N a = N { unN :: FladuinoM NCode } class LiftN n a where liftN :: n -> N a instance LiftN (N a) a where liftN = id instance forall a . (Reify a) => LiftN [H.Decl] a where liftN decls = N $ addCode ty (HsDecls ty decls) $ do decls' <- Rename.rename decls >>= Desugar.desugar v <- case binders decls' of [v] -> return v vs -> withLocContext (getLoc decls') (text "declaration") $ fail $ pretty 80 $ text "cannot choose which declaration to lift:" <+> commasep (map ppr vs) liftDecls decls' v ty where ty :: H.Type ty = reify (undefined :: a) instance forall a . (Reify a) => LiftN H.Exp a where liftN e = N $ addCode ty (HsExp ty e) $ liftDecls [decl] v ty where v :: H.Var v = H.var "v" ty :: H.Type ty = reify (undefined :: a) decl :: H.Decl decl = H.patD (H.varP v) (H.rhsD [H.sigE e ty]) instance Reify a => LiftN Func a where liftN f = N $ addCode ty (CFun ty f) $ do cty <- toC ty when (funTy f /= cty) $ throwException $ CTypeError cty (funTy f) liftCFun f ty where ty :: H.Type ty = reify (undefined :: a) funTy :: Func -> Type funTy (Func decl_spec _ decl args _) = Type decl_spec (Ptr [] (Proto decl (stripParams args))) funTy (OldFunc decl_spec _ decl args _ _) = Type decl_spec (Ptr [] (OldProto decl args)) stripParams :: Params -> Params stripParams (Params ps var) = Params (map stripParam ps) var stripParam :: Param -> Param stripParam (Param _ decl_spec decl) = Param Nothing decl_spec decl stripParam _ = error "internal error" liftDecls :: MonadFladuino m => [H.Decl] -> H.Var -> H.Type -> m H.Var liftDecls decls v@(H.Var n) ty = do v' <- return H.var `ap` gensym (nameString n) let decl = H.patD (H.varP v') (H.rhsD [H.letE decls (H.varE v)]) modifyFladuinoEnv $ \s -> s { f_hsdecls = f_hsdecls s ++ [H.sigD [v'] ty, decl] } return v' liftDecls _ _ _ = fail "Cannot lift" liftCFun :: MonadFladuino m => Func -> H.Type -> m H.Var liftCFun f ty = do addCImport fid ty [$cexp|$id:fid|] addDecls [$decls|$var:v :: $ty:ty|] addCFundef $ FuncDef f internalLoc return v where fid :: String fid = idString (funName f) v :: H.Var v = H.var fid funName :: Func -> Id funName (Func _ ident _ _ _) = ident funName (OldFunc _ ident _ _ _ _) = ident idString :: Id -> String idString (Id s) = s idString _ = error "internal error" nzip :: forall a b . (Reify a, Reify b) => N a -> N b -> N (a, b) nzip na nb = N $ do n_1 <- unN na n_2 <- unN nb let n1 = H.varE (n_var n_1) let n2 = H.varE (n_var n_2) nzip <- unN $ (liftN [$exp|($exp:n1, $exp:n2)|] :: N (a, b)) return nzip nexp :: N a -> FladuinoM H.Exp nexp n = do ncode <- unN n return $ H.varE (n_var ncode)
null
https://raw.githubusercontent.com/reenberg/wobot/ce7f112096ba1abd43b8d29da7e8944c2a004125/fladuino/fladuino/Fladuino/LiftN.hs
haskell
# LANGUAGE RankNTypes # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: notice, this list of conditions and the following disclaimer. notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. may be used to endorse or promote products derived from this software without specific prior written permission. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ARE DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY OR CONTRIBUTORS BE LIABLE DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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. ------------------------------------------------------------------------------ | License : BSD-style Maintainer : ------------------------------------------------------------------------------ type class allows us to lift either C or "Red" code to node-level code.
# LANGUAGE CPP # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE FunctionalDependencies # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE MultiParamTypeClasses # # LANGUAGE QuasiQuotes # # LANGUAGE ScopedTypeVariables # # LANGUAGE TemplateHaskell # Copyright ( c ) 2008 The President and Fellows of Harvard College . 1 . Redistributions of source code must retain the above copyright 2 . Redistributions in binary form must reproduce the above copyright 3 . Neither the name of the University nor the names of its contributors THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY AND CONTRIBUTORS ` ` AS IS '' AND IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT Module : . Copyright : ( c ) Harvard University 2008 module Fladuino.LiftN where import Prelude hiding (exp) import Control.Monad.State import Control.Monad.CGen import Control.Monad.ContextException import Control.Monad.Exception import Data.Loc import Data.Name import qualified Language.Hs.Syntax import qualified Language.Hs as H import Language.Hs.Quote import Language.C.Syntax import Language.C.Quote import Text.PrettyPrint.Mainland import qualified Transform.Hs.Desugar as Desugar import qualified Transform.Hs.Rename as Rename import Fladuino.Driver import Fladuino.Exceptions import Fladuino.Monad import Fladuino.Reify |A value of type @N a@ represents node - level code of type The @LiftN@ newtype N a = N { unN :: FladuinoM NCode } class LiftN n a where liftN :: n -> N a instance LiftN (N a) a where liftN = id instance forall a . (Reify a) => LiftN [H.Decl] a where liftN decls = N $ addCode ty (HsDecls ty decls) $ do decls' <- Rename.rename decls >>= Desugar.desugar v <- case binders decls' of [v] -> return v vs -> withLocContext (getLoc decls') (text "declaration") $ fail $ pretty 80 $ text "cannot choose which declaration to lift:" <+> commasep (map ppr vs) liftDecls decls' v ty where ty :: H.Type ty = reify (undefined :: a) instance forall a . (Reify a) => LiftN H.Exp a where liftN e = N $ addCode ty (HsExp ty e) $ liftDecls [decl] v ty where v :: H.Var v = H.var "v" ty :: H.Type ty = reify (undefined :: a) decl :: H.Decl decl = H.patD (H.varP v) (H.rhsD [H.sigE e ty]) instance Reify a => LiftN Func a where liftN f = N $ addCode ty (CFun ty f) $ do cty <- toC ty when (funTy f /= cty) $ throwException $ CTypeError cty (funTy f) liftCFun f ty where ty :: H.Type ty = reify (undefined :: a) funTy :: Func -> Type funTy (Func decl_spec _ decl args _) = Type decl_spec (Ptr [] (Proto decl (stripParams args))) funTy (OldFunc decl_spec _ decl args _ _) = Type decl_spec (Ptr [] (OldProto decl args)) stripParams :: Params -> Params stripParams (Params ps var) = Params (map stripParam ps) var stripParam :: Param -> Param stripParam (Param _ decl_spec decl) = Param Nothing decl_spec decl stripParam _ = error "internal error" liftDecls :: MonadFladuino m => [H.Decl] -> H.Var -> H.Type -> m H.Var liftDecls decls v@(H.Var n) ty = do v' <- return H.var `ap` gensym (nameString n) let decl = H.patD (H.varP v') (H.rhsD [H.letE decls (H.varE v)]) modifyFladuinoEnv $ \s -> s { f_hsdecls = f_hsdecls s ++ [H.sigD [v'] ty, decl] } return v' liftDecls _ _ _ = fail "Cannot lift" liftCFun :: MonadFladuino m => Func -> H.Type -> m H.Var liftCFun f ty = do addCImport fid ty [$cexp|$id:fid|] addDecls [$decls|$var:v :: $ty:ty|] addCFundef $ FuncDef f internalLoc return v where fid :: String fid = idString (funName f) v :: H.Var v = H.var fid funName :: Func -> Id funName (Func _ ident _ _ _) = ident funName (OldFunc _ ident _ _ _ _) = ident idString :: Id -> String idString (Id s) = s idString _ = error "internal error" nzip :: forall a b . (Reify a, Reify b) => N a -> N b -> N (a, b) nzip na nb = N $ do n_1 <- unN na n_2 <- unN nb let n1 = H.varE (n_var n_1) let n2 = H.varE (n_var n_2) nzip <- unN $ (liftN [$exp|($exp:n1, $exp:n2)|] :: N (a, b)) return nzip nexp :: N a -> FladuinoM H.Exp nexp n = do ncode <- unN n return $ H.varE (n_var ncode)
f093dc1bc9d2c84e4444e57fb27e091de99a1febc21401240667eb5166b2ddaa
facebook/pyre-check
modulePath.ml
* Copyright ( c ) Meta Platforms , Inc. and affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) (* TODO(T132410158) Add a module-level doc comment. *) open Core open Pyre module Raw = struct module T = struct type t = { relative: string; priority: int; } [@@deriving compare, hash, sexp] let pp formatter { relative; priority } = Format.fprintf formatter "%d/%s" priority relative let equal = [%compare.equal: t] let create ~configuration path = let search_paths = Configuration.Analysis.search_paths configuration in SearchPath.search_for_path ~search_paths path >>| fun SearchPath.{ relative_path; priority } -> { relative = PyrePath.RelativePath.relative relative_path; priority } let full_path ~configuration { relative; priority; _ } = let root = Configuration.Analysis.search_paths configuration |> fun search_paths -> List.nth_exn search_paths priority |> SearchPath.get_root in PyrePath.create_relative ~root ~relative |> ArtifactPath.create end include T module Set = Caml.Set.Make (T) end module T = struct type t = { raw: Raw.t; qualifier: Reference.t; is_stub: bool; is_external: bool; is_init: bool; } [@@deriving compare, hash, sexp] end include Hashable.Make (T) include T let equal = [%compare.equal: t] let pp formatter { raw; qualifier; is_stub; is_external; is_init } = let is_stub = if is_stub then " [STUB]" else "" in let is_external = if is_external then " [EXTERNAL]" else "" in let is_init = if is_init then " [INIT]" else "" in Format.fprintf formatter "[%a(%a)%s%s%s]" Raw.pp raw Reference.pp qualifier is_stub is_external is_init let qualifier_of_relative relative = match relative with | "" -> Reference.empty | _ -> let qualifier = let reversed_elements = let strip_stub_suffix name = Stub packages have their directories named as ` XXX - stubs ` . See PEP 561 . match String.chop_suffix name ~suffix:"-stubs" with | Some result -> result | None -> name in Filename.parts relative Strip current directory . |> List.map ~f:strip_stub_suffix |> List.rev in let last_without_suffix = let last = List.hd_exn reversed_elements in match String.rindex last '.' with | Some index -> String.slice last 0 index | _ -> last in let strip = function | ["builtins"] | ["builtins"; "future"] -> [] | "__init__" :: tail -> tail | elements -> elements in last_without_suffix :: List.tl_exn reversed_elements |> strip |> List.rev_map ~f:(String.split ~on:'.') |> List.concat in Reference.create_from_list qualifier let is_internal_path ~configuration:{ Configuration.Analysis.filter_directories; ignore_all_errors; _ } path = let original_raw_path = let raw_path = ArtifactPath.raw path in (* NOTE(grievejia): Symlink are generally not followed by the type checker. This usage comes from legacy code and should not be replicated elsewhere. *) PyrePath.follow_symbolic_link raw_path |> Option.value ~default:raw_path in let source_path_is_covered item = PyrePath.equal item original_raw_path || PyrePath.directory_contains ~directory:item original_raw_path in let filter_directories = Option.value filter_directories ~default:[] in let ignore_all_errors = Option.value ignore_all_errors ~default:[] in List.exists filter_directories ~f:source_path_is_covered && not (List.exists ignore_all_errors ~f:source_path_is_covered) let should_type_check ~configuration:({ Configuration.Analysis.analyze_external_sources; _ } as configuration) path = analyze_external_sources || is_internal_path ~configuration path let create ~configuration:({ Configuration.Analysis.excludes; _ } as configuration) path = let absolute_path = ArtifactPath.raw path |> PyrePath.absolute in if List.exists excludes ~f:(fun regexp -> Str.string_match regexp absolute_path 0) then None else Raw.create ~configuration path >>= fun (Raw.{ relative; _ } as raw) -> let qualifier = match Configuration.Analysis.find_extension configuration path with | Some { Configuration.Extension.include_suffix_in_module_qualifier; _ } when include_suffix_in_module_qualifier -> (* Ensure extension is not stripped when creating qualifier *) qualifier_of_relative (relative ^ ".py") | _ -> qualifier_of_relative relative in let is_stub = PyrePath.is_path_python_stub relative in let is_init = PyrePath.is_path_python_init relative in Some { raw; qualifier; is_stub; is_external = not (should_type_check ~configuration path); is_init; } let qualifier { qualifier; _ } = qualifier let raw { raw; _ } = raw let relative { raw = { relative; _ }; _ } = relative let is_in_project { is_external; _ } = not is_external let create_for_testing ~relative ~is_external ~priority = let raw = Raw.{ relative; priority } in let qualifier = qualifier_of_relative relative in let is_stub = PyrePath.is_path_python_stub relative in let is_init = PyrePath.is_path_python_init relative in { raw; qualifier; is_stub; is_external; is_init } let full_path ~configuration { raw; _ } = Raw.full_path ~configuration raw NOTE : This comparator is expected to operate on SourceFiles that are mapped to the same module only . Do NOT use it on . only. Do NOT use it on aribitrary SourceFiles. *) let same_module_compare ~configuration { raw = { relative = left_path; priority = left_priority }; is_stub = left_is_stub; is_init = left_is_init; _; } { raw = { relative = right_path; priority = right_priority }; is_stub = right_is_stub; is_init = right_is_init; _; } = (* Stub file always takes precedence *) let stub_priority _ = match left_is_stub, right_is_stub with | true, false -> -1 | false, true -> 1 | _, _ -> 0 in (* Priority based on priority number. Smaller int means higher priority. *) let number_priority _ = Int.compare left_priority right_priority in (* Package takes precedence over file module with the same name *) let is_init_priority _ = match left_is_init, right_is_init with | true, false -> -1 | false, true -> 1 | _, _ -> 0 in (* prioritize extensions in the order listed in the configuration. *) let extension_priority _ = let extensions = Configuration.Analysis.extension_suffixes configuration in let find_extension_index path = let extensions = if Option.is_some (List.find extensions ~f:(String.equal ".py")) then extensions else ".py" :: extensions in let get_extension path = Filename.split_extension path |> snd >>| (fun extension -> "." ^ extension) |> Option.value ~default:"" in List.findi extensions ~f:(fun _ extension -> String.equal (get_extension path) extension) >>| fst in match find_extension_index left_path, find_extension_index right_path with | Some left, Some right -> left - right | _ -> 0 in Prioritize the file ` b.py ` within a directory ` a ` over ` a.b.py ` if importing as ` a.b ` . Note : files with multiple dots are not valid in vanilla python . files with multiple dots are not valid in vanilla python. *) let file_path_priority _ = let is_slash char = Char.equal char (Char.of_string "/") in String.count right_path ~f:is_slash - String.count left_path ~f:is_slash in let priority_order = [stub_priority; number_priority; is_init_priority; extension_priority; file_path_priority] in Return the first nonzero comparison Option.value (List.find_map priority_order ~f:(fun priority_function -> match priority_function () with | 0 -> None | n -> Some n)) ~default:0 let is_stub { is_stub; _ } = is_stub let is_init { is_init; _ } = is_init let expand_relative_import ~from { is_init; qualifier; _ } = match Reference.show from with | "builtins" -> Reference.empty | serialized -> Expand relative imports according to PEP 328 let dots = String.take_while ~f:(fun dot -> Char.equal dot '.') serialized in let postfix = match String.drop_prefix serialized (String.length dots) with (* Special case for single `.`, `..`, etc. in from clause. *) | "" -> Reference.empty | nonempty -> Reference.create nonempty in let prefix = if not (String.is_empty dots) then let initializer_module_offset = (* `.` corresponds to the directory containing the module. For non-init modules, the qualifier matches the path, so we drop exactly the number of dots. However, for __init__ modules, the directory containing it represented by the qualifier. *) if is_init then 1 else 0 in List.rev (Reference.as_list qualifier) |> (fun reversed -> List.drop reversed (String.length dots - initializer_module_offset)) |> List.rev |> Reference.create_from_list else Reference.empty in Reference.combine prefix postfix
null
https://raw.githubusercontent.com/facebook/pyre-check/2ae0e5f9eccceb2f085135724a0654db999da0fb/source/ast/modulePath.ml
ocaml
TODO(T132410158) Add a module-level doc comment. NOTE(grievejia): Symlink are generally not followed by the type checker. This usage comes from legacy code and should not be replicated elsewhere. Ensure extension is not stripped when creating qualifier Stub file always takes precedence Priority based on priority number. Smaller int means higher priority. Package takes precedence over file module with the same name prioritize extensions in the order listed in the configuration. Special case for single `.`, `..`, etc. in from clause. `.` corresponds to the directory containing the module. For non-init modules, the qualifier matches the path, so we drop exactly the number of dots. However, for __init__ modules, the directory containing it represented by the qualifier.
* Copyright ( c ) Meta Platforms , Inc. and affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) open Core open Pyre module Raw = struct module T = struct type t = { relative: string; priority: int; } [@@deriving compare, hash, sexp] let pp formatter { relative; priority } = Format.fprintf formatter "%d/%s" priority relative let equal = [%compare.equal: t] let create ~configuration path = let search_paths = Configuration.Analysis.search_paths configuration in SearchPath.search_for_path ~search_paths path >>| fun SearchPath.{ relative_path; priority } -> { relative = PyrePath.RelativePath.relative relative_path; priority } let full_path ~configuration { relative; priority; _ } = let root = Configuration.Analysis.search_paths configuration |> fun search_paths -> List.nth_exn search_paths priority |> SearchPath.get_root in PyrePath.create_relative ~root ~relative |> ArtifactPath.create end include T module Set = Caml.Set.Make (T) end module T = struct type t = { raw: Raw.t; qualifier: Reference.t; is_stub: bool; is_external: bool; is_init: bool; } [@@deriving compare, hash, sexp] end include Hashable.Make (T) include T let equal = [%compare.equal: t] let pp formatter { raw; qualifier; is_stub; is_external; is_init } = let is_stub = if is_stub then " [STUB]" else "" in let is_external = if is_external then " [EXTERNAL]" else "" in let is_init = if is_init then " [INIT]" else "" in Format.fprintf formatter "[%a(%a)%s%s%s]" Raw.pp raw Reference.pp qualifier is_stub is_external is_init let qualifier_of_relative relative = match relative with | "" -> Reference.empty | _ -> let qualifier = let reversed_elements = let strip_stub_suffix name = Stub packages have their directories named as ` XXX - stubs ` . See PEP 561 . match String.chop_suffix name ~suffix:"-stubs" with | Some result -> result | None -> name in Filename.parts relative Strip current directory . |> List.map ~f:strip_stub_suffix |> List.rev in let last_without_suffix = let last = List.hd_exn reversed_elements in match String.rindex last '.' with | Some index -> String.slice last 0 index | _ -> last in let strip = function | ["builtins"] | ["builtins"; "future"] -> [] | "__init__" :: tail -> tail | elements -> elements in last_without_suffix :: List.tl_exn reversed_elements |> strip |> List.rev_map ~f:(String.split ~on:'.') |> List.concat in Reference.create_from_list qualifier let is_internal_path ~configuration:{ Configuration.Analysis.filter_directories; ignore_all_errors; _ } path = let original_raw_path = let raw_path = ArtifactPath.raw path in PyrePath.follow_symbolic_link raw_path |> Option.value ~default:raw_path in let source_path_is_covered item = PyrePath.equal item original_raw_path || PyrePath.directory_contains ~directory:item original_raw_path in let filter_directories = Option.value filter_directories ~default:[] in let ignore_all_errors = Option.value ignore_all_errors ~default:[] in List.exists filter_directories ~f:source_path_is_covered && not (List.exists ignore_all_errors ~f:source_path_is_covered) let should_type_check ~configuration:({ Configuration.Analysis.analyze_external_sources; _ } as configuration) path = analyze_external_sources || is_internal_path ~configuration path let create ~configuration:({ Configuration.Analysis.excludes; _ } as configuration) path = let absolute_path = ArtifactPath.raw path |> PyrePath.absolute in if List.exists excludes ~f:(fun regexp -> Str.string_match regexp absolute_path 0) then None else Raw.create ~configuration path >>= fun (Raw.{ relative; _ } as raw) -> let qualifier = match Configuration.Analysis.find_extension configuration path with | Some { Configuration.Extension.include_suffix_in_module_qualifier; _ } when include_suffix_in_module_qualifier -> qualifier_of_relative (relative ^ ".py") | _ -> qualifier_of_relative relative in let is_stub = PyrePath.is_path_python_stub relative in let is_init = PyrePath.is_path_python_init relative in Some { raw; qualifier; is_stub; is_external = not (should_type_check ~configuration path); is_init; } let qualifier { qualifier; _ } = qualifier let raw { raw; _ } = raw let relative { raw = { relative; _ }; _ } = relative let is_in_project { is_external; _ } = not is_external let create_for_testing ~relative ~is_external ~priority = let raw = Raw.{ relative; priority } in let qualifier = qualifier_of_relative relative in let is_stub = PyrePath.is_path_python_stub relative in let is_init = PyrePath.is_path_python_init relative in { raw; qualifier; is_stub; is_external; is_init } let full_path ~configuration { raw; _ } = Raw.full_path ~configuration raw NOTE : This comparator is expected to operate on SourceFiles that are mapped to the same module only . Do NOT use it on . only. Do NOT use it on aribitrary SourceFiles. *) let same_module_compare ~configuration { raw = { relative = left_path; priority = left_priority }; is_stub = left_is_stub; is_init = left_is_init; _; } { raw = { relative = right_path; priority = right_priority }; is_stub = right_is_stub; is_init = right_is_init; _; } = let stub_priority _ = match left_is_stub, right_is_stub with | true, false -> -1 | false, true -> 1 | _, _ -> 0 in let number_priority _ = Int.compare left_priority right_priority in let is_init_priority _ = match left_is_init, right_is_init with | true, false -> -1 | false, true -> 1 | _, _ -> 0 in let extension_priority _ = let extensions = Configuration.Analysis.extension_suffixes configuration in let find_extension_index path = let extensions = if Option.is_some (List.find extensions ~f:(String.equal ".py")) then extensions else ".py" :: extensions in let get_extension path = Filename.split_extension path |> snd >>| (fun extension -> "." ^ extension) |> Option.value ~default:"" in List.findi extensions ~f:(fun _ extension -> String.equal (get_extension path) extension) >>| fst in match find_extension_index left_path, find_extension_index right_path with | Some left, Some right -> left - right | _ -> 0 in Prioritize the file ` b.py ` within a directory ` a ` over ` a.b.py ` if importing as ` a.b ` . Note : files with multiple dots are not valid in vanilla python . files with multiple dots are not valid in vanilla python. *) let file_path_priority _ = let is_slash char = Char.equal char (Char.of_string "/") in String.count right_path ~f:is_slash - String.count left_path ~f:is_slash in let priority_order = [stub_priority; number_priority; is_init_priority; extension_priority; file_path_priority] in Return the first nonzero comparison Option.value (List.find_map priority_order ~f:(fun priority_function -> match priority_function () with | 0 -> None | n -> Some n)) ~default:0 let is_stub { is_stub; _ } = is_stub let is_init { is_init; _ } = is_init let expand_relative_import ~from { is_init; qualifier; _ } = match Reference.show from with | "builtins" -> Reference.empty | serialized -> Expand relative imports according to PEP 328 let dots = String.take_while ~f:(fun dot -> Char.equal dot '.') serialized in let postfix = match String.drop_prefix serialized (String.length dots) with | "" -> Reference.empty | nonempty -> Reference.create nonempty in let prefix = if not (String.is_empty dots) then let initializer_module_offset = if is_init then 1 else 0 in List.rev (Reference.as_list qualifier) |> (fun reversed -> List.drop reversed (String.length dots - initializer_module_offset)) |> List.rev |> Reference.create_from_list else Reference.empty in Reference.combine prefix postfix
6beaa3d0a1c8d7ef1f4f78635d3af744f3ca23970dd69a92308b0aeffcbba20f
dieu/consulerl
consulerl_eunit.erl
-module(consulerl_eunit). -include("consulerl.hrl"). -include_lib("eunit/include/eunit.hrl"). %% API -export([ setup_app/0, setup_httpc_200/1, setup_httpc_200/2, setup_httpc_200_plain/1, setup_httpc_404/0, setup_httpc_405/0, setup_httpc_409/1, setup_httpc_timeout/0, setup_error/0 ]). -export([ stop_app/0, stop_httpc/0, stop/1 ]). -export([ command/4, command_async/4, command_async_twice/4 ]). setup_app() -> {ok, _} = application:ensure_all_started(consulerl), ok. setup_httpc_200(Response) -> ok = meck:expect(hackney, request, fun(_, _, _, _, _) -> Ref = make_ref(), ok = exec(self(), Ref, 200, test, <<"application/json">>, Response), {ok, Ref} end). setup_httpc_200(Response, Timeout) -> ok = meck:expect(hackney, request, fun(_, _, _, _, _) -> Ref = make_ref(), Self = self(), timer:apply_after(Timeout, ?MODULE, exec, [Self, Ref, 200, test, <<"application/json">>, Response]), {ok, Ref} end). setup_httpc_200_plain(Response) -> ok = meck:expect(hackney, request, fun(_, _, _, _, _) -> Ref = make_ref(), ok = exec(self(), Ref, 200, test, <<"text/plain; charset=utf-8">>, Response), {ok, Ref} end). setup_httpc_404() -> ok = meck:expect(hackney, request, fun(_, _, _, _, _) -> Ref = make_ref(), ok = exec(self(), Ref, 404, "Not Found", <<"text/plain; charset=utf-8">>, <<>>), {ok, Ref} end). setup_httpc_405() -> ok = meck:expect(hackney, request, fun(_, _, _, _, _) -> Ref = make_ref(), ok = exec(self(), Ref, 405, "Method Not Allowed", <<"text/plain; charset=utf-8">>, <<>>), {ok, Ref} end). setup_httpc_409(Error) -> ok = meck:expect(hackney, request, fun(_, _, _, _, _) -> Ref = make_ref(), ok = exec(self(), Ref, 409, "Conflict", <<"application/json">>, Error), {ok, Ref} end). setup_httpc_timeout() -> ok = meck:expect(hackney, request, fun(_, _, _, _, _) -> Ref = make_ref(), {ok, Ref} end). setup_error() -> ok = meck:expect(hackney, request, fun(_, _, _, _, _) -> {error, error} end). stop_app() -> application:stop(consulerl). stop_httpc() -> ok = meck:unload(hackney). stop(_) -> ok = stop_httpc(), ok = stop_app(). command(Module, Method, Args, ExpectedResponse) -> Response = apply(Module, Method, Args), ?_assertEqual(ExpectedResponse, Response). command_async(Module, Method, Args, ExpectedResponse) -> Pid = apply(Module, Method, Args), Response = consulerl_util:receive_response(?EVENT_RESPONSE), ok = consulerl_api:terminate(Pid), ok = consulerl_api:ensure_stopped(Pid), ?_assertEqual(ExpectedResponse, Response). command_async_twice(Module, Method, Args, ExpectedResponse) -> Pid = apply(Module, Method, Args), Response = consulerl_util:receive_response(?EVENT_RESPONSE), ok = apply(Module, Method, [Pid | Args]), Response2 = consulerl_util:receive_response(?EVENT_RESPONSE), ok = consulerl_api:terminate(Pid), [ ?_assertEqual(ExpectedResponse, Response), ?_assertEqual(ExpectedResponse, Response2) ]. exec(Dest, Ref, Status, Reason, Type, Response) -> Dest ! {hackney_response, Ref, {status, Status, Reason}}, Dest ! {hackney_response, Ref, {headers, [{<<"Content-Type">>, Type}]}}, Dest ! {hackney_response, Ref, Response}, Dest ! {hackney_response, Ref, done}, ok.
null
https://raw.githubusercontent.com/dieu/consulerl/a8c003dbc380911a1ad90a3468e60017aef38c79/test/consulerl_eunit.erl
erlang
API
-module(consulerl_eunit). -include("consulerl.hrl"). -include_lib("eunit/include/eunit.hrl"). -export([ setup_app/0, setup_httpc_200/1, setup_httpc_200/2, setup_httpc_200_plain/1, setup_httpc_404/0, setup_httpc_405/0, setup_httpc_409/1, setup_httpc_timeout/0, setup_error/0 ]). -export([ stop_app/0, stop_httpc/0, stop/1 ]). -export([ command/4, command_async/4, command_async_twice/4 ]). setup_app() -> {ok, _} = application:ensure_all_started(consulerl), ok. setup_httpc_200(Response) -> ok = meck:expect(hackney, request, fun(_, _, _, _, _) -> Ref = make_ref(), ok = exec(self(), Ref, 200, test, <<"application/json">>, Response), {ok, Ref} end). setup_httpc_200(Response, Timeout) -> ok = meck:expect(hackney, request, fun(_, _, _, _, _) -> Ref = make_ref(), Self = self(), timer:apply_after(Timeout, ?MODULE, exec, [Self, Ref, 200, test, <<"application/json">>, Response]), {ok, Ref} end). setup_httpc_200_plain(Response) -> ok = meck:expect(hackney, request, fun(_, _, _, _, _) -> Ref = make_ref(), ok = exec(self(), Ref, 200, test, <<"text/plain; charset=utf-8">>, Response), {ok, Ref} end). setup_httpc_404() -> ok = meck:expect(hackney, request, fun(_, _, _, _, _) -> Ref = make_ref(), ok = exec(self(), Ref, 404, "Not Found", <<"text/plain; charset=utf-8">>, <<>>), {ok, Ref} end). setup_httpc_405() -> ok = meck:expect(hackney, request, fun(_, _, _, _, _) -> Ref = make_ref(), ok = exec(self(), Ref, 405, "Method Not Allowed", <<"text/plain; charset=utf-8">>, <<>>), {ok, Ref} end). setup_httpc_409(Error) -> ok = meck:expect(hackney, request, fun(_, _, _, _, _) -> Ref = make_ref(), ok = exec(self(), Ref, 409, "Conflict", <<"application/json">>, Error), {ok, Ref} end). setup_httpc_timeout() -> ok = meck:expect(hackney, request, fun(_, _, _, _, _) -> Ref = make_ref(), {ok, Ref} end). setup_error() -> ok = meck:expect(hackney, request, fun(_, _, _, _, _) -> {error, error} end). stop_app() -> application:stop(consulerl). stop_httpc() -> ok = meck:unload(hackney). stop(_) -> ok = stop_httpc(), ok = stop_app(). command(Module, Method, Args, ExpectedResponse) -> Response = apply(Module, Method, Args), ?_assertEqual(ExpectedResponse, Response). command_async(Module, Method, Args, ExpectedResponse) -> Pid = apply(Module, Method, Args), Response = consulerl_util:receive_response(?EVENT_RESPONSE), ok = consulerl_api:terminate(Pid), ok = consulerl_api:ensure_stopped(Pid), ?_assertEqual(ExpectedResponse, Response). command_async_twice(Module, Method, Args, ExpectedResponse) -> Pid = apply(Module, Method, Args), Response = consulerl_util:receive_response(?EVENT_RESPONSE), ok = apply(Module, Method, [Pid | Args]), Response2 = consulerl_util:receive_response(?EVENT_RESPONSE), ok = consulerl_api:terminate(Pid), [ ?_assertEqual(ExpectedResponse, Response), ?_assertEqual(ExpectedResponse, Response2) ]. exec(Dest, Ref, Status, Reason, Type, Response) -> Dest ! {hackney_response, Ref, {status, Status, Reason}}, Dest ! {hackney_response, Ref, {headers, [{<<"Content-Type">>, Type}]}}, Dest ! {hackney_response, Ref, Response}, Dest ! {hackney_response, Ref, done}, ok.
b5c12487f7e11858f5769bc2701241269f1a9d2dcd39a2ac14b6101804e5ab06
anoma/juvix
IndexTable.hs
module Juvix.Compiler.Core.Translation.FromInternal.Data.IndexTable where import Data.HashMap.Strict qualified as HashMap import Juvix.Compiler.Abstract.Data.Name import Juvix.Compiler.Core.Language data IndexTable = IndexTable { _indexTableVarsNum :: Index, _indexTableVars :: HashMap NameId Index } makeLenses ''IndexTable initIndexTable :: IndexTable initIndexTable = IndexTable 0 mempty localAddName :: forall r a. (Member (Reader IndexTable) r) => Name -> Sem r a -> Sem r a localAddName n s = do updateFn <- update local updateFn s where update :: Sem r (IndexTable -> IndexTable) update = do idx <- asks (^. indexTableVarsNum) return ( over indexTableVars (HashMap.insert (n ^. nameId) idx) . over indexTableVarsNum (+ 1) )
null
https://raw.githubusercontent.com/anoma/juvix/807b3b1770289b8921304e92e7305c55c2e11f8f/src/Juvix/Compiler/Core/Translation/FromInternal/Data/IndexTable.hs
haskell
module Juvix.Compiler.Core.Translation.FromInternal.Data.IndexTable where import Data.HashMap.Strict qualified as HashMap import Juvix.Compiler.Abstract.Data.Name import Juvix.Compiler.Core.Language data IndexTable = IndexTable { _indexTableVarsNum :: Index, _indexTableVars :: HashMap NameId Index } makeLenses ''IndexTable initIndexTable :: IndexTable initIndexTable = IndexTable 0 mempty localAddName :: forall r a. (Member (Reader IndexTable) r) => Name -> Sem r a -> Sem r a localAddName n s = do updateFn <- update local updateFn s where update :: Sem r (IndexTable -> IndexTable) update = do idx <- asks (^. indexTableVarsNum) return ( over indexTableVars (HashMap.insert (n ^. nameId) idx) . over indexTableVarsNum (+ 1) )
71980104b644597068a151b26001288c6cc34ec29cc46e0c2e240b324efa8759
janestreet/core
day_of_week_intf.ml
* For representing a day of the week . open! Import module type Day_of_week = sig type t = | Sun | Mon | Tue | Wed | Thu | Fri | Sat [@@deriving bin_io, compare, hash, quickcheck, sexp, sexp_grammar, typerep] include Comparable.S_binable with type t := t include Hashable.S_binable with type t := t * [ of_string s ] accepts three - character abbreviations and full day names with any capitalization , and strings of the integers 0 - 6 . with any capitalization, and strings of the integers 0-6. *) include Stringable.S with type t := t * Capitalized full day names rather than all - caps 3 - letter abbreviations . val to_string_long : t -> string * These use the same mapping as [ Unix.tm_wday ] : 0 < - > Sun , ... 6 < - > Sat val of_int_exn : int -> t val of_int : int -> t option val to_int : t -> int * As per ISO 8601 , Mon->1 , , ... Sun->7 val iso_8601_weekday_number : t -> int (** [shift] goes forward (or backward) the specified number of days. *) val shift : t -> int -> t * [ num_days ~from ~to _ ] gives the number of days that must elapse from a [ from ] to get to a [ to _ ] , i.e. , the smallest non - negative number [ i ] such that [ shift from i = to _ ] . to a [to_], i.e., the smallest non-negative number [i] such that [shift from i = to_]. *) val num_days : from:t -> to_:t -> int val is_sun_or_sat : t -> bool val all : t list (** [ Mon; Tue; Wed; Thu; Fri ] *) val weekdays : t list (** [ Sat; Sun ] *) val weekends : t list module Stable : sig module V1 : sig type nonrec t = t [@@deriving bin_io, sexp, sexp_grammar, compare, hash, stable_witness] include Comparable.Stable.V1.With_stable_witness.S with type comparable := t with type comparator_witness := comparator_witness include Hashable.Stable.V1.With_stable_witness.S with type key := t end end end
null
https://raw.githubusercontent.com/janestreet/core/f382131ccdcb4a8cd21ebf9a49fa42dcf8183de6/core/src/day_of_week_intf.ml
ocaml
* [shift] goes forward (or backward) the specified number of days. * [ Mon; Tue; Wed; Thu; Fri ] * [ Sat; Sun ]
* For representing a day of the week . open! Import module type Day_of_week = sig type t = | Sun | Mon | Tue | Wed | Thu | Fri | Sat [@@deriving bin_io, compare, hash, quickcheck, sexp, sexp_grammar, typerep] include Comparable.S_binable with type t := t include Hashable.S_binable with type t := t * [ of_string s ] accepts three - character abbreviations and full day names with any capitalization , and strings of the integers 0 - 6 . with any capitalization, and strings of the integers 0-6. *) include Stringable.S with type t := t * Capitalized full day names rather than all - caps 3 - letter abbreviations . val to_string_long : t -> string * These use the same mapping as [ Unix.tm_wday ] : 0 < - > Sun , ... 6 < - > Sat val of_int_exn : int -> t val of_int : int -> t option val to_int : t -> int * As per ISO 8601 , Mon->1 , , ... Sun->7 val iso_8601_weekday_number : t -> int val shift : t -> int -> t * [ num_days ~from ~to _ ] gives the number of days that must elapse from a [ from ] to get to a [ to _ ] , i.e. , the smallest non - negative number [ i ] such that [ shift from i = to _ ] . to a [to_], i.e., the smallest non-negative number [i] such that [shift from i = to_]. *) val num_days : from:t -> to_:t -> int val is_sun_or_sat : t -> bool val all : t list val weekdays : t list val weekends : t list module Stable : sig module V1 : sig type nonrec t = t [@@deriving bin_io, sexp, sexp_grammar, compare, hash, stable_witness] include Comparable.Stable.V1.With_stable_witness.S with type comparable := t with type comparator_witness := comparator_witness include Hashable.Stable.V1.With_stable_witness.S with type key := t end end end
6714a4940296db8c1d8efb1d52a97a6759be060364b3ca298955ac1edba1e90e
jarcane/clojurice
core.clj
;;;; core.clj - app.core ;;; The main entry point for production application. (ns app.core (:gen-class) (:require [system.repl :refer [set-init! start]] [app.systems :as system])) (defn -main "The main entry point for production deployments." [& args] (set-init! #'system/prod-system) (start))
null
https://raw.githubusercontent.com/jarcane/clojurice/8fd899a5bbad918902d306c6aa28e3724a6e0bbe/src/clj/app/core.clj
clojure
core.clj - app.core The main entry point for production application.
(ns app.core (:gen-class) (:require [system.repl :refer [set-init! start]] [app.systems :as system])) (defn -main "The main entry point for production deployments." [& args] (set-init! #'system/prod-system) (start))
3cd54868416c444c8c6fe7de71b688c440b3a37c474b72fae86d8ff50da5361d
Incubaid/arakoon
compression_test.ml
Copyright ( 2010 - 2014 ) INCUBAID BVBA Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not use this file except in compliance with the License . You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing , software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . See the License for the specific language governing permissions and limitations under the License . Copyright (2010-2014) INCUBAID BVBA Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) open Compression open Lwt open Extra open OUnit open Tlogwriter open Update let section = Logger.Section.main let test_compress_file which () = let archive_name, compressor, _tlog_name = which in Logger.info Logger.Section.main "test_compress_file" >>= fun () -> let tlog_name = "/tmp/test_compress_file.tlog" in Lwt_io.with_file tlog_name ~mode:Lwt_io.output (fun oc -> let writer = new tlogWriter oc 0L in let rec loop i = if i = 100000L then Lwt.return () else begin let v = Printf.sprintf "<xml_bla>value%Li</xml_bla>" i in let updates = [Update.Set ("x", v)] in let value = Value.create_client_value updates false in writer # log_value i value >>= fun _ -> loop (Int64.succ i) end in loop 0L ) >>= fun () -> let arch_name = archive_name tlog_name in compress_tlog ~cancel:(ref false) tlog_name arch_name compressor >>= fun () -> let tlog2_name = _tlog_name arch_name in Logger.debug_f_ "comparing %s with %s" tlog2_name tlog_name >>= fun ()-> OUnit.assert_equal ~printer:(fun s -> s) tlog2_name tlog_name; let tlog_name' = (tlog_name ^".restored") in uncompress_tlog arch_name tlog_name' >>= fun () -> let md5 = Digest.file tlog_name in let md5' = Digest.file tlog_name' in OUnit.assert_equal md5 md5'; Lwt.return() let w= lwt_test_wrap let snappy = let archive_name x = x ^ ".tlx" and compressor = Compression.Snappy and tlog_name a = Filename.chop_extension a in (archive_name, compressor, tlog_name) let bz2 = let archive_name x = x ^ ".tlf" and compressor = Compression.Bz2 and tlog_name a = Filename.chop_extension a in (archive_name, compressor, tlog_name) let suite = "compression" >:::[ "file_bz2" >:: w (test_compress_file bz2); "file_snappy" >::w (test_compress_file snappy); ]
null
https://raw.githubusercontent.com/Incubaid/arakoon/43a8d0b26e4876ef91d9657149f105c7e57e0cb0/src/tlog/compression_test.ml
ocaml
Copyright ( 2010 - 2014 ) INCUBAID BVBA Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not use this file except in compliance with the License . You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing , software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . See the License for the specific language governing permissions and limitations under the License . Copyright (2010-2014) INCUBAID BVBA Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) open Compression open Lwt open Extra open OUnit open Tlogwriter open Update let section = Logger.Section.main let test_compress_file which () = let archive_name, compressor, _tlog_name = which in Logger.info Logger.Section.main "test_compress_file" >>= fun () -> let tlog_name = "/tmp/test_compress_file.tlog" in Lwt_io.with_file tlog_name ~mode:Lwt_io.output (fun oc -> let writer = new tlogWriter oc 0L in let rec loop i = if i = 100000L then Lwt.return () else begin let v = Printf.sprintf "<xml_bla>value%Li</xml_bla>" i in let updates = [Update.Set ("x", v)] in let value = Value.create_client_value updates false in writer # log_value i value >>= fun _ -> loop (Int64.succ i) end in loop 0L ) >>= fun () -> let arch_name = archive_name tlog_name in compress_tlog ~cancel:(ref false) tlog_name arch_name compressor >>= fun () -> let tlog2_name = _tlog_name arch_name in Logger.debug_f_ "comparing %s with %s" tlog2_name tlog_name >>= fun ()-> OUnit.assert_equal ~printer:(fun s -> s) tlog2_name tlog_name; let tlog_name' = (tlog_name ^".restored") in uncompress_tlog arch_name tlog_name' >>= fun () -> let md5 = Digest.file tlog_name in let md5' = Digest.file tlog_name' in OUnit.assert_equal md5 md5'; Lwt.return() let w= lwt_test_wrap let snappy = let archive_name x = x ^ ".tlx" and compressor = Compression.Snappy and tlog_name a = Filename.chop_extension a in (archive_name, compressor, tlog_name) let bz2 = let archive_name x = x ^ ".tlf" and compressor = Compression.Bz2 and tlog_name a = Filename.chop_extension a in (archive_name, compressor, tlog_name) let suite = "compression" >:::[ "file_bz2" >:: w (test_compress_file bz2); "file_snappy" >::w (test_compress_file snappy); ]
2c4748bdf6b9212cc605a083f912705d8082b0488f4d6cd14bb12c61f957792b
mfikes/fifth-postulate
ns22.cljs
(ns fifth-postulate.ns22) (defn solve-for01 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for02 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for03 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for04 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for05 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for06 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for07 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for08 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for09 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for10 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for11 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for12 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for13 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for14 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for15 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for16 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for17 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for18 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for19 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
null
https://raw.githubusercontent.com/mfikes/fifth-postulate/22cfd5f8c2b4a2dead1c15a96295bfeb4dba235e/src/fifth_postulate/ns22.cljs
clojure
(ns fifth-postulate.ns22) (defn solve-for01 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for02 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for03 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for04 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for05 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for06 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for07 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for08 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for09 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for10 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for11 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for12 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for13 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for14 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for15 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for16 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for17 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for18 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for19 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
6b5b66101fb4a1e79ac63f21588985ac4e3443edddf00ed680830f65756b9da4
sibylfs/sibylfs_src
check.ml
(****************************************************************************) Copyright ( c ) 2013 , 2014 , 2015 , , , , ( as part of the SibylFS project ) (* *) (* 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. *) (* *) Meta : (* - Headers maintained using headache. *) (* - License source: *) (****************************************************************************) (* check: read a trace file, and check that the transitions are allowed by the spec #directory "../../build_spec";; #directory "../../src_ext/lem/ocaml-lib/_build";; #use "topfind";; #require "unix";; #require "bigarray";; #require "num";; #require "str";; #require "sha";; #load "extract.cma";; #load "fs_spec_lib.cma";; *) open Fs_interface.Fs_spec_intf.Fs_types open Fs_interface.Fs_spec_intf.Fs_arch open Fs_spec_extras open CheckLib (******************************************************************************) (* command line *) let verbose = ref false let no_warnings = ref false let dry_run = ref false let no_root = ref true let out_file = ref (None : string option) let arch = ref None let files = ref ([]:string list) let seed = ref None let sexp_file = ref (None : string option) let options = Arg.align ([ ( "-v", Arg.Set verbose, " verbose output"); ( "-nw", Arg.Set no_warnings, " suppress warning messages"); ( "-n", Arg.Set dry_run, " dry-run (only parse and print)"); ( "--dry-run", Arg.Set dry_run, " dry-run (only parse and print)"); ( "--root", Arg.Clear no_root, " run process 1 with superuser permissions"); ( "-o", Arg.String (fun s -> out_file := Some s), " output file; converts input trace and stores it in given file"); ( "-arch", Arg.Symbol (["posix"; "linux"; "mac_os_x"; "freebsd"], (function | "linux" -> (arch := Some ARCH_LINUX) | "posix" -> (arch := Some ARCH_POSIX) | "mac_os_x" -> (arch := Some ARCH_MAC_OS_X) | "freebsd" -> (arch := Some ARCH_FREEBSD) | _ -> () (* can't happen *))), " architecture to simulate"); ( "--seed", Arg.Int (fun s -> seed := Some s), " use this integer for random seed"); ( "--sexp", Arg.String (fun s -> sexp_file := Some s), " output the result of the check to this file as an S expression"); ]) let usage_msg = ("check 0.4\n" ^ "Usage: check [OPTION]... [TRACE_FILE]... \n\ Example: check -v example_traces/os_trace1.txt\n\n\ check that the traces stored in the given trace-files are accepted by the POSIX specification.\n" ) let check_args () = let print_err m = print_endline ("Error: "^m); Arg.usage options usage_msg; exit 1 in if List.length (!files) = 0 then print_err "no trace-file given" else if (!out_file <> None) && (List.length (!files) > 1) then print_err "if option '-o' is used, only one trace-file can be processed" else if (!arch = None) then print_err "-arch required" let () = Arg.parse options (fun s -> (files := ((!files) @ [s]))) usage_msg; check_args () module C = CheckLib.Check_spec (* check_args enforces *) let arch = match !arch with Some a -> a | None -> assert false let spec_initial_state = CheckLib.spec_initial_state arch !no_root let comment s = let lines = Fs_test_util.split [] s '\n' in String.concat "\n" (List.map (fun l -> "# "^l) lines) let write_out o s = output_string o s; output_string o "\n"; flush o let outf o_ty s = match o_ty with | CO_error | CO_warning -> write_out stderr s; write_out stdout (comment s) | CO_verbose | CO_dump | CO_normal | CO_status -> write_out stdout s let outf = if !verbose then outf else drop_check_output_fun CO_verbose outf let outf = if !no_warnings then drop_check_output_fun CO_warning outf else outf let convert_trace = C.convert_trace arch outf spec_initial_state !dry_run calls can raise Parse_error from Fs_ast , Trace , or CheckLib ? let process_file f = try let tr = Trace.of_file arch f in match !out_file with | Some outfile -> fst (convert_trace tr Trace.TyTrace) | None -> if !dry_run then C.parse_print_trace_file arch outf f else Trace.(match tr with | TyScript, tr -> fst (convert_trace (TyScript,tr) TyTrace) | TyTrace, tr -> let (check, state_set) as r = C.process_trace spec_initial_state tr in (match !sexp_file with | None -> () | Some sexp -> let oc = open_out sexp in Sexplib.Sexp.output_hum oc (CheckLib.sexp_of_d_trace check); close_out oc ); C.print_check arch outf r ) with CheckLib.Exec_error msg -> outf CO_error ("\nFatal exec error: "^msg); exit 1 let multiple_files = (List.length (!files) > 1) let process_file_print filename = (match !seed with | None -> Random.self_init () | Some seed -> Random.init seed ); let o_ty = if multiple_files then CO_status else CO_verbose in outf o_ty ("# processing file '"^filename^"' ..."); ignore ((process_file filename) : bool); if multiple_files then (outf CO_status "\n"); ;; List.iter process_file_print (!files)
null
https://raw.githubusercontent.com/sibylfs/sibylfs_src/30675bc3b91e73f7133d0c30f18857bb1f4df8fa/fs_test/check.ml
ocaml
************************************************************************** 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. 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 PERFORMANCE OF THIS SOFTWARE. - Headers maintained using headache. - License source: ************************************************************************** check: read a trace file, and check that the transitions are allowed by the spec #directory "../../build_spec";; #directory "../../src_ext/lem/ocaml-lib/_build";; #use "topfind";; #require "unix";; #require "bigarray";; #require "num";; #require "str";; #require "sha";; #load "extract.cma";; #load "fs_spec_lib.cma";; **************************************************************************** command line can't happen check_args enforces
Copyright ( c ) 2013 , 2014 , 2015 , , , , ( as part of the SibylFS project ) THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL PROFITS , WHETHER IN AN ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF OR IN CONNECTION WITH THE USE OR Meta : open Fs_interface.Fs_spec_intf.Fs_types open Fs_interface.Fs_spec_intf.Fs_arch open Fs_spec_extras open CheckLib let verbose = ref false let no_warnings = ref false let dry_run = ref false let no_root = ref true let out_file = ref (None : string option) let arch = ref None let files = ref ([]:string list) let seed = ref None let sexp_file = ref (None : string option) let options = Arg.align ([ ( "-v", Arg.Set verbose, " verbose output"); ( "-nw", Arg.Set no_warnings, " suppress warning messages"); ( "-n", Arg.Set dry_run, " dry-run (only parse and print)"); ( "--dry-run", Arg.Set dry_run, " dry-run (only parse and print)"); ( "--root", Arg.Clear no_root, " run process 1 with superuser permissions"); ( "-o", Arg.String (fun s -> out_file := Some s), " output file; converts input trace and stores it in given file"); ( "-arch", Arg.Symbol (["posix"; "linux"; "mac_os_x"; "freebsd"], (function | "linux" -> (arch := Some ARCH_LINUX) | "posix" -> (arch := Some ARCH_POSIX) | "mac_os_x" -> (arch := Some ARCH_MAC_OS_X) | "freebsd" -> (arch := Some ARCH_FREEBSD) " architecture to simulate"); ( "--seed", Arg.Int (fun s -> seed := Some s), " use this integer for random seed"); ( "--sexp", Arg.String (fun s -> sexp_file := Some s), " output the result of the check to this file as an S expression"); ]) let usage_msg = ("check 0.4\n" ^ "Usage: check [OPTION]... [TRACE_FILE]... \n\ Example: check -v example_traces/os_trace1.txt\n\n\ check that the traces stored in the given trace-files are accepted by the POSIX specification.\n" ) let check_args () = let print_err m = print_endline ("Error: "^m); Arg.usage options usage_msg; exit 1 in if List.length (!files) = 0 then print_err "no trace-file given" else if (!out_file <> None) && (List.length (!files) > 1) then print_err "if option '-o' is used, only one trace-file can be processed" else if (!arch = None) then print_err "-arch required" let () = Arg.parse options (fun s -> (files := ((!files) @ [s]))) usage_msg; check_args () module C = CheckLib.Check_spec let arch = match !arch with Some a -> a | None -> assert false let spec_initial_state = CheckLib.spec_initial_state arch !no_root let comment s = let lines = Fs_test_util.split [] s '\n' in String.concat "\n" (List.map (fun l -> "# "^l) lines) let write_out o s = output_string o s; output_string o "\n"; flush o let outf o_ty s = match o_ty with | CO_error | CO_warning -> write_out stderr s; write_out stdout (comment s) | CO_verbose | CO_dump | CO_normal | CO_status -> write_out stdout s let outf = if !verbose then outf else drop_check_output_fun CO_verbose outf let outf = if !no_warnings then drop_check_output_fun CO_warning outf else outf let convert_trace = C.convert_trace arch outf spec_initial_state !dry_run calls can raise Parse_error from Fs_ast , Trace , or CheckLib ? let process_file f = try let tr = Trace.of_file arch f in match !out_file with | Some outfile -> fst (convert_trace tr Trace.TyTrace) | None -> if !dry_run then C.parse_print_trace_file arch outf f else Trace.(match tr with | TyScript, tr -> fst (convert_trace (TyScript,tr) TyTrace) | TyTrace, tr -> let (check, state_set) as r = C.process_trace spec_initial_state tr in (match !sexp_file with | None -> () | Some sexp -> let oc = open_out sexp in Sexplib.Sexp.output_hum oc (CheckLib.sexp_of_d_trace check); close_out oc ); C.print_check arch outf r ) with CheckLib.Exec_error msg -> outf CO_error ("\nFatal exec error: "^msg); exit 1 let multiple_files = (List.length (!files) > 1) let process_file_print filename = (match !seed with | None -> Random.self_init () | Some seed -> Random.init seed ); let o_ty = if multiple_files then CO_status else CO_verbose in outf o_ty ("# processing file '"^filename^"' ..."); ignore ((process_file filename) : bool); if multiple_files then (outf CO_status "\n"); ;; List.iter process_file_print (!files)
04876d97743c189326ebb8c20d694ed7903151049f0572e4ce82fe287baa1bf6
exoscale/clojure-kubernetes-client
v1beta1_volume_error.clj
(ns clojure-kubernetes-client.specs.v1beta1-volume-error (:require [clojure.spec.alpha :as s] [spec-tools.data-spec :as ds] ) (:import (java.io File))) (declare v1beta1-volume-error-data v1beta1-volume-error) (def v1beta1-volume-error-data { (ds/opt :message) string? (ds/opt :time) inst? }) (def v1beta1-volume-error (ds/spec {:name ::v1beta1-volume-error :spec v1beta1-volume-error-data}))
null
https://raw.githubusercontent.com/exoscale/clojure-kubernetes-client/79d84417f28d048c5ac015c17e3926c73e6ac668/src/clojure_kubernetes_client/specs/v1beta1_volume_error.clj
clojure
(ns clojure-kubernetes-client.specs.v1beta1-volume-error (:require [clojure.spec.alpha :as s] [spec-tools.data-spec :as ds] ) (:import (java.io File))) (declare v1beta1-volume-error-data v1beta1-volume-error) (def v1beta1-volume-error-data { (ds/opt :message) string? (ds/opt :time) inst? }) (def v1beta1-volume-error (ds/spec {:name ::v1beta1-volume-error :spec v1beta1-volume-error-data}))
43fb8d3e63976fb4af58dc3d6d9433c0718766ca07f55921c9be39dcebcc52b4
diagrams/diagrams-solve
Polynomial.hs
----------------------------------------------------------------------------- -- | -- Module : Diagrams.Solve.Polynomial Copyright : ( c ) 2011 - 2015 diagrams - solve team ( see LICENSE ) -- License : BSD-style (see LICENSE) -- Maintainer : -- Exact solving of low - degree ( n < = 4 ) polynomials . -- ----------------------------------------------------------------------------- module Diagrams.Solve.Polynomial ( quadForm , cubForm , quartForm , cubForm' , quartForm' ) where import Data.List (maximumBy) import Data.Ord (comparing) import Prelude hiding ((^)) import qualified Prelude as P ((^)) -- | The fundamental circle constant, /i.e./ ratio between a circle's -- circumference and radius. tau :: Floating a => a tau = 2*pi | A specialization of ( ^ ) to Integer c.f . -- for discussion. "The choice in (^) and (^^) to overload on the power 's Integral type ... was a genuinely bad idea . " - -- -- Note there are rewrite rules in GHC.Real to expand small exponents. (^) :: (Num a) => a -> Integer -> a (^) = (P.^) -- | Utility function used to avoid singularities aboutZero' :: (Ord a, Num a) => a -> a -> Bool aboutZero' toler x = abs x < toler # INLINE aboutZero ' # ------------------------------------------------------------ -- Quadratic formula ------------------------------------------------------------ -- | The quadratic formula. quadForm :: (Floating d, Ord d) => d -> d -> d -> [d] quadForm a b c -- There are infinitely many solutions in this case, -- so arbitrarily return 0 | a == 0 && b == 0 && c == 0 = [0] -- c /= 0 | a == 0 && b == 0 = [] -- linear | a == 0 = [-c/b] -- no real solutions | d < 0 = [] ax^2 + c = 0 | b == 0 = [sqrt (-c/a), -sqrt (-c/a)] multiplicity 2 solution | d == 0 = [-b/(2*a)] -- see -hd.mpg.de/astrophysik/HEA/internal/Numerical_Recipes/f5-6.pdf | otherwise = [q/a, c/q] where d = b^2 - 4*a*c q = -1/2*(b + signum b * sqrt d) # INLINE quadForm # _quadForm_prop :: Double -> Double -> Double -> Bool _quadForm_prop a b c = all (aboutZero' 1e-10 . eval) (quadForm a b c) where eval x = a*x^2 + b*x + c ------------------------------------------------------------ Cubic formula ------------------------------------------------------------ See #General_formula_of_roots | Solve the cubic equation ax^3 + bx^2 + cx + d = 0 , returning a list of all real roots . First argument is tolerance . cubForm' :: (Floating d, Ord d) => d -> d -> d -> d -> d -> [d] cubForm' toler a b c d | aboutZero' toler a = quadForm b c d three real roots , use trig method to avoid complex numbers | delta > 0 = map trig [0,1,2] one real root of multiplicity 3 | delta == 0 && disc == 0 = [ -b/(3*a) ] two real roots , one of multiplicity 2 | delta == 0 && disc /= 0 = [ (b*c - 9*a*d)/(2*disc) , (9*a^2*d - 4*a*b*c + b^3)/(a * disc) ] one real root ( and two complex ) | otherwise = [-b/(3*a) - cc/(3*a) + disc/(3*a*cc)] where delta = 18*a*b*c*d - 4*b^3*d + b^2*c^2 - 4*a*c^3 - 27*a^2*d^2 disc = 3*a*c - b^2 qq = sqrt(-27*(a^2)*delta) qq' = if abs (xx + qq) > abs (xx - qq) then qq else -qq cc = cubert (1/2*(qq' + xx)) xx = 2*b^3 - 9*a*b*c + 27*a^2*d p = disc/(3*a^2) q = xx/(27*a^3) phi = 1/3*acos(3*q/(2*p)*sqrt(-3/p)) trig k = 2 * sqrt(-p/3) * cos(phi - k*tau/3) - b/(3*a) cubert x | x < 0 = -((-x)**(1/3)) | otherwise = x**(1/3) # INLINE cubForm ' # | Solve the cubic equation ax^3 + bx^2 + cx + d = 0 , returning a -- list of all real roots within 1e-10 tolerance ( although currently it 's closer to 1e-5 ) cubForm :: (Floating d, Ord d) => d -> d -> d -> d -> [d] cubForm = cubForm' 1e-10 # INLINE cubForm # _cubForm_prop :: Double -> Double -> Double -> Double -> Bool _cubForm_prop a b c d = all (aboutZero' 1e-5 . eval) (cubForm a b c d) where eval x = a*x^3 + b*x^2 + c*x + d -- Basically, however large you set the tolerance it seems that quickcheck can always come up with examples where the returned solutions evaluate to something near zero -- but larger than the tolerance (but it takes it more -- tries the larger you set the tolerance). Wonder if this -- is an inherent limitation or (more likely) a problem -- with numerical stability. If this turns out to be an -- issue in practice we could, say, use the solutions -- generated here as very good guesses to a numerical -- solver which can give us a more precise answer? ------------------------------------------------------------ Quartic formula ------------------------------------------------------------ -- Based on -- as of 5/12/14, with help from -- | Solve the quartic equation c4 x^4 + c3 x^3 + c2 x^2 + c1 x + c0 = 0, returning a list of all real roots . First argument is tolerance . quartForm' :: (Floating d, Ord d) => d -> d -> d -> d -> d -> d -> [d] quartForm' toler c4 c3 c2 c1 c0 -- obvious cubic | aboutZero' toler c4 = cubForm c3 c2 c1 c0 -- x(ax^3+bx^2+cx+d) | aboutZero' toler c0 = 0 : cubForm c4 c3 c2 c1 -- substitute solutions of y back to x | otherwise = map (\x->x-(a/4)) roots where -- eliminate c4: x^4+ax^3+bx^2+cx+d [a,b,c,d] = map (/c4) [c3,c2,c1,c0] -- eliminate cubic term via x = y - a/4 reduced quartic : y^4 + py^2 + qy + r = 0 p = b - 3/8*a^2 q = 1/8*a^3-a*b/2+c r = (-3/256)*a^4+a^2*b/16-a*c/4+d -- | roots of the reduced quartic roots | aboutZero' toler r = no constant term : y(y^3 + py + q ) = 0 | u < -toler || v < -toler = [] -- no real solutions due to square root | otherwise = s1++s2 -- solutions of the quadratics -- solve the resolvent cubic - only one solution is needed z:_ = cubForm 1 (-p/2) (-r) (p*r/2 - q^2/8) solve the two quadratic equations y^2 ) u = z^2 - r v = 2*z - p u' = if aboutZero' toler u then 0 else sqrt u v' = if aboutZero' toler v then 0 else sqrt v s1 = quadForm 1 (if q<0 then -v' else v') (z-u') s2 = quadForm 1 (if q<0 then v' else -v') (z+u') {-# INLINE quartForm' #-} -- | Solve the quartic equation c4 x^4 + c3 x^3 + c2 x^2 + c1 x + c0 = 0, returning a -- list of all real roots within 1e-10 tolerance ( although currently it 's closer to 1e-5 ) quartForm :: (Floating d, Ord d) => d -> d -> d -> d -> d -> [d] quartForm = quartForm' 1e-10 # INLINE quartForm # _quartForm_prop :: Double -> Double -> Double -> Double -> Double -> Bool _quartForm_prop a b c d e = all (aboutZero' 1e-5 . eval) (quartForm a b c d e) where eval x = a*x^4 + b*x^3 + c*x^2 + d*x + e -- Same note about tolerance as for cubic
null
https://raw.githubusercontent.com/diagrams/diagrams-solve/c6fa6ab304cd155cb4e06ee607cb3f120ef22ee7/src/Diagrams/Solve/Polynomial.hs
haskell
--------------------------------------------------------------------------- | Module : Diagrams.Solve.Polynomial License : BSD-style (see LICENSE) Maintainer : --------------------------------------------------------------------------- | The fundamental circle constant, /i.e./ ratio between a circle's circumference and radius. for discussion. "The choice in (^) and (^^) to overload on the Note there are rewrite rules in GHC.Real to expand small exponents. | Utility function used to avoid singularities ---------------------------------------------------------- Quadratic formula ---------------------------------------------------------- | The quadratic formula. There are infinitely many solutions in this case, so arbitrarily return 0 c /= 0 linear no real solutions see -hd.mpg.de/astrophysik/HEA/internal/Numerical_Recipes/f5-6.pdf ---------------------------------------------------------- ---------------------------------------------------------- list of all real roots within 1e-10 tolerance Basically, however large you set the tolerance it seems but larger than the tolerance (but it takes it more tries the larger you set the tolerance). Wonder if this is an inherent limitation or (more likely) a problem with numerical stability. If this turns out to be an issue in practice we could, say, use the solutions generated here as very good guesses to a numerical solver which can give us a more precise answer? ---------------------------------------------------------- ---------------------------------------------------------- Based on as of 5/12/14, with help from | Solve the quartic equation c4 x^4 + c3 x^3 + c2 x^2 + c1 x + c0 = 0, returning a obvious cubic x(ax^3+bx^2+cx+d) substitute solutions of y back to x eliminate c4: x^4+ax^3+bx^2+cx+d eliminate cubic term via x = y - a/4 | roots of the reduced quartic no real solutions due to square root solutions of the quadratics solve the resolvent cubic - only one solution is needed # INLINE quartForm' # | Solve the quartic equation c4 x^4 + c3 x^3 + c2 x^2 + c1 x + c0 = 0, returning a list of all real roots within 1e-10 tolerance Same note about tolerance as for cubic
Copyright : ( c ) 2011 - 2015 diagrams - solve team ( see LICENSE ) Exact solving of low - degree ( n < = 4 ) polynomials . module Diagrams.Solve.Polynomial ( quadForm , cubForm , quartForm , cubForm' , quartForm' ) where import Data.List (maximumBy) import Data.Ord (comparing) import Prelude hiding ((^)) import qualified Prelude as P ((^)) tau :: Floating a => a tau = 2*pi | A specialization of ( ^ ) to Integer c.f . power 's Integral type ... was a genuinely bad idea . " - (^) :: (Num a) => a -> Integer -> a (^) = (P.^) aboutZero' :: (Ord a, Num a) => a -> a -> Bool aboutZero' toler x = abs x < toler # INLINE aboutZero ' # quadForm :: (Floating d, Ord d) => d -> d -> d -> [d] quadForm a b c | a == 0 && b == 0 && c == 0 = [0] | a == 0 && b == 0 = [] | a == 0 = [-c/b] | d < 0 = [] ax^2 + c = 0 | b == 0 = [sqrt (-c/a), -sqrt (-c/a)] multiplicity 2 solution | d == 0 = [-b/(2*a)] | otherwise = [q/a, c/q] where d = b^2 - 4*a*c q = -1/2*(b + signum b * sqrt d) # INLINE quadForm # _quadForm_prop :: Double -> Double -> Double -> Bool _quadForm_prop a b c = all (aboutZero' 1e-10 . eval) (quadForm a b c) where eval x = a*x^2 + b*x + c Cubic formula See #General_formula_of_roots | Solve the cubic equation ax^3 + bx^2 + cx + d = 0 , returning a list of all real roots . First argument is tolerance . cubForm' :: (Floating d, Ord d) => d -> d -> d -> d -> d -> [d] cubForm' toler a b c d | aboutZero' toler a = quadForm b c d three real roots , use trig method to avoid complex numbers | delta > 0 = map trig [0,1,2] one real root of multiplicity 3 | delta == 0 && disc == 0 = [ -b/(3*a) ] two real roots , one of multiplicity 2 | delta == 0 && disc /= 0 = [ (b*c - 9*a*d)/(2*disc) , (9*a^2*d - 4*a*b*c + b^3)/(a * disc) ] one real root ( and two complex ) | otherwise = [-b/(3*a) - cc/(3*a) + disc/(3*a*cc)] where delta = 18*a*b*c*d - 4*b^3*d + b^2*c^2 - 4*a*c^3 - 27*a^2*d^2 disc = 3*a*c - b^2 qq = sqrt(-27*(a^2)*delta) qq' = if abs (xx + qq) > abs (xx - qq) then qq else -qq cc = cubert (1/2*(qq' + xx)) xx = 2*b^3 - 9*a*b*c + 27*a^2*d p = disc/(3*a^2) q = xx/(27*a^3) phi = 1/3*acos(3*q/(2*p)*sqrt(-3/p)) trig k = 2 * sqrt(-p/3) * cos(phi - k*tau/3) - b/(3*a) cubert x | x < 0 = -((-x)**(1/3)) | otherwise = x**(1/3) # INLINE cubForm ' # | Solve the cubic equation ax^3 + bx^2 + cx + d = 0 , returning a ( although currently it 's closer to 1e-5 ) cubForm :: (Floating d, Ord d) => d -> d -> d -> d -> [d] cubForm = cubForm' 1e-10 # INLINE cubForm # _cubForm_prop :: Double -> Double -> Double -> Double -> Bool _cubForm_prop a b c d = all (aboutZero' 1e-5 . eval) (cubForm a b c d) where eval x = a*x^3 + b*x^2 + c*x + d that quickcheck can always come up with examples where the returned solutions evaluate to something near zero Quartic formula list of all real roots . First argument is tolerance . quartForm' :: (Floating d, Ord d) => d -> d -> d -> d -> d -> d -> [d] quartForm' toler c4 c3 c2 c1 c0 | aboutZero' toler c4 = cubForm c3 c2 c1 c0 | aboutZero' toler c0 = 0 : cubForm c4 c3 c2 c1 | otherwise = map (\x->x-(a/4)) roots where [a,b,c,d] = map (/c4) [c3,c2,c1,c0] reduced quartic : y^4 + py^2 + qy + r = 0 p = b - 3/8*a^2 q = 1/8*a^3-a*b/2+c r = (-3/256)*a^4+a^2*b/16-a*c/4+d roots | aboutZero' toler r = no constant term : y(y^3 + py + q ) = 0 z:_ = cubForm 1 (-p/2) (-r) (p*r/2 - q^2/8) solve the two quadratic equations y^2 ) u = z^2 - r v = 2*z - p u' = if aboutZero' toler u then 0 else sqrt u v' = if aboutZero' toler v then 0 else sqrt v s1 = quadForm 1 (if q<0 then -v' else v') (z-u') s2 = quadForm 1 (if q<0 then v' else -v') (z+u') ( although currently it 's closer to 1e-5 ) quartForm :: (Floating d, Ord d) => d -> d -> d -> d -> d -> [d] quartForm = quartForm' 1e-10 # INLINE quartForm # _quartForm_prop :: Double -> Double -> Double -> Double -> Double -> Bool _quartForm_prop a b c d e = all (aboutZero' 1e-5 . eval) (quartForm a b c d e) where eval x = a*x^4 + b*x^3 + c*x^2 + d*x + e
1f07b7d433589877db81f3e51a2e898e3c7fa2d91b37aac8f7b0b8708f8bd5f9
appliedfm/vstyle-tools
doctree.mli
class doc_node : Style_group.body_node -> object inherit Style.node val body : Style_group.body_node val css_margin : int val css_max_indent : int method load_style : style:Css.Types.Stylesheet.t -> ctx:Style.node list -> unit method styled_pp : ppf:Format.formatter -> ctx:Style.node list -> unit end;; type grouping = | GBody of Style_group.body_node | GComponent of Style_group.component_node exception WrongGrouping val as_grouping : grouping -> Style.grouping_node val as_body : grouping -> Style_group.body_node val as_component : grouping -> Style_group.component_node class doctree : object method get_stack_length : int method load_style : style:Css.Types.Stylesheet.t -> unit method styled_pp : ppf:Format.formatter -> unit method add_vernac : Proof.t option -> Vernacexpr.vernac_control_r CAst.t -> unit end;;
null
https://raw.githubusercontent.com/appliedfm/vstyle-tools/c639e5acff3fd1dfae6af423d7ce9bce9433f140/src/doctree.mli
ocaml
class doc_node : Style_group.body_node -> object inherit Style.node val body : Style_group.body_node val css_margin : int val css_max_indent : int method load_style : style:Css.Types.Stylesheet.t -> ctx:Style.node list -> unit method styled_pp : ppf:Format.formatter -> ctx:Style.node list -> unit end;; type grouping = | GBody of Style_group.body_node | GComponent of Style_group.component_node exception WrongGrouping val as_grouping : grouping -> Style.grouping_node val as_body : grouping -> Style_group.body_node val as_component : grouping -> Style_group.component_node class doctree : object method get_stack_length : int method load_style : style:Css.Types.Stylesheet.t -> unit method styled_pp : ppf:Format.formatter -> unit method add_vernac : Proof.t option -> Vernacexpr.vernac_control_r CAst.t -> unit end;;
14abcf894c7696e1e90ad20bfe3f374c9cf3ee18ae8e250806921eada563c7ae
inhabitedtype/ocaml-aws
modifyVpnConnection.mli
open Types type input = ModifyVpnConnectionRequest.t type output = ModifyVpnConnectionResult.t type error = Errors_internal.t include Aws.Call with type input := input and type output := output and type error := error
null
https://raw.githubusercontent.com/inhabitedtype/ocaml-aws/b6d5554c5d201202b5de8d0b0253871f7b66dab6/libraries/ec2/lib/modifyVpnConnection.mli
ocaml
open Types type input = ModifyVpnConnectionRequest.t type output = ModifyVpnConnectionResult.t type error = Errors_internal.t include Aws.Call with type input := input and type output := output and type error := error
692ea0dfe8c00be788882a87555e01bc9d621e93338c53bb643e46093629e0a8
ghc/ghc
FastString.hs
{-# LANGUAGE BangPatterns #-} # LANGUAGE CPP # {-# LANGUAGE DeriveDataTypeable #-} # LANGUAGE DerivingStrategies # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE MagicHash # # LANGUAGE UnboxedTuples # {-# LANGUAGE UnliftedFFITypes #-} {-# OPTIONS_GHC -O2 -funbox-strict-fields #-} -- We always optimise this, otherwise performance of a non-optimised -- compiler is severely affected -- | There are two principal string types used internally by GHC : -- [ ' FastString ' ] -- -- * A compact, hash-consed, representation of character strings. -- * Generated by 'fsLit'. -- * You can get a 'GHC.Types.Unique.Unique' from them. -- * Equality test is O(1) (it uses the Unique). -- * Comparison is O(1) or O(n): -- * O(n) but deterministic with lexical comparison (`lexicalCompareFS`) * O(1 ) but non - deterministic with Unique comparison ( ` uniqCompareFS ` ) * Turn into ' GHC.Utils . Outputable . SDoc ' with ' GHC.Utils.Outputable.ftext ' . -- [ ' PtrString ' ] -- -- * Pointer and size of a Latin-1 encoded string. -- * Practically no operations. -- * Outputting them is fast. -- * Generated by 'mkPtrString#'. * Length of string literals ( mkPtrString # " abc " # ) is computed statically * Turn into ' GHC.Utils . Outputable . SDoc ' with ' GHC.Utils.Outputable.ptext ' -- * Requires manual memory management. -- Improper use may lead to memory leaks or dangling pointers. -- * It assumes Latin-1 as the encoding, therefore it cannot represent arbitrary Unicode strings . -- Use ' PtrString ' unless you want the facilities of ' FastString ' . module GHC.Data.FastString ( * ByteString bytesFS, fastStringToByteString, mkFastStringByteString, fastZStringToByteString, unsafeMkByteString, * ShortByteString fastStringToShortByteString, mkFastStringShortByteString, -- * ShortText fastStringToShortText, -- * FastZString FastZString, hPutFZS, zString, zStringTakeN, lengthFZS, * FastString(..), -- not abstract, for now. NonDetFastString (..), LexicalFastString (..), -- ** Construction fsLit, mkFastString, mkFastStringBytes, mkFastStringByteList, mkFastString#, -- ** Deconstruction unpackFS, -- :: FastString -> String : : FastString - > Maybe ( , FastString ) -- ** Encoding zEncodeFS, -- ** Operations uniqueOfFS, lengthFS, nullFS, appendFS, concatFS, consFS, nilFS, lexicalCompareFS, uniqCompareFS, -- ** Outputting hPutFS, -- ** Internal getFastStringTable, getFastStringZEncCounter, * PtrStrings PtrString (..), -- ** Construction mkPtrString#, -- ** Deconstruction unpackPtrString, unpackPtrStringTakeN, -- ** Operations lengthPS ) where import GHC.Prelude.Basic as Prelude import GHC.Utils.Encoding import GHC.Utils.IO.Unsafe import GHC.Utils.Panic.Plain import GHC.Utils.Misc import GHC.Data.FastMutInt import Control.Concurrent.MVar import Control.DeepSeq import Control.Monad import Data.ByteString (ByteString) import Data.ByteString.Short (ShortByteString) import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as BSC import qualified Data.ByteString.Unsafe as BS import qualified Data.ByteString.Short as SBS #if !MIN_VERSION_bytestring(0,11,0) import qualified Data.ByteString.Short.Internal as SBS #endif import GHC.Data.ShortText (ShortText(..)) import Foreign.C import System.IO import Data.Data import Data.IORef import Data.Semigroup as Semi import Foreign #if MIN_VERSION_GLASGOW_HASKELL(9,3,0,0) import GHC.Conc.Sync (sharedCAF) #endif #if __GLASGOW_HASKELL__ < 811 import GHC.Base (unpackCString#,unpackNBytes#) #endif import GHC.Exts import GHC.IO | Gives the Modified UTF-8 encoded bytes corresponding to a ' FastString ' bytesFS, fastStringToByteString :: FastString -> ByteString {-# INLINE[1] bytesFS #-} bytesFS f = SBS.fromShort $ fs_sbs f {-# DEPRECATED fastStringToByteString "Use `bytesFS` instead" #-} fastStringToByteString = bytesFS fastStringToShortByteString :: FastString -> ShortByteString fastStringToShortByteString = fs_sbs fastStringToShortText :: FastString -> ShortText fastStringToShortText = ShortText . fs_sbs fastZStringToByteString :: FastZString -> ByteString fastZStringToByteString (FastZString bs) = bs -- This will drop information if any character > '\xFF' unsafeMkByteString :: String -> ByteString unsafeMkByteString = BSC.pack hashFastString :: FastString -> Int hashFastString fs = hashStr $ fs_sbs fs -- ----------------------------------------------------------------------------- newtype FastZString = FastZString ByteString deriving NFData hPutFZS :: Handle -> FastZString -> IO () hPutFZS handle (FastZString bs) = BS.hPut handle bs zString :: FastZString -> String zString (FastZString bs) = inlinePerformIO $ BS.unsafeUseAsCStringLen bs peekCAStringLen -- | @zStringTakeN n = 'take' n . 'zString'@ but is performed in \(O(\min(n , l))\ ) rather than \(O(l)\ ) , -- where \(l\) is the length of the 'FastZString'. zStringTakeN :: Int -> FastZString -> String zStringTakeN n (FastZString bs) = inlinePerformIO $ BS.unsafeUseAsCStringLen bs $ \(cp, len) -> peekCAStringLen (cp, min n len) lengthFZS :: FastZString -> Int lengthFZS (FastZString bs) = BS.length bs mkFastZStringString :: String -> FastZString mkFastZStringString str = FastZString (BSC.pack str) -- ----------------------------------------------------------------------------- | A ' FastString ' is a UTF-8 encoded string together with a unique ID . All ' FastString 's are stored in a global hashtable to support fast O(1 ) comparison . It is also associated with a lazy reference to the Z - encoding of this string which is used by the compiler internally . 'FastString's are stored in a global hashtable to support fast O(1) comparison. It is also associated with a lazy reference to the Z-encoding of this string which is used by the compiler internally. -} data FastString = FastString { uniq :: {-# UNPACK #-} !Int, -- unique id n_chars :: {-# UNPACK #-} !Int, -- number of chars fs_sbs :: {-# UNPACK #-} !ShortByteString, fs_zenc :: FastZString -- ^ Lazily computed Z-encoding of this string. See Note [Z-Encoding] in GHC.Utils . Encoding . -- Since ' FastString 's are globally memoized this is computed at most -- once for any given string. } instance Eq FastString where f1 == f2 = uniq f1 == uniq f2 We do n't provide any " Ord FastString " instance to force you to think about -- which ordering you want: * lexical : deterministic , O(n ) . LexicalFastString . * by unique : non - deterministic , O(1 ) . Cf uniqCompareFS and NonDetFastString . instance IsString FastString where fromString = fsLit instance Semi.Semigroup FastString where (<>) = appendFS instance Monoid FastString where mempty = nilFS mappend = (Semi.<>) mconcat = concatFS instance Show FastString where show fs = show (unpackFS fs) instance Data FastString where -- don't traverse? toConstr _ = abstractConstr "FastString" gunfold _ _ = error "gunfold" dataTypeOf _ = mkNoRepType "FastString" instance NFData FastString where rnf fs = seq fs () | Compare FastString lexically -- -- If you don't care about the lexical ordering, use `uniqCompareFS` instead. lexicalCompareFS :: FastString -> FastString -> Ordering lexicalCompareFS fs1 fs2 = if uniq fs1 == uniq fs2 then EQ else utf8CompareShortByteString (fs_sbs fs1) (fs_sbs fs2) -- perform a lexical comparison taking into account the Modified UTF-8 -- encoding we use (cf #18562) | Compare FastString by their Unique ( not lexically ) . -- -- Much cheaper than `lexicalCompareFS` but non-deterministic! uniqCompareFS :: FastString -> FastString -> Ordering uniqCompareFS fs1 fs2 = compare (uniq fs1) (uniq fs2) | Non - deterministic FastString -- This is a simple FastString wrapper with an instance using ` uniqCompareFS ` ( i.e. which compares FastStrings on their Uniques ) . Hence it is not deterministic from one run to the other . newtype NonDetFastString = NonDetFastString FastString deriving newtype (Eq, Show) deriving stock Data instance Ord NonDetFastString where compare (NonDetFastString fs1) (NonDetFastString fs2) = uniqCompareFS fs1 fs2 | Lexical FastString -- This is a simple FastString wrapper with an instance using ` lexicalCompareFS ` ( i.e. which compares FastStrings on their String representation ) . Hence it is deterministic from one run to the other . newtype LexicalFastString = LexicalFastString FastString deriving newtype (Eq, Show) deriving stock Data instance Ord LexicalFastString where compare (LexicalFastString fs1) (LexicalFastString fs2) = lexicalCompareFS fs1 fs2 -- ----------------------------------------------------------------------------- -- Construction Internally , the compiler will maintain a fast string symbol table , providing sharing and fast comparison . Creation of new @FastString@s then covertly does a lookup , re - using the @FastString@ if there was a hit . The design of the FastString hash table allows for lockless concurrent reads and updates to multiple buckets with low synchronization overhead . See Note [ Updating the FastString table ] on how it 's updated . Internally, the compiler will maintain a fast string symbol table, providing sharing and fast comparison. Creation of new @FastString@s then covertly does a lookup, re-using the @FastString@ if there was a hit. The design of the FastString hash table allows for lockless concurrent reads and updates to multiple buckets with low synchronization overhead. See Note [Updating the FastString table] on how it's updated. -} data FastStringTable = FastStringTable {-# UNPACK #-} !FastMutInt -- the unique ID counter shared with all buckets {-# UNPACK #-} !FastMutInt -- number of computed z-encodings for all buckets (Array# (IORef FastStringTableSegment)) -- concurrent segments data FastStringTableSegment = FastStringTableSegment {-# UNPACK #-} !(MVar ()) -- the lock for write in each segment {-# UNPACK #-} !FastMutInt -- the number of elements (MutableArray# RealWorld [FastString]) -- buckets in this segment Following parameters are determined based on : * Benchmark based on testsuite / tests / utils / should_run / T14854.hs * Stats of @echo : browse | ghc --interactive -dfaststring - stats > /dev / null@ : on 2018 - 10 - 24 , we have 13920 entries . Following parameters are determined based on: * Benchmark based on testsuite/tests/utils/should_run/T14854.hs * Stats of @echo :browse | ghc --interactive -dfaststring-stats >/dev/null@: on 2018-10-24, we have 13920 entries. -} segmentBits, numSegments, segmentMask, initialNumBuckets :: Int segmentBits = 8 numSegments = 256 -- bit segmentBits bit segmentBits - 1 initialNumBuckets = 64 hashToSegment# :: Int# -> Int# hashToSegment# hash# = hash# `andI#` segmentMask# where !(I# segmentMask#) = segmentMask hashToIndex# :: MutableArray# RealWorld [FastString] -> Int# -> Int# hashToIndex# buckets# hash# = (hash# `uncheckedIShiftRL#` segmentBits#) `remInt#` size# where !(I# segmentBits#) = segmentBits size# = sizeofMutableArray# buckets# maybeResizeSegment :: IORef FastStringTableSegment -> IO FastStringTableSegment maybeResizeSegment segmentRef = do segment@(FastStringTableSegment lock counter old#) <- readIORef segmentRef let oldSize# = sizeofMutableArray# old# newSize# = oldSize# *# 2# (I# n#) <- readFastMutInt counter maximum load of 1 then return segment else do resizedSegment@(FastStringTableSegment _ _ new#) <- IO $ \s1# -> case newArray# newSize# [] s1# of (# s2#, arr# #) -> (# s2#, FastStringTableSegment lock counter arr# #) forM_ [0 .. (I# oldSize#) - 1] $ \(I# i#) -> do fsList <- IO $ readArray# old# i# forM_ fsList $ \fs -> do Shall we store in hash value in FastString instead ? !(I# hash#) = hashFastString fs idx# = hashToIndex# new# hash# IO $ \s1# -> case readArray# new# idx# s1# of (# s2#, bucket #) -> case writeArray# new# idx# (fs: bucket) s2# of s3# -> (# s3#, () #) writeIORef segmentRef resizedSegment return resizedSegment # NOINLINE stringTable # stringTable :: FastStringTable stringTable = unsafePerformIO $ do let !(I# numSegments#) = numSegments !(I# initialNumBuckets#) = initialNumBuckets loop a# i# s1# | isTrue# (i# ==# numSegments#) = s1# | otherwise = case newMVar () `unIO` s1# of (# s2#, lock #) -> case newFastMutInt 0 `unIO` s2# of (# s3#, counter #) -> case newArray# initialNumBuckets# [] s3# of (# s4#, buckets# #) -> case newIORef (FastStringTableSegment lock counter buckets#) `unIO` s4# of (# s5#, segment #) -> case writeArray# a# i# segment s5# of s6# -> loop a# (i# +# 1#) s6# ord ' $ ' * 0x01000000 n_zencs <- newFastMutInt 0 tab <- IO $ \s1# -> case newArray# numSegments# (panic "string_table") s1# of (# s2#, arr# #) -> case loop arr# 0# s2# of s3# -> case unsafeFreezeArray# arr# s3# of (# s4#, segments# #) -> (# s4#, FastStringTable uid n_zencs segments# #) use the support wired into the RTS to share this CAF among all images of -- libHSghc #if !MIN_VERSION_GLASGOW_HASKELL(9,3,0,0) return tab #else sharedCAF tab getOrSetLibHSghcFastStringTable from the 9.3 RTS ; the previouss RTS before might not have this symbol . The right way to do this however would be to define some HAVE_FAST_STRING_TABLE -- or similar rather than use (odd parity) development versions. foreign import ccall unsafe "getOrSetLibHSghcFastStringTable" getOrSetLibHSghcFastStringTable :: Ptr a -> IO (Ptr a) #endif We include the FastString table in the ` sharedCAF ` mechanism because we 'd like created by a Core plugin to have the same uniques as corresponding strings created by the host compiler itself . For example , this allows plugins to lookup known names ( eg ` " MySpecialType " ` ) in the GlobalRdrEnv or even re - invoke the parser . In particular , the following little sanity test was failing in a plugin prototyping safe newtype - coercions : GHC.NT.Type . NT was imported , but could not be looked up /by the plugin/. let rdrName = mkModuleName " GHC.NT.Type " ` mkRdrQual ` " NT " putMsgS $ showSDoc dflags $ ppr $ lookupGRE_RdrName rdrName $ mg_rdr_env guts ` ` involves the lookup ( or creation ) of a FastString . Since the plugin 's FastString.string_table is empty , constructing the RdrName also allocates new uniques for the " GHC.NT.Type " and " NT " . These uniques are almost certainly unequal to the ones that the host compiler originally assigned to those FastStrings . Thus the lookup fails since the domain of the GlobalRdrEnv is affected by the RdrName 's OccName 's FastString 's unique . Maintaining synchronization of the two instances of this global is rather difficult because of the uses of ` unsafePerformIO ` in this module . Not synchronizing them risks breaking the rather major invariant that two FastStrings with the same unique have the same string . Thus we use the lower - level ` sharedCAF ` mechanism that relies on Globals.c . We include the FastString table in the `sharedCAF` mechanism because we'd like FastStrings created by a Core plugin to have the same uniques as corresponding strings created by the host compiler itself. For example, this allows plugins to lookup known names (eg `mkTcOcc "MySpecialType"`) in the GlobalRdrEnv or even re-invoke the parser. In particular, the following little sanity test was failing in a plugin prototyping safe newtype-coercions: GHC.NT.Type.NT was imported, but could not be looked up /by the plugin/. let rdrName = mkModuleName "GHC.NT.Type" `mkRdrQual` mkTcOcc "NT" putMsgS $ showSDoc dflags $ ppr $ lookupGRE_RdrName rdrName $ mg_rdr_env guts `mkTcOcc` involves the lookup (or creation) of a FastString. Since the plugin's FastString.string_table is empty, constructing the RdrName also allocates new uniques for the FastStrings "GHC.NT.Type" and "NT". These uniques are almost certainly unequal to the ones that the host compiler originally assigned to those FastStrings. Thus the lookup fails since the domain of the GlobalRdrEnv is affected by the RdrName's OccName's FastString's unique. Maintaining synchronization of the two instances of this global is rather difficult because of the uses of `unsafePerformIO` in this module. Not synchronizing them risks breaking the rather major invariant that two FastStrings with the same unique have the same string. Thus we use the lower-level `sharedCAF` mechanism that relies on Globals.c. -} mkFastString# :: Addr# -> FastString # INLINE mkFastString # # mkFastString# a# = mkFastStringBytes ptr (ptrStrLength ptr) where ptr = Ptr a# Note [ Updating the FastString table ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We use a concurrent hashtable which contains multiple segments , each hash value always maps to the same segment . Read is lock - free , write to the a segment should acquire a lock for that segment to avoid race condition , writes to different segments are independent . The procedure goes like this : 1 . Find out which segment to operate on based on the hash value 2 . Read the relevant bucket and perform a look up of the string . 3 . If it exists , return it . 4 . Otherwise grab a unique ID , create a new FastString and atomically attempt to update the relevant segment with this FastString : * Resize the segment by doubling the number of buckets when the number of FastStrings in this segment grows beyond the threshold . * Double check that the string is not in the bucket . Another thread may have inserted it while we were creating our string . * Return the existing FastString if it exists . The one we preemptively created will get GCed . * Otherwise , insert and return the string we created . ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We use a concurrent hashtable which contains multiple segments, each hash value always maps to the same segment. Read is lock-free, write to the a segment should acquire a lock for that segment to avoid race condition, writes to different segments are independent. The procedure goes like this: 1. Find out which segment to operate on based on the hash value 2. Read the relevant bucket and perform a look up of the string. 3. If it exists, return it. 4. Otherwise grab a unique ID, create a new FastString and atomically attempt to update the relevant segment with this FastString: * Resize the segment by doubling the number of buckets when the number of FastStrings in this segment grows beyond the threshold. * Double check that the string is not in the bucket. Another thread may have inserted it while we were creating our string. * Return the existing FastString if it exists. The one we preemptively created will get GCed. * Otherwise, insert and return the string we created. -} mkFastStringWith :: (Int -> FastMutInt-> IO FastString) -> ShortByteString -> IO FastString mkFastStringWith mk_fs sbs = do FastStringTableSegment lock _ buckets# <- readIORef segmentRef let idx# = hashToIndex# buckets# hash# bucket <- IO $ readArray# buckets# idx# case bucket_match bucket sbs of Just found -> return found Nothing -> do -- The withMVar below is not dupable. It can lead to deadlock if it is only run partially and putMVar is not called after takeMVar . noDuplicate n <- get_uid new_fs <- mk_fs n n_zencs withMVar lock $ \_ -> insert new_fs where !(FastStringTable uid n_zencs segments#) = stringTable get_uid = atomicFetchAddFastMut uid 1 !(I# hash#) = hashStr sbs (# segmentRef #) = indexArray# segments# (hashToSegment# hash#) insert fs = do FastStringTableSegment _ counter buckets# <- maybeResizeSegment segmentRef let idx# = hashToIndex# buckets# hash# bucket <- IO $ readArray# buckets# idx# case bucket_match bucket sbs of The FastString was added by another thread after previous read and -- before we acquired the write lock. Just found -> return found Nothing -> do IO $ \s1# -> case writeArray# buckets# idx# (fs : bucket) s1# of s2# -> (# s2#, () #) _ <- atomicFetchAddFastMut counter 1 return fs bucket_match :: [FastString] -> ShortByteString -> Maybe FastString bucket_match fs sbs = go fs where go [] = Nothing go (fs@(FastString {fs_sbs=fs_sbs}) : ls) | fs_sbs == sbs = Just fs | otherwise = go ls mkFastStringBytes :: Ptr Word8 -> Int -> FastString mkFastStringBytes !ptr !len = NB : Might as well use unsafeDupablePerformIO , since is -- idempotent. unsafeDupablePerformIO $ do sbs <- newSBSFromPtr ptr len mkFastStringWith (mkNewFastStringShortByteString sbs) sbs newSBSFromPtr :: Ptr a -> Int -> IO ShortByteString newSBSFromPtr (Ptr src#) (I# len#) = IO $ \s -> case newByteArray# len# s of { (# s, dst# #) -> case copyAddrToByteArray# src# dst# 0# len# s of { s -> case unsafeFreezeByteArray# dst# s of { (# s, ba# #) -> (# s, SBS.SBS ba# #) }}} | Create a ' FastString ' by copying an existing ' ByteString ' mkFastStringByteString :: ByteString -> FastString mkFastStringByteString bs = let sbs = SBS.toShort bs in inlinePerformIO $ mkFastStringWith (mkNewFastStringShortByteString sbs) sbs | Create a ' FastString ' from an existing ' ShortByteString ' without -- copying. mkFastStringShortByteString :: ShortByteString -> FastString mkFastStringShortByteString sbs = inlinePerformIO $ mkFastStringWith (mkNewFastStringShortByteString sbs) sbs | Creates a UTF-8 encoded ' FastString ' from a ' String ' mkFastString :: String -> FastString {-# NOINLINE[1] mkFastString #-} mkFastString str = inlinePerformIO $ do let !sbs = utf8EncodeShortByteString str mkFastStringWith (mkNewFastStringShortByteString sbs) sbs The following rule is used to avoid polluting the non - reclaimable FastString -- table with transient strings when we only want their encoding. # RULES " bytesFS / mkFastString " forall x. bytesFS ( ) = utf8EncodeByteString x # "bytesFS/mkFastString" forall x. bytesFS (mkFastString x) = utf8EncodeByteString x #-} | Creates a ' FastString ' from a UTF-8 encoded @[Word8]@ mkFastStringByteList :: [Word8] -> FastString mkFastStringByteList str = mkFastStringShortByteString (SBS.pack str) | Creates a ( lazy ) Z - encoded ' FastString ' from a ' ShortByteString ' and -- account the number of forced z-strings into the passed 'FastMutInt'. mkZFastString :: FastMutInt -> ShortByteString -> FastZString mkZFastString n_zencs sbs = unsafePerformIO $ do _ <- atomicFetchAddFastMut n_zencs 1 return $ mkFastZStringString (zEncodeString (utf8DecodeShortByteString sbs)) mkNewFastStringShortByteString :: ShortByteString -> Int -> FastMutInt -> IO FastString mkNewFastStringShortByteString sbs uid n_zencs = do let zstr = mkZFastString n_zencs sbs chars = utf8CountCharsShortByteString sbs return (FastString uid chars sbs zstr) hashStr :: ShortByteString -> Int -- produce a hash value between 0 & m (inclusive) hashStr sbs@(SBS.SBS ba#) = loop 0# 0# where !(I# len#) = SBS.length sbs loop h n = if isTrue# (n ==# len#) then I# h else let -- DO NOT move this let binding! indexCharOffAddr# reads from the -- pointer so we need to evaluate this based on the length check above . Not doing this right caused # 17909 . #if __GLASGOW_HASKELL__ >= 901 !c = int8ToInt# (indexInt8Array# ba# n) #else !c = indexInt8Array# ba# n #endif !h2 = (h *# 16777619#) `xorI#` c in loop h2 (n +# 1#) -- ----------------------------------------------------------------------------- Operations | Returns the length of the ' FastString ' in characters lengthFS :: FastString -> Int lengthFS fs = n_chars fs | Returns @True@ if the ' FastString ' is empty nullFS :: FastString -> Bool nullFS fs = SBS.null $ fs_sbs fs | Lazily unpacks and decodes the FastString unpackFS :: FastString -> String unpackFS fs = utf8DecodeShortByteString $ fs_sbs fs | Returns a Z - encoded version of a ' FastString ' . This might be the original , if it was already Z - encoded . The first time this function is applied to a particular ' FastString ' , the results are -- memoized. -- zEncodeFS :: FastString -> FastZString zEncodeFS fs = fs_zenc fs appendFS :: FastString -> FastString -> FastString appendFS fs1 fs2 = mkFastStringShortByteString $ (Semi.<>) (fs_sbs fs1) (fs_sbs fs2) concatFS :: [FastString] -> FastString concatFS = mkFastStringShortByteString . mconcat . map fs_sbs consFS :: Char -> FastString -> FastString consFS c fs = mkFastString (c : unpackFS fs) unconsFS :: FastString -> Maybe (Char, FastString) unconsFS fs = case unpackFS fs of [] -> Nothing (chr : str) -> Just (chr, mkFastString str) uniqueOfFS :: FastString -> Int uniqueOfFS fs = uniq fs nilFS :: FastString nilFS = mkFastString "" -- ----------------------------------------------------------------------------- -- Stats getFastStringTable :: IO [[[FastString]]] getFastStringTable = forM [0 .. numSegments - 1] $ \(I# i#) -> do let (# segmentRef #) = indexArray# segments# i# FastStringTableSegment _ _ buckets# <- readIORef segmentRef let bucketSize = I# (sizeofMutableArray# buckets#) forM [0 .. bucketSize - 1] $ \(I# j#) -> IO $ readArray# buckets# j# where !(FastStringTable _ _ segments#) = stringTable getFastStringZEncCounter :: IO Int getFastStringZEncCounter = readFastMutInt n_zencs where !(FastStringTable _ n_zencs _) = stringTable -- ----------------------------------------------------------------------------- Outputting ' FastString 's |Outputs a ' FastString ' with /no decoding at all/ , that is , you get the actual bytes in the ' FastString ' written to the ' Handle ' . hPutFS :: Handle -> FastString -> IO () hPutFS handle fs = BS.hPut handle $ bytesFS fs ToDo : we 'll probably want an hPutFSLocal , or something , to output -- in the current locale's encoding (for error messages and suchlike). -- ----------------------------------------------------------------------------- PtrStrings , here for convenience only . | A ' PtrString ' is a pointer to some array of Latin-1 encoded chars . data PtrString = PtrString !(Ptr Word8) !Int | Wrap an unboxed address into a ' PtrString ' . mkPtrString# :: Addr# -> PtrString # INLINE mkPtrString # # mkPtrString# a# = PtrString (Ptr a#) (ptrStrLength (Ptr a#)) | Decode a ' PtrString ' back into a ' String ' using Latin-1 encoding . This does not free the memory associated with ' PtrString ' . unpackPtrString :: PtrString -> String unpackPtrString (PtrString (Ptr p#) (I# n#)) = unpackNBytes# p# n# -- | @unpackPtrStringTakeN n = 'take' n . 'unpackPtrString'@ but is performed in \(O(\min(n , l))\ ) rather than \(O(l)\ ) , where \(l\ ) is the length of the ' PtrString ' . unpackPtrStringTakeN :: Int -> PtrString -> String unpackPtrStringTakeN n (PtrString (Ptr p#) len) = case min n len of I# n# -> unpackNBytes# p# n# | Return the length of a ' PtrString ' lengthPS :: PtrString -> Int lengthPS (PtrString _ n) = n -- ----------------------------------------------------------------------------- -- under the carpet #if !MIN_VERSION_GLASGOW_HASKELL(9,0,0,0) foreign import ccall unsafe "strlen" cstringLength# :: Addr# -> Int# #endif ptrStrLength :: Ptr Word8 -> Int # INLINE ptrStrLength # ptrStrLength (Ptr a) = I# (cstringLength# a) # NOINLINE fsLit # fsLit :: String -> FastString fsLit x = mkFastString x # RULES " fslit " forall x . fsLit ( unpackCString # x ) = mkFastString # x # forall x . fsLit (unpackCString# x) = mkFastString# x #-}
null
https://raw.githubusercontent.com/ghc/ghc/93f0e3c49cea484bd6e838892ff8702ec51f34c3/compiler/GHC/Data/FastString.hs
haskell
# LANGUAGE BangPatterns # # LANGUAGE DeriveDataTypeable # # LANGUAGE UnliftedFFITypes # # OPTIONS_GHC -O2 -funbox-strict-fields # We always optimise this, otherwise performance of a non-optimised compiler is severely affected | * A compact, hash-consed, representation of character strings. * Generated by 'fsLit'. * You can get a 'GHC.Types.Unique.Unique' from them. * Equality test is O(1) (it uses the Unique). * Comparison is O(1) or O(n): * O(n) but deterministic with lexical comparison (`lexicalCompareFS`) * Pointer and size of a Latin-1 encoded string. * Practically no operations. * Outputting them is fast. * Generated by 'mkPtrString#'. * Requires manual memory management. Improper use may lead to memory leaks or dangling pointers. * It assumes Latin-1 as the encoding, therefore it cannot represent * ShortText * FastZString not abstract, for now. ** Construction ** Deconstruction :: FastString -> String ** Encoding ** Operations ** Outputting ** Internal ** Construction ** Deconstruction ** Operations # INLINE[1] bytesFS # # DEPRECATED fastStringToByteString "Use `bytesFS` instead" # This will drop information if any character > '\xFF' ----------------------------------------------------------------------------- | @zStringTakeN n = 'take' n . 'zString'@ where \(l\) is the length of the 'FastZString'. ----------------------------------------------------------------------------- # UNPACK # unique id # UNPACK # number of chars # UNPACK # ^ Lazily computed Z-encoding of this string. See Note [Z-Encoding] in once for any given string. which ordering you want: don't traverse? If you don't care about the lexical ordering, use `uniqCompareFS` instead. perform a lexical comparison taking into account the Modified UTF-8 encoding we use (cf #18562) Much cheaper than `lexicalCompareFS` but non-deterministic! ----------------------------------------------------------------------------- Construction # UNPACK # the unique ID counter shared with all buckets # UNPACK # number of computed z-encodings for all buckets concurrent segments # UNPACK # the lock for write in each segment # UNPACK # the number of elements buckets in this segment interactive -dfaststring - stats > /dev / null@ : interactive -dfaststring-stats >/dev/null@: bit segmentBits libHSghc or similar rather than use (odd parity) development versions. The withMVar below is not dupable. It can lead to deadlock if it is before we acquired the write lock. idempotent. copying. # NOINLINE[1] mkFastString # table with transient strings when we only want their encoding. account the number of forced z-strings into the passed 'FastMutInt'. produce a hash value between 0 & m (inclusive) DO NOT move this let binding! indexCharOffAddr# reads from the pointer so we need to evaluate this based on the length check ----------------------------------------------------------------------------- memoized. ----------------------------------------------------------------------------- Stats ----------------------------------------------------------------------------- in the current locale's encoding (for error messages and suchlike). ----------------------------------------------------------------------------- | @unpackPtrStringTakeN n = 'take' n . 'unpackPtrString'@ ----------------------------------------------------------------------------- under the carpet
# LANGUAGE CPP # # LANGUAGE DerivingStrategies # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE MagicHash # # LANGUAGE UnboxedTuples # There are two principal string types used internally by GHC : [ ' FastString ' ] * O(1 ) but non - deterministic with Unique comparison ( ` uniqCompareFS ` ) * Turn into ' GHC.Utils . Outputable . SDoc ' with ' GHC.Utils.Outputable.ftext ' . [ ' PtrString ' ] * Length of string literals ( mkPtrString # " abc " # ) is computed statically * Turn into ' GHC.Utils . Outputable . SDoc ' with ' GHC.Utils.Outputable.ptext ' arbitrary Unicode strings . Use ' PtrString ' unless you want the facilities of ' FastString ' . module GHC.Data.FastString ( * ByteString bytesFS, fastStringToByteString, mkFastStringByteString, fastZStringToByteString, unsafeMkByteString, * ShortByteString fastStringToShortByteString, mkFastStringShortByteString, fastStringToShortText, FastZString, hPutFZS, zString, zStringTakeN, lengthFZS, * NonDetFastString (..), LexicalFastString (..), fsLit, mkFastString, mkFastStringBytes, mkFastStringByteList, mkFastString#, : : FastString - > Maybe ( , FastString ) zEncodeFS, uniqueOfFS, lengthFS, nullFS, appendFS, concatFS, consFS, nilFS, lexicalCompareFS, uniqCompareFS, hPutFS, getFastStringTable, getFastStringZEncCounter, * PtrStrings PtrString (..), mkPtrString#, unpackPtrString, unpackPtrStringTakeN, lengthPS ) where import GHC.Prelude.Basic as Prelude import GHC.Utils.Encoding import GHC.Utils.IO.Unsafe import GHC.Utils.Panic.Plain import GHC.Utils.Misc import GHC.Data.FastMutInt import Control.Concurrent.MVar import Control.DeepSeq import Control.Monad import Data.ByteString (ByteString) import Data.ByteString.Short (ShortByteString) import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as BSC import qualified Data.ByteString.Unsafe as BS import qualified Data.ByteString.Short as SBS #if !MIN_VERSION_bytestring(0,11,0) import qualified Data.ByteString.Short.Internal as SBS #endif import GHC.Data.ShortText (ShortText(..)) import Foreign.C import System.IO import Data.Data import Data.IORef import Data.Semigroup as Semi import Foreign #if MIN_VERSION_GLASGOW_HASKELL(9,3,0,0) import GHC.Conc.Sync (sharedCAF) #endif #if __GLASGOW_HASKELL__ < 811 import GHC.Base (unpackCString#,unpackNBytes#) #endif import GHC.Exts import GHC.IO | Gives the Modified UTF-8 encoded bytes corresponding to a ' FastString ' bytesFS, fastStringToByteString :: FastString -> ByteString bytesFS f = SBS.fromShort $ fs_sbs f fastStringToByteString = bytesFS fastStringToShortByteString :: FastString -> ShortByteString fastStringToShortByteString = fs_sbs fastStringToShortText :: FastString -> ShortText fastStringToShortText = ShortText . fs_sbs fastZStringToByteString :: FastZString -> ByteString fastZStringToByteString (FastZString bs) = bs unsafeMkByteString :: String -> ByteString unsafeMkByteString = BSC.pack hashFastString :: FastString -> Int hashFastString fs = hashStr $ fs_sbs fs newtype FastZString = FastZString ByteString deriving NFData hPutFZS :: Handle -> FastZString -> IO () hPutFZS handle (FastZString bs) = BS.hPut handle bs zString :: FastZString -> String zString (FastZString bs) = inlinePerformIO $ BS.unsafeUseAsCStringLen bs peekCAStringLen but is performed in \(O(\min(n , l))\ ) rather than \(O(l)\ ) , zStringTakeN :: Int -> FastZString -> String zStringTakeN n (FastZString bs) = inlinePerformIO $ BS.unsafeUseAsCStringLen bs $ \(cp, len) -> peekCAStringLen (cp, min n len) lengthFZS :: FastZString -> Int lengthFZS (FastZString bs) = BS.length bs mkFastZStringString :: String -> FastZString mkFastZStringString str = FastZString (BSC.pack str) | A ' FastString ' is a UTF-8 encoded string together with a unique ID . All ' FastString 's are stored in a global hashtable to support fast O(1 ) comparison . It is also associated with a lazy reference to the Z - encoding of this string which is used by the compiler internally . 'FastString's are stored in a global hashtable to support fast O(1) comparison. It is also associated with a lazy reference to the Z-encoding of this string which is used by the compiler internally. -} data FastString = FastString { fs_zenc :: FastZString GHC.Utils . Encoding . Since ' FastString 's are globally memoized this is computed at most } instance Eq FastString where f1 == f2 = uniq f1 == uniq f2 We do n't provide any " Ord FastString " instance to force you to think about * lexical : deterministic , O(n ) . LexicalFastString . * by unique : non - deterministic , O(1 ) . Cf uniqCompareFS and NonDetFastString . instance IsString FastString where fromString = fsLit instance Semi.Semigroup FastString where (<>) = appendFS instance Monoid FastString where mempty = nilFS mappend = (Semi.<>) mconcat = concatFS instance Show FastString where show fs = show (unpackFS fs) instance Data FastString where toConstr _ = abstractConstr "FastString" gunfold _ _ = error "gunfold" dataTypeOf _ = mkNoRepType "FastString" instance NFData FastString where rnf fs = seq fs () | Compare FastString lexically lexicalCompareFS :: FastString -> FastString -> Ordering lexicalCompareFS fs1 fs2 = if uniq fs1 == uniq fs2 then EQ else utf8CompareShortByteString (fs_sbs fs1) (fs_sbs fs2) | Compare FastString by their Unique ( not lexically ) . uniqCompareFS :: FastString -> FastString -> Ordering uniqCompareFS fs1 fs2 = compare (uniq fs1) (uniq fs2) | Non - deterministic FastString This is a simple FastString wrapper with an instance using ` uniqCompareFS ` ( i.e. which compares FastStrings on their Uniques ) . Hence it is not deterministic from one run to the other . newtype NonDetFastString = NonDetFastString FastString deriving newtype (Eq, Show) deriving stock Data instance Ord NonDetFastString where compare (NonDetFastString fs1) (NonDetFastString fs2) = uniqCompareFS fs1 fs2 | Lexical FastString This is a simple FastString wrapper with an instance using ` lexicalCompareFS ` ( i.e. which compares FastStrings on their String representation ) . Hence it is deterministic from one run to the other . newtype LexicalFastString = LexicalFastString FastString deriving newtype (Eq, Show) deriving stock Data instance Ord LexicalFastString where compare (LexicalFastString fs1) (LexicalFastString fs2) = lexicalCompareFS fs1 fs2 Internally , the compiler will maintain a fast string symbol table , providing sharing and fast comparison . Creation of new @FastString@s then covertly does a lookup , re - using the @FastString@ if there was a hit . The design of the FastString hash table allows for lockless concurrent reads and updates to multiple buckets with low synchronization overhead . See Note [ Updating the FastString table ] on how it 's updated . Internally, the compiler will maintain a fast string symbol table, providing sharing and fast comparison. Creation of new @FastString@s then covertly does a lookup, re-using the @FastString@ if there was a hit. The design of the FastString hash table allows for lockless concurrent reads and updates to multiple buckets with low synchronization overhead. See Note [Updating the FastString table] on how it's updated. -} data FastStringTable = FastStringTable data FastStringTableSegment = FastStringTableSegment Following parameters are determined based on : * Benchmark based on testsuite / tests / utils / should_run / T14854.hs on 2018 - 10 - 24 , we have 13920 entries . Following parameters are determined based on: * Benchmark based on testsuite/tests/utils/should_run/T14854.hs on 2018-10-24, we have 13920 entries. -} segmentBits, numSegments, segmentMask, initialNumBuckets :: Int segmentBits = 8 bit segmentBits - 1 initialNumBuckets = 64 hashToSegment# :: Int# -> Int# hashToSegment# hash# = hash# `andI#` segmentMask# where !(I# segmentMask#) = segmentMask hashToIndex# :: MutableArray# RealWorld [FastString] -> Int# -> Int# hashToIndex# buckets# hash# = (hash# `uncheckedIShiftRL#` segmentBits#) `remInt#` size# where !(I# segmentBits#) = segmentBits size# = sizeofMutableArray# buckets# maybeResizeSegment :: IORef FastStringTableSegment -> IO FastStringTableSegment maybeResizeSegment segmentRef = do segment@(FastStringTableSegment lock counter old#) <- readIORef segmentRef let oldSize# = sizeofMutableArray# old# newSize# = oldSize# *# 2# (I# n#) <- readFastMutInt counter maximum load of 1 then return segment else do resizedSegment@(FastStringTableSegment _ _ new#) <- IO $ \s1# -> case newArray# newSize# [] s1# of (# s2#, arr# #) -> (# s2#, FastStringTableSegment lock counter arr# #) forM_ [0 .. (I# oldSize#) - 1] $ \(I# i#) -> do fsList <- IO $ readArray# old# i# forM_ fsList $ \fs -> do Shall we store in hash value in FastString instead ? !(I# hash#) = hashFastString fs idx# = hashToIndex# new# hash# IO $ \s1# -> case readArray# new# idx# s1# of (# s2#, bucket #) -> case writeArray# new# idx# (fs: bucket) s2# of s3# -> (# s3#, () #) writeIORef segmentRef resizedSegment return resizedSegment # NOINLINE stringTable # stringTable :: FastStringTable stringTable = unsafePerformIO $ do let !(I# numSegments#) = numSegments !(I# initialNumBuckets#) = initialNumBuckets loop a# i# s1# | isTrue# (i# ==# numSegments#) = s1# | otherwise = case newMVar () `unIO` s1# of (# s2#, lock #) -> case newFastMutInt 0 `unIO` s2# of (# s3#, counter #) -> case newArray# initialNumBuckets# [] s3# of (# s4#, buckets# #) -> case newIORef (FastStringTableSegment lock counter buckets#) `unIO` s4# of (# s5#, segment #) -> case writeArray# a# i# segment s5# of s6# -> loop a# (i# +# 1#) s6# ord ' $ ' * 0x01000000 n_zencs <- newFastMutInt 0 tab <- IO $ \s1# -> case newArray# numSegments# (panic "string_table") s1# of (# s2#, arr# #) -> case loop arr# 0# s2# of s3# -> case unsafeFreezeArray# arr# s3# of (# s4#, segments# #) -> (# s4#, FastStringTable uid n_zencs segments# #) use the support wired into the RTS to share this CAF among all images of #if !MIN_VERSION_GLASGOW_HASKELL(9,3,0,0) return tab #else sharedCAF tab getOrSetLibHSghcFastStringTable from the 9.3 RTS ; the previouss RTS before might not have this symbol . The right way to do this however would be to define some HAVE_FAST_STRING_TABLE foreign import ccall unsafe "getOrSetLibHSghcFastStringTable" getOrSetLibHSghcFastStringTable :: Ptr a -> IO (Ptr a) #endif We include the FastString table in the ` sharedCAF ` mechanism because we 'd like created by a Core plugin to have the same uniques as corresponding strings created by the host compiler itself . For example , this allows plugins to lookup known names ( eg ` " MySpecialType " ` ) in the GlobalRdrEnv or even re - invoke the parser . In particular , the following little sanity test was failing in a plugin prototyping safe newtype - coercions : GHC.NT.Type . NT was imported , but could not be looked up /by the plugin/. let rdrName = mkModuleName " GHC.NT.Type " ` mkRdrQual ` " NT " putMsgS $ showSDoc dflags $ ppr $ lookupGRE_RdrName rdrName $ mg_rdr_env guts ` ` involves the lookup ( or creation ) of a FastString . Since the plugin 's FastString.string_table is empty , constructing the RdrName also allocates new uniques for the " GHC.NT.Type " and " NT " . These uniques are almost certainly unequal to the ones that the host compiler originally assigned to those FastStrings . Thus the lookup fails since the domain of the GlobalRdrEnv is affected by the RdrName 's OccName 's FastString 's unique . Maintaining synchronization of the two instances of this global is rather difficult because of the uses of ` unsafePerformIO ` in this module . Not synchronizing them risks breaking the rather major invariant that two FastStrings with the same unique have the same string . Thus we use the lower - level ` sharedCAF ` mechanism that relies on Globals.c . We include the FastString table in the `sharedCAF` mechanism because we'd like FastStrings created by a Core plugin to have the same uniques as corresponding strings created by the host compiler itself. For example, this allows plugins to lookup known names (eg `mkTcOcc "MySpecialType"`) in the GlobalRdrEnv or even re-invoke the parser. In particular, the following little sanity test was failing in a plugin prototyping safe newtype-coercions: GHC.NT.Type.NT was imported, but could not be looked up /by the plugin/. let rdrName = mkModuleName "GHC.NT.Type" `mkRdrQual` mkTcOcc "NT" putMsgS $ showSDoc dflags $ ppr $ lookupGRE_RdrName rdrName $ mg_rdr_env guts `mkTcOcc` involves the lookup (or creation) of a FastString. Since the plugin's FastString.string_table is empty, constructing the RdrName also allocates new uniques for the FastStrings "GHC.NT.Type" and "NT". These uniques are almost certainly unequal to the ones that the host compiler originally assigned to those FastStrings. Thus the lookup fails since the domain of the GlobalRdrEnv is affected by the RdrName's OccName's FastString's unique. Maintaining synchronization of the two instances of this global is rather difficult because of the uses of `unsafePerformIO` in this module. Not synchronizing them risks breaking the rather major invariant that two FastStrings with the same unique have the same string. Thus we use the lower-level `sharedCAF` mechanism that relies on Globals.c. -} mkFastString# :: Addr# -> FastString # INLINE mkFastString # # mkFastString# a# = mkFastStringBytes ptr (ptrStrLength ptr) where ptr = Ptr a# Note [ Updating the FastString table ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We use a concurrent hashtable which contains multiple segments , each hash value always maps to the same segment . Read is lock - free , write to the a segment should acquire a lock for that segment to avoid race condition , writes to different segments are independent . The procedure goes like this : 1 . Find out which segment to operate on based on the hash value 2 . Read the relevant bucket and perform a look up of the string . 3 . If it exists , return it . 4 . Otherwise grab a unique ID , create a new FastString and atomically attempt to update the relevant segment with this FastString : * Resize the segment by doubling the number of buckets when the number of FastStrings in this segment grows beyond the threshold . * Double check that the string is not in the bucket . Another thread may have inserted it while we were creating our string . * Return the existing FastString if it exists . The one we preemptively created will get GCed . * Otherwise , insert and return the string we created . ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We use a concurrent hashtable which contains multiple segments, each hash value always maps to the same segment. Read is lock-free, write to the a segment should acquire a lock for that segment to avoid race condition, writes to different segments are independent. The procedure goes like this: 1. Find out which segment to operate on based on the hash value 2. Read the relevant bucket and perform a look up of the string. 3. If it exists, return it. 4. Otherwise grab a unique ID, create a new FastString and atomically attempt to update the relevant segment with this FastString: * Resize the segment by doubling the number of buckets when the number of FastStrings in this segment grows beyond the threshold. * Double check that the string is not in the bucket. Another thread may have inserted it while we were creating our string. * Return the existing FastString if it exists. The one we preemptively created will get GCed. * Otherwise, insert and return the string we created. -} mkFastStringWith :: (Int -> FastMutInt-> IO FastString) -> ShortByteString -> IO FastString mkFastStringWith mk_fs sbs = do FastStringTableSegment lock _ buckets# <- readIORef segmentRef let idx# = hashToIndex# buckets# hash# bucket <- IO $ readArray# buckets# idx# case bucket_match bucket sbs of Just found -> return found Nothing -> do only run partially and putMVar is not called after takeMVar . noDuplicate n <- get_uid new_fs <- mk_fs n n_zencs withMVar lock $ \_ -> insert new_fs where !(FastStringTable uid n_zencs segments#) = stringTable get_uid = atomicFetchAddFastMut uid 1 !(I# hash#) = hashStr sbs (# segmentRef #) = indexArray# segments# (hashToSegment# hash#) insert fs = do FastStringTableSegment _ counter buckets# <- maybeResizeSegment segmentRef let idx# = hashToIndex# buckets# hash# bucket <- IO $ readArray# buckets# idx# case bucket_match bucket sbs of The FastString was added by another thread after previous read and Just found -> return found Nothing -> do IO $ \s1# -> case writeArray# buckets# idx# (fs : bucket) s1# of s2# -> (# s2#, () #) _ <- atomicFetchAddFastMut counter 1 return fs bucket_match :: [FastString] -> ShortByteString -> Maybe FastString bucket_match fs sbs = go fs where go [] = Nothing go (fs@(FastString {fs_sbs=fs_sbs}) : ls) | fs_sbs == sbs = Just fs | otherwise = go ls mkFastStringBytes :: Ptr Word8 -> Int -> FastString mkFastStringBytes !ptr !len = NB : Might as well use unsafeDupablePerformIO , since is unsafeDupablePerformIO $ do sbs <- newSBSFromPtr ptr len mkFastStringWith (mkNewFastStringShortByteString sbs) sbs newSBSFromPtr :: Ptr a -> Int -> IO ShortByteString newSBSFromPtr (Ptr src#) (I# len#) = IO $ \s -> case newByteArray# len# s of { (# s, dst# #) -> case copyAddrToByteArray# src# dst# 0# len# s of { s -> case unsafeFreezeByteArray# dst# s of { (# s, ba# #) -> (# s, SBS.SBS ba# #) }}} | Create a ' FastString ' by copying an existing ' ByteString ' mkFastStringByteString :: ByteString -> FastString mkFastStringByteString bs = let sbs = SBS.toShort bs in inlinePerformIO $ mkFastStringWith (mkNewFastStringShortByteString sbs) sbs | Create a ' FastString ' from an existing ' ShortByteString ' without mkFastStringShortByteString :: ShortByteString -> FastString mkFastStringShortByteString sbs = inlinePerformIO $ mkFastStringWith (mkNewFastStringShortByteString sbs) sbs | Creates a UTF-8 encoded ' FastString ' from a ' String ' mkFastString :: String -> FastString mkFastString str = inlinePerformIO $ do let !sbs = utf8EncodeShortByteString str mkFastStringWith (mkNewFastStringShortByteString sbs) sbs The following rule is used to avoid polluting the non - reclaimable FastString # RULES " bytesFS / mkFastString " forall x. bytesFS ( ) = utf8EncodeByteString x # "bytesFS/mkFastString" forall x. bytesFS (mkFastString x) = utf8EncodeByteString x #-} | Creates a ' FastString ' from a UTF-8 encoded @[Word8]@ mkFastStringByteList :: [Word8] -> FastString mkFastStringByteList str = mkFastStringShortByteString (SBS.pack str) | Creates a ( lazy ) Z - encoded ' FastString ' from a ' ShortByteString ' and mkZFastString :: FastMutInt -> ShortByteString -> FastZString mkZFastString n_zencs sbs = unsafePerformIO $ do _ <- atomicFetchAddFastMut n_zencs 1 return $ mkFastZStringString (zEncodeString (utf8DecodeShortByteString sbs)) mkNewFastStringShortByteString :: ShortByteString -> Int -> FastMutInt -> IO FastString mkNewFastStringShortByteString sbs uid n_zencs = do let zstr = mkZFastString n_zencs sbs chars = utf8CountCharsShortByteString sbs return (FastString uid chars sbs zstr) hashStr :: ShortByteString -> Int hashStr sbs@(SBS.SBS ba#) = loop 0# 0# where !(I# len#) = SBS.length sbs loop h n = if isTrue# (n ==# len#) then I# h else let above . Not doing this right caused # 17909 . #if __GLASGOW_HASKELL__ >= 901 !c = int8ToInt# (indexInt8Array# ba# n) #else !c = indexInt8Array# ba# n #endif !h2 = (h *# 16777619#) `xorI#` c in loop h2 (n +# 1#) Operations | Returns the length of the ' FastString ' in characters lengthFS :: FastString -> Int lengthFS fs = n_chars fs | Returns @True@ if the ' FastString ' is empty nullFS :: FastString -> Bool nullFS fs = SBS.null $ fs_sbs fs | Lazily unpacks and decodes the FastString unpackFS :: FastString -> String unpackFS fs = utf8DecodeShortByteString $ fs_sbs fs | Returns a Z - encoded version of a ' FastString ' . This might be the original , if it was already Z - encoded . The first time this function is applied to a particular ' FastString ' , the results are zEncodeFS :: FastString -> FastZString zEncodeFS fs = fs_zenc fs appendFS :: FastString -> FastString -> FastString appendFS fs1 fs2 = mkFastStringShortByteString $ (Semi.<>) (fs_sbs fs1) (fs_sbs fs2) concatFS :: [FastString] -> FastString concatFS = mkFastStringShortByteString . mconcat . map fs_sbs consFS :: Char -> FastString -> FastString consFS c fs = mkFastString (c : unpackFS fs) unconsFS :: FastString -> Maybe (Char, FastString) unconsFS fs = case unpackFS fs of [] -> Nothing (chr : str) -> Just (chr, mkFastString str) uniqueOfFS :: FastString -> Int uniqueOfFS fs = uniq fs nilFS :: FastString nilFS = mkFastString "" getFastStringTable :: IO [[[FastString]]] getFastStringTable = forM [0 .. numSegments - 1] $ \(I# i#) -> do let (# segmentRef #) = indexArray# segments# i# FastStringTableSegment _ _ buckets# <- readIORef segmentRef let bucketSize = I# (sizeofMutableArray# buckets#) forM [0 .. bucketSize - 1] $ \(I# j#) -> IO $ readArray# buckets# j# where !(FastStringTable _ _ segments#) = stringTable getFastStringZEncCounter :: IO Int getFastStringZEncCounter = readFastMutInt n_zencs where !(FastStringTable _ n_zencs _) = stringTable Outputting ' FastString 's |Outputs a ' FastString ' with /no decoding at all/ , that is , you get the actual bytes in the ' FastString ' written to the ' Handle ' . hPutFS :: Handle -> FastString -> IO () hPutFS handle fs = BS.hPut handle $ bytesFS fs ToDo : we 'll probably want an hPutFSLocal , or something , to output PtrStrings , here for convenience only . | A ' PtrString ' is a pointer to some array of Latin-1 encoded chars . data PtrString = PtrString !(Ptr Word8) !Int | Wrap an unboxed address into a ' PtrString ' . mkPtrString# :: Addr# -> PtrString # INLINE mkPtrString # # mkPtrString# a# = PtrString (Ptr a#) (ptrStrLength (Ptr a#)) | Decode a ' PtrString ' back into a ' String ' using Latin-1 encoding . This does not free the memory associated with ' PtrString ' . unpackPtrString :: PtrString -> String unpackPtrString (PtrString (Ptr p#) (I# n#)) = unpackNBytes# p# n# but is performed in \(O(\min(n , l))\ ) rather than \(O(l)\ ) , where \(l\ ) is the length of the ' PtrString ' . unpackPtrStringTakeN :: Int -> PtrString -> String unpackPtrStringTakeN n (PtrString (Ptr p#) len) = case min n len of I# n# -> unpackNBytes# p# n# | Return the length of a ' PtrString ' lengthPS :: PtrString -> Int lengthPS (PtrString _ n) = n #if !MIN_VERSION_GLASGOW_HASKELL(9,0,0,0) foreign import ccall unsafe "strlen" cstringLength# :: Addr# -> Int# #endif ptrStrLength :: Ptr Word8 -> Int # INLINE ptrStrLength # ptrStrLength (Ptr a) = I# (cstringLength# a) # NOINLINE fsLit # fsLit :: String -> FastString fsLit x = mkFastString x # RULES " fslit " forall x . fsLit ( unpackCString # x ) = mkFastString # x # forall x . fsLit (unpackCString# x) = mkFastString# x #-}
4f4fac53c129f40a99ed9bd94551e43683490537328670a845ab323fda2e3026
cyverse-archive/DiscoveryEnvironmentBackend
build_profiles.clj
{:user {:plugins [[lein-exec "0.3.4"]]}}
null
https://raw.githubusercontent.com/cyverse-archive/DiscoveryEnvironmentBackend/7f6177078c1a1cb6d11e62f12cfe2e22d669635b/docker/de-backend-buildenv/build_profiles.clj
clojure
{:user {:plugins [[lein-exec "0.3.4"]]}}
bf6b5d0fbbdc633762784727dede0d5f19602d8d85e4d6e23bd90f0098242b6b
abdulapopoola/SICPBook
4.42.scm
#lang racket (define (xor x y) (or (and x (not y)) (and y (not x)))) (define (liars-puzzle) (let ((Betty (amb 1 2 3 4 5)) (Ethel (amb 1 2 3 4 5)) (Joan (amb 1 2 3 4 5)) (Kitty (amb 1 2 3 4 5)) (Mary (amb 1 2 3 4 5))) (require (xor (= Betty 3) (= Kitty 3))) (require (xor (= Ethel 1) (= Joan 2))) (require (xor (= Joan 3) (= Ethel 5))) (require (xor (= Kitty 2) (= Mary 4))) (require (xor (= Mary 4) (= Betty 1))) (require (distinct? (list Betty Ethel Joan Kitty Mary))) (list (list 'Betty Betty) (list 'Ethel Ethel) (list 'Joan Joan) (list 'Kitty Kitty) (list 'Mary Mary)))) ( ( betty 3 ) ( ethel 5 ) ( joan 2 ) ( kitty 1 ) ( mary 4 ) )
null
https://raw.githubusercontent.com/abdulapopoola/SICPBook/c8a0228ebf66d9c1ddc5ef1fcc1d05d8684f090a/Chapter%204/4.3/4.42.scm
scheme
#lang racket (define (xor x y) (or (and x (not y)) (and y (not x)))) (define (liars-puzzle) (let ((Betty (amb 1 2 3 4 5)) (Ethel (amb 1 2 3 4 5)) (Joan (amb 1 2 3 4 5)) (Kitty (amb 1 2 3 4 5)) (Mary (amb 1 2 3 4 5))) (require (xor (= Betty 3) (= Kitty 3))) (require (xor (= Ethel 1) (= Joan 2))) (require (xor (= Joan 3) (= Ethel 5))) (require (xor (= Kitty 2) (= Mary 4))) (require (xor (= Mary 4) (= Betty 1))) (require (distinct? (list Betty Ethel Joan Kitty Mary))) (list (list 'Betty Betty) (list 'Ethel Ethel) (list 'Joan Joan) (list 'Kitty Kitty) (list 'Mary Mary)))) ( ( betty 3 ) ( ethel 5 ) ( joan 2 ) ( kitty 1 ) ( mary 4 ) )
a0b56ab824c51c0b0845e4aa7c470756ce932dd8826486dc2115199657344c70
pavlobaron/ErlangOTPBookSamples
mod3.erl
-module(mod3). -vsn(1.0). -export([calc/2]). calc(A, B) -> A + B.
null
https://raw.githubusercontent.com/pavlobaron/ErlangOTPBookSamples/50094964ad814932760174914490e49618b2b8c2/entwicklung/upgrade/mod3.erl
erlang
-module(mod3). -vsn(1.0). -export([calc/2]). calc(A, B) -> A + B.
8bfef3a990738d56ddcf640861467833c3e3df1720f420a382ab20e6b12ccaf8
mpickering/apply-refact
Structure12.hs
foo (Bar _ _) = x
null
https://raw.githubusercontent.com/mpickering/apply-refact/a4343ea0f4f9d8c2e16d6b16b9068f321ba4f272/tests/examples/Structure12.hs
haskell
foo (Bar _ _) = x
f1a8c28afecf6bd0441d57dfe401fe5e28626ccbeec8fc5fae06578b0bf8fb57
xguerin/netml
NetML_Layer.mli
module II = NetML_Layer_II module III = NetML_Layer_III module IV = NetML_Layer_IV
null
https://raw.githubusercontent.com/xguerin/netml/de9d277d2f1ac055aea391b89391df6830f80eff/src/NetML_Layer.mli
ocaml
module II = NetML_Layer_II module III = NetML_Layer_III module IV = NetML_Layer_IV
3f7090f6170568bc3142036bbfce3749ac42f1247ebe8ad854f611e24505d06f
racket/rhombus-prototype
name-root-ref.rkt
#lang racket/base (require (for-syntax racket/base syntax/parse/pre racket/symbol (prefix-in enforest: enforest/name-root) enforest/syntax-local shrubbery/property "srcloc.rkt" "id-binding.rkt") "name-root-space.rkt") ;; convert a hierachical layer implemented as portal syntax to a name-root (provide (for-syntax name-root-ref make-name-root-ref replace-head-dotted-name import-root-ref extensible-name-root portal-syntax->lookup portal-syntax->import)) (define-for-syntax (make-name-root-ref #:binding-ref [binding-ref #f] #:non-portal-ref [non-portal-ref #f] #:binding-extension-combine [binding-extension-combine (lambda (id prefix) id)]) (lambda (v) (define (make self-id get) (enforest:name-root (lambda (in-space stxes) (let loop ([stxes stxes] [gets ;; reverse order search path: (cons get prefix) (list (cons get #f) (cons #f (syntax-parse stxes [(form-id . _) #'form-id])))]) (define (build-name prefix field-id) (datum->syntax prefix (string->symbol (string-append (symbol->immutable-string (syntax-e prefix)) "." (symbol->immutable-string (syntax-e field-id)))) field-id field-id)) (define (next form-id field-id what tail) (define binding-end? (and binding-ref (syntax-parse tail #:datum-literals (op parens |.|) [((op |.|) . _) #f] [_ #t]))) (define id (or (for/or ([get+prefix (in-list (reverse gets))]) (define get (car get+prefix)) (define prefix (cdr get+prefix)) (cond [(not get) (define name (build-name prefix field-id)) (and (or (identifier-binding* (in-space name)) (identifier-binding* (in-name-root-space name))) (relocate-field form-id field-id name))] [else (define sub-id (if prefix (build-name prefix field-id) field-id)) (let ([id (get #f what sub-id in-space)]) (and id (or (not binding-end?) (syntax-local-value* (in-space id) binding-ref)) (relocate-field form-id field-id id)))])) (if binding-end? (let ([prefix (cdar (reverse gets))]) (binding-extension-combine (relocate-field form-id field-id (build-name prefix field-id)) (in-name-root-space prefix))) ;; try again with the shallowest to report an error (let ([get (caar gets)]) (get form-id what field-id in-space))))) ;; keep looking at dots? (define more-dots? (syntax-parse tail #:datum-literals (op parens group |.|) [((op |.|) _:identifier . _) #t] [((op |.|) (parens (group target (op _))) . tail) #t] [_ #f])) (define v (and (or more-dots? non-portal-ref) (syntax-local-value* (in-name-root-space id) (lambda (v) (and (portal-syntax? v) v))))) (cond [v (portal-syntax->lookup (portal-syntax-content v) (lambda (self-id next-get) (if more-dots? (loop (cons id tail) (cons (cons next-get #f) (for/list ([get+prefix (in-list gets)]) (define get (car get+prefix)) (define prefix (cdr get+prefix)) (cons get (if prefix (build-name prefix field-id) field-id))))) (values self-id tail))))] [non-portal-ref (non-portal-ref form-id field-id tail)] [else (values id tail)])) (syntax-parse stxes #:datum-literals (op parens group |.|) [(form-id (op |.|) field:identifier . tail) (next #'form-id #'field "identifier" #'tail)] [(form-id (op |.|) (parens (group (op field))) . tail) (next #'form-id #'field "operator" #'tail)] [(form-id (op (~and dot |.|)) . tail) (raise-syntax-error #f "expected an identifier or parentheses after dot" #'dot)] [(form-id . tail) (raise-syntax-error #f "expected a dot after name" #'form-id)]))))) (or (enforest:name-root-ref v) (and (portal-syntax? v) (portal-syntax->lookup (portal-syntax-content v) make))))) (define-for-syntax name-root-ref (make-name-root-ref)) (define-for-syntax (portal-syntax->lookup portal-stx make) (syntax-parse portal-stx #:datum-literals (import map) [([import _ _ _] pre-ctx-s ctx-s) (define pre-ctx #'pre-ctx-s) (define ctx #'ctx-s) (make #f (lambda (who-stx what name in-space) (cond [(syntax-e name) (define id (datum->syntax ctx (syntax-e name) name name)) (define pre-id (datum->syntax pre-ctx (syntax-e name))) (cond [(or (identifier-distinct-binding* (in-space id) (in-space pre-id)) (identifier-distinct-binding* (in-name-root-space id) (in-name-root-space pre-id))) id] [who-stx (raise-syntax-error #f (format "no such imported ~a" what) name)] [else #f])] [else #f])))] [(map self-id _ [key val . rule] ...) (define keys (syntax->list #'(key ...))) (define vals (syntax->list #'(val ...))) (define rules (syntax->list #'(rule ...))) (make #'self-id (lambda (who-stx what name in-space) (or (for/or ([key (in-list keys)] [val (in-list vals)] [rule (in-list rules)]) (and (eq? (syntax-e key) (syntax-e name)) (matches-rule? in-space rule) val)) (and who-stx (raise-syntax-error #f (format "~a not provided by ~a" what (syntax-e who-stx)) name)))))] [_ #f])) (define-for-syntax (matches-rule? in-space rule) (cond [(null? (syntax-e rule)) #t] [else (define x (datum->syntax #f 'x)) (with-syntax ([(mode space ...) rule]) (define match? (for/or ([sp-stx (in-list (syntax->list #'(space ...)))]) (define sp (syntax-e sp-stx)) (bound-identifier=? (in-space x) (if sp ((make-interned-syntax-introducer sp) x) x)))) (if (eq? (syntax-e #'mode) 'only) match? (not match?)))])) (define-for-syntax (portal-syntax->extends portal-stx) (syntax-parse portal-stx #:datum-literals (import map) [(map _ extends . _) #'extends] [_ #f])) (define-for-syntax (relocate-field root-id field-id new-field-id) (syntax-property (datum->syntax new-field-id (syntax-e new-field-id) (span-srcloc root-id field-id) field-id) 'rhombus-dotted-name (string->symbol (format "~a.~a" (or (syntax-property root-id 'syntax-error-name) (syntax-e root-id)) (syntax-e field-id))))) (define-for-syntax (replace-head-dotted-name stx) (define head (car (syntax-e stx))) (define name (syntax-property head 'rhombus-dotted-name)) (cond [name (datum->syntax stx (cons (syntax-raw-property (datum->syntax head name head head) (symbol->string name)) (cdr (syntax-e stx))) stx stx)] [else stx])) ;; Gets information on a name ref that can be used with `import` (define-for-syntax (import-root-ref v) (and (portal-syntax? v) (portal-syntax->import (portal-syntax-content v)))) (define-for-syntax (portal-syntax->import portal-stx) (syntax-parse portal-stx #:datum-literals (map import) [([import mod-path parsed-r mod-ctx] orig-s ctx-s) #`(parsed #,(datum->syntax #'ctx-s (syntax-e #'mod-path)) #,((make-syntax-delta-introducer #'mod-ctx (syntax-local-introduce (datum->syntax #f 'empty))) #'parsed-r 'remove))] [(map . _) portal-stx] [_ #f])) returns the i d of an extension root , the first one found from the ;; possibilities in `ids` (define-for-syntax (extensible-name-root ids) (let loop ([ids ids] [portal-stx #f] [prev-who #f]) (define id (cond [(not portal-stx) (car ids)] [else (portal-syntax->lookup portal-stx (lambda (self-id get) (define id (get #f #f (car ids) in-name-root-space)) (and id (relocate-field prev-who (car ids) id))))])) (define v (and id (syntax-local-value* (in-name-root-space id) (lambda (v) (and (portal-syntax? v) v))))) (and v (cond [(null? (cdr ids)) ;; must be `map` portal syntax to allow extension: (syntax-parse (portal-syntax-content v) #:datum-literals (map) [(map . _) #t] [_ #f])] [else (loop (cdr ids) (portal-syntax-content v) id)]) (in-name-root-space id))))
null
https://raw.githubusercontent.com/racket/rhombus-prototype/6832f0778330d1a7079443d55ca1aeaa9e2dbe18/rhombus/private/name-root-ref.rkt
racket
convert a hierachical layer implemented as portal syntax to a name-root reverse order search path: (cons get prefix) try again with the shallowest to report an error keep looking at dots? Gets information on a name ref that can be used with `import` possibilities in `ids` must be `map` portal syntax to allow extension:
#lang racket/base (require (for-syntax racket/base syntax/parse/pre racket/symbol (prefix-in enforest: enforest/name-root) enforest/syntax-local shrubbery/property "srcloc.rkt" "id-binding.rkt") "name-root-space.rkt") (provide (for-syntax name-root-ref make-name-root-ref replace-head-dotted-name import-root-ref extensible-name-root portal-syntax->lookup portal-syntax->import)) (define-for-syntax (make-name-root-ref #:binding-ref [binding-ref #f] #:non-portal-ref [non-portal-ref #f] #:binding-extension-combine [binding-extension-combine (lambda (id prefix) id)]) (lambda (v) (define (make self-id get) (enforest:name-root (lambda (in-space stxes) (let loop ([stxes stxes] [gets (list (cons get #f) (cons #f (syntax-parse stxes [(form-id . _) #'form-id])))]) (define (build-name prefix field-id) (datum->syntax prefix (string->symbol (string-append (symbol->immutable-string (syntax-e prefix)) "." (symbol->immutable-string (syntax-e field-id)))) field-id field-id)) (define (next form-id field-id what tail) (define binding-end? (and binding-ref (syntax-parse tail #:datum-literals (op parens |.|) [((op |.|) . _) #f] [_ #t]))) (define id (or (for/or ([get+prefix (in-list (reverse gets))]) (define get (car get+prefix)) (define prefix (cdr get+prefix)) (cond [(not get) (define name (build-name prefix field-id)) (and (or (identifier-binding* (in-space name)) (identifier-binding* (in-name-root-space name))) (relocate-field form-id field-id name))] [else (define sub-id (if prefix (build-name prefix field-id) field-id)) (let ([id (get #f what sub-id in-space)]) (and id (or (not binding-end?) (syntax-local-value* (in-space id) binding-ref)) (relocate-field form-id field-id id)))])) (if binding-end? (let ([prefix (cdar (reverse gets))]) (binding-extension-combine (relocate-field form-id field-id (build-name prefix field-id)) (in-name-root-space prefix))) (let ([get (caar gets)]) (get form-id what field-id in-space))))) (define more-dots? (syntax-parse tail #:datum-literals (op parens group |.|) [((op |.|) _:identifier . _) #t] [((op |.|) (parens (group target (op _))) . tail) #t] [_ #f])) (define v (and (or more-dots? non-portal-ref) (syntax-local-value* (in-name-root-space id) (lambda (v) (and (portal-syntax? v) v))))) (cond [v (portal-syntax->lookup (portal-syntax-content v) (lambda (self-id next-get) (if more-dots? (loop (cons id tail) (cons (cons next-get #f) (for/list ([get+prefix (in-list gets)]) (define get (car get+prefix)) (define prefix (cdr get+prefix)) (cons get (if prefix (build-name prefix field-id) field-id))))) (values self-id tail))))] [non-portal-ref (non-portal-ref form-id field-id tail)] [else (values id tail)])) (syntax-parse stxes #:datum-literals (op parens group |.|) [(form-id (op |.|) field:identifier . tail) (next #'form-id #'field "identifier" #'tail)] [(form-id (op |.|) (parens (group (op field))) . tail) (next #'form-id #'field "operator" #'tail)] [(form-id (op (~and dot |.|)) . tail) (raise-syntax-error #f "expected an identifier or parentheses after dot" #'dot)] [(form-id . tail) (raise-syntax-error #f "expected a dot after name" #'form-id)]))))) (or (enforest:name-root-ref v) (and (portal-syntax? v) (portal-syntax->lookup (portal-syntax-content v) make))))) (define-for-syntax name-root-ref (make-name-root-ref)) (define-for-syntax (portal-syntax->lookup portal-stx make) (syntax-parse portal-stx #:datum-literals (import map) [([import _ _ _] pre-ctx-s ctx-s) (define pre-ctx #'pre-ctx-s) (define ctx #'ctx-s) (make #f (lambda (who-stx what name in-space) (cond [(syntax-e name) (define id (datum->syntax ctx (syntax-e name) name name)) (define pre-id (datum->syntax pre-ctx (syntax-e name))) (cond [(or (identifier-distinct-binding* (in-space id) (in-space pre-id)) (identifier-distinct-binding* (in-name-root-space id) (in-name-root-space pre-id))) id] [who-stx (raise-syntax-error #f (format "no such imported ~a" what) name)] [else #f])] [else #f])))] [(map self-id _ [key val . rule] ...) (define keys (syntax->list #'(key ...))) (define vals (syntax->list #'(val ...))) (define rules (syntax->list #'(rule ...))) (make #'self-id (lambda (who-stx what name in-space) (or (for/or ([key (in-list keys)] [val (in-list vals)] [rule (in-list rules)]) (and (eq? (syntax-e key) (syntax-e name)) (matches-rule? in-space rule) val)) (and who-stx (raise-syntax-error #f (format "~a not provided by ~a" what (syntax-e who-stx)) name)))))] [_ #f])) (define-for-syntax (matches-rule? in-space rule) (cond [(null? (syntax-e rule)) #t] [else (define x (datum->syntax #f 'x)) (with-syntax ([(mode space ...) rule]) (define match? (for/or ([sp-stx (in-list (syntax->list #'(space ...)))]) (define sp (syntax-e sp-stx)) (bound-identifier=? (in-space x) (if sp ((make-interned-syntax-introducer sp) x) x)))) (if (eq? (syntax-e #'mode) 'only) match? (not match?)))])) (define-for-syntax (portal-syntax->extends portal-stx) (syntax-parse portal-stx #:datum-literals (import map) [(map _ extends . _) #'extends] [_ #f])) (define-for-syntax (relocate-field root-id field-id new-field-id) (syntax-property (datum->syntax new-field-id (syntax-e new-field-id) (span-srcloc root-id field-id) field-id) 'rhombus-dotted-name (string->symbol (format "~a.~a" (or (syntax-property root-id 'syntax-error-name) (syntax-e root-id)) (syntax-e field-id))))) (define-for-syntax (replace-head-dotted-name stx) (define head (car (syntax-e stx))) (define name (syntax-property head 'rhombus-dotted-name)) (cond [name (datum->syntax stx (cons (syntax-raw-property (datum->syntax head name head head) (symbol->string name)) (cdr (syntax-e stx))) stx stx)] [else stx])) (define-for-syntax (import-root-ref v) (and (portal-syntax? v) (portal-syntax->import (portal-syntax-content v)))) (define-for-syntax (portal-syntax->import portal-stx) (syntax-parse portal-stx #:datum-literals (map import) [([import mod-path parsed-r mod-ctx] orig-s ctx-s) #`(parsed #,(datum->syntax #'ctx-s (syntax-e #'mod-path)) #,((make-syntax-delta-introducer #'mod-ctx (syntax-local-introduce (datum->syntax #f 'empty))) #'parsed-r 'remove))] [(map . _) portal-stx] [_ #f])) returns the i d of an extension root , the first one found from the (define-for-syntax (extensible-name-root ids) (let loop ([ids ids] [portal-stx #f] [prev-who #f]) (define id (cond [(not portal-stx) (car ids)] [else (portal-syntax->lookup portal-stx (lambda (self-id get) (define id (get #f #f (car ids) in-name-root-space)) (and id (relocate-field prev-who (car ids) id))))])) (define v (and id (syntax-local-value* (in-name-root-space id) (lambda (v) (and (portal-syntax? v) v))))) (and v (cond [(null? (cdr ids)) (syntax-parse (portal-syntax-content v) #:datum-literals (map) [(map . _) #t] [_ #f])] [else (loop (cdr ids) (portal-syntax-content v) id)]) (in-name-root-space id))))
bc955f1fb9958a464b1274c731e9ab20a3a332d018fbb6f44942b3156d63af30
PacktWorkshops/The-Clojure-Workshop
core.cljs
(ns minmacros.core (:require-macros [minmacros.macros :as mm])) (println "Hello from clojurescript") (mm/minimal-macro)
null
https://raw.githubusercontent.com/PacktWorkshops/The-Clojure-Workshop/3d309bb0e46a41ce2c93737870433b47ce0ba6a2/Chapter11/Examples/minmacros/src/minmacros/core.cljs
clojure
(ns minmacros.core (:require-macros [minmacros.macros :as mm])) (println "Hello from clojurescript") (mm/minimal-macro)
757cc090bc5b8baad1d224d1627be55873e93cc6e7043c057947002d9eeb07b0
composewell/streamly
Parallel.hs
# OPTIONS_GHC -Wno - deprecations # -- | -- Module : Main Copyright : ( c ) 2018 Composewell Technologies -- -- License : BSD3 -- Maintainer : # LANGUAGE FlexibleContexts # import Prelude hiding (mapM) import Data.Function ((&)) import Streamly.Prelude ( SerialT, fromParallel, parallel, fromSerial, maxBuffer, maxThreads) import qualified Streamly.Prelude as S import qualified Streamly.Internal.Data.Fold as FL import qualified Streamly.Internal.Data.Stream.IsStream as Internal import Streamly.Benchmark.Common import Streamly.Benchmark.Prelude import Gauge moduleName :: String moduleName = "Prelude.Parallel" ------------------------------------------------------------------------------- -- Merging ------------------------------------------------------------------------------- # INLINE mergeAsyncByM # mergeAsyncByM :: (S.IsStream t, S.MonadAsync m) => Int -> Int -> t m Int mergeAsyncByM count n = S.mergeAsyncByM (\a b -> return (a `compare` b)) (sourceUnfoldrM count n) (sourceUnfoldrM count (n + 1)) # INLINE mergeAsyncBy # mergeAsyncBy :: (S.IsStream t, S.MonadAsync m) => Int -> Int -> t m Int mergeAsyncBy count n = S.mergeAsyncBy compare (sourceUnfoldrM count n) (sourceUnfoldrM count (n + 1)) ------------------------------------------------------------------------------- -- Application/fold ------------------------------------------------------------------------------- {-# INLINE parAppMap #-} parAppMap :: S.MonadAsync m => SerialT m Int -> m () parAppMap src = S.drain $ S.map (+1) S.|$ src {-# INLINE parAppSum #-} parAppSum :: S.MonadAsync m => SerialT m Int -> m () parAppSum src = (S.sum S.|$. src) >>= \x -> seq x (return ()) # INLINE ( | & ) # (|&) :: S.MonadAsync m => SerialT m Int -> m () (|&) src = src S.|& S.map (+ 1) & S.drain # INLINE ( | & . ) # (|&.) :: S.MonadAsync m => SerialT m Int -> m () (|&.) src = (src S.|&. S.sum) >>= \x -> seq x (return ()) ------------------------------------------------------------------------------- -- Tapping ------------------------------------------------------------------------------- # INLINE tapAsyncS # tapAsyncS :: S.MonadAsync m => Int -> SerialT m Int -> m () tapAsyncS n = composeN n $ Internal.tapAsyncK S.sum # INLINE tapAsync # tapAsync :: S.MonadAsync m => Int -> SerialT m Int -> m () tapAsync n = composeN n $ Internal.tapAsync FL.sum o_1_space_merge_app_tap :: Int -> [Benchmark] o_1_space_merge_app_tap value = [ bgroup "merge-app-tap" [ benchIOSrc fromSerial "mergeAsyncBy (2,x/2)" (mergeAsyncBy (value `div` 2)) , benchIOSrc fromSerial "mergeAsyncByM (2,x/2)" (mergeAsyncByM (value `div` 2)) Parallel stages in a pipeline , benchIOSink value "parAppMap" parAppMap , benchIOSink value "parAppSum" parAppSum , benchIOSink value "(|&)" (|&) , benchIOSink value "(|&.)" (|&.) , benchIOSink value "tapAsync" (tapAsync 1) , benchIOSink value "tapAsyncS" (tapAsyncS 1) ] ] ------------------------------------------------------------------------------- -- Generation ------------------------------------------------------------------------------- o_n_heap_generation :: Int -> [Benchmark] o_n_heap_generation value = [ bgroup "generation" [ benchIOSrc fromParallel "unfoldr" (sourceUnfoldr value) , benchIOSrc fromParallel "unfoldrM" (sourceUnfoldrM value) , benchIOSrc fromParallel "fromFoldable" (sourceFromFoldable value) , benchIOSrc fromParallel "fromFoldableM" (sourceFromFoldableM value) , benchIOSrc fromParallel "unfoldrM maxThreads 1" (maxThreads 1 . sourceUnfoldrM value) , benchIOSrc fromParallel "unfoldrM maxBuffer 1 (x/10 ops)" (maxBuffer 1 . sourceUnfoldrM (value `div` 10)) ] ] ------------------------------------------------------------------------------- -- Mapping ------------------------------------------------------------------------------- o_n_heap_mapping :: Int -> [Benchmark] o_n_heap_mapping value = [ bgroup "mapping" [ benchIOSink value "map" $ mapN fromParallel 1 , benchIOSink value "fmap" $ fmapN fromParallel 1 , benchIOSink value "mapM" $ mapM fromParallel 1 . fromSerial ] ] ------------------------------------------------------------------------------- -- Joining ------------------------------------------------------------------------------- # INLINE parallel2 # parallel2 :: Int -> Int -> IO () parallel2 count n = S.drain $ (sourceUnfoldrM count n) `parallel` (sourceUnfoldrM count (n + 1)) o_1_space_joining :: Int -> [Benchmark] o_1_space_joining value = [ bgroup "joining" [ benchIOSrc1 "parallel (2 of n/2)" (parallel2 (value `div` 2)) ] ] ------------------------------------------------------------------------------- Concat ------------------------------------------------------------------------------- o_n_heap_concatFoldable :: Int -> [Benchmark] o_n_heap_concatFoldable value = [ bgroup "concat-foldable" [ benchIOSrc fromParallel "foldMapWith (<>) (List)" (sourceFoldMapWith value) , benchIOSrc fromParallel "foldMapWith (<>) (Stream)" (sourceFoldMapWithStream value) , benchIOSrc fromParallel "foldMapWithM (<>) (List)" (sourceFoldMapWithM value) , benchIOSrc fromSerial "S.concatFoldableWith (<>) (List)" (concatFoldableWith value) , benchIOSrc fromSerial "S.concatForFoldableWith (<>) (List)" (concatForFoldableWith value) , benchIOSrc fromParallel "foldMapM (List)" (sourceFoldMapM value) ] ] o_n_heap_concat :: Int -> [Benchmark] o_n_heap_concat value = value2 `seq` [ bgroup "concat" This is for comparison with foldMapWith [ benchIOSrc fromSerial "concatMapWithId (n of 1) (fromFoldable)" (S.concatMapWith parallel id . sourceConcatMapId value) , benchIO "concatMapWith (n of 1)" (concatStreamsWith parallel value 1) , benchIO "concatMapWith (sqrt x of sqrt x)" (concatStreamsWith parallel value2 value2) , benchIO "concatMapWith (1 of n)" (concatStreamsWith parallel 1 value) ] ] where value2 = round $ sqrt (fromIntegral value :: Double) ------------------------------------------------------------------------------- Monadic outer product ------------------------------------------------------------------------------- o_n_heap_outerProduct :: Int -> [Benchmark] o_n_heap_outerProduct value = [ bgroup "monad-outer-product" [ benchIO "toNullAp" $ toNullAp value fromParallel , benchIO "toNull" $ toNullM value fromParallel , benchIO "toNull3" $ toNullM3 value fromParallel , benchIO "filterAllOut" $ filterAllOutM value fromParallel , benchIO "filterAllIn" $ filterAllInM value fromParallel , benchIO "filterSome" $ filterSome value fromParallel , benchIO "breakAfterSome" $ breakAfterSome value fromParallel ] ] o_n_space_outerProduct :: Int -> [Benchmark] o_n_space_outerProduct value = [ bgroup "monad-outer-product" [ benchIO "toList" $ toListM value fromParallel -- XXX disabled due to a bug for now -- , benchIO "toListSome" $ toListSome value fromParallel ] ] ------------------------------------------------------------------------------- -- Main ------------------------------------------------------------------------------- main :: IO () main = runWithCLIOpts defaultStreamSize allBenchmarks where allBenchmarks value = [ bgroup (o_1_space_prefix moduleName) $ concat [ o_1_space_merge_app_tap value , o_1_space_joining value ] , bgroup (o_n_heap_prefix moduleName) $ concat [ o_n_heap_generation value , o_n_heap_mapping value , o_n_heap_concatFoldable value , o_n_heap_concat value , o_n_heap_outerProduct value ] , bgroup (o_n_space_prefix moduleName) (o_n_space_outerProduct value) ]
null
https://raw.githubusercontent.com/composewell/streamly/5327f181db2cf956461b74ed50720eebf119f25a/benchmark/Streamly/Benchmark/Prelude/Parallel.hs
haskell
| Module : Main License : BSD3 Maintainer : ----------------------------------------------------------------------------- Merging ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- Application/fold ----------------------------------------------------------------------------- # INLINE parAppMap # # INLINE parAppSum # ----------------------------------------------------------------------------- Tapping ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- Generation ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- Mapping ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- Joining ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- XXX disabled due to a bug for now , benchIO "toListSome" $ toListSome value fromParallel ----------------------------------------------------------------------------- Main -----------------------------------------------------------------------------
# OPTIONS_GHC -Wno - deprecations # Copyright : ( c ) 2018 Composewell Technologies # LANGUAGE FlexibleContexts # import Prelude hiding (mapM) import Data.Function ((&)) import Streamly.Prelude ( SerialT, fromParallel, parallel, fromSerial, maxBuffer, maxThreads) import qualified Streamly.Prelude as S import qualified Streamly.Internal.Data.Fold as FL import qualified Streamly.Internal.Data.Stream.IsStream as Internal import Streamly.Benchmark.Common import Streamly.Benchmark.Prelude import Gauge moduleName :: String moduleName = "Prelude.Parallel" # INLINE mergeAsyncByM # mergeAsyncByM :: (S.IsStream t, S.MonadAsync m) => Int -> Int -> t m Int mergeAsyncByM count n = S.mergeAsyncByM (\a b -> return (a `compare` b)) (sourceUnfoldrM count n) (sourceUnfoldrM count (n + 1)) # INLINE mergeAsyncBy # mergeAsyncBy :: (S.IsStream t, S.MonadAsync m) => Int -> Int -> t m Int mergeAsyncBy count n = S.mergeAsyncBy compare (sourceUnfoldrM count n) (sourceUnfoldrM count (n + 1)) parAppMap :: S.MonadAsync m => SerialT m Int -> m () parAppMap src = S.drain $ S.map (+1) S.|$ src parAppSum :: S.MonadAsync m => SerialT m Int -> m () parAppSum src = (S.sum S.|$. src) >>= \x -> seq x (return ()) # INLINE ( | & ) # (|&) :: S.MonadAsync m => SerialT m Int -> m () (|&) src = src S.|& S.map (+ 1) & S.drain # INLINE ( | & . ) # (|&.) :: S.MonadAsync m => SerialT m Int -> m () (|&.) src = (src S.|&. S.sum) >>= \x -> seq x (return ()) # INLINE tapAsyncS # tapAsyncS :: S.MonadAsync m => Int -> SerialT m Int -> m () tapAsyncS n = composeN n $ Internal.tapAsyncK S.sum # INLINE tapAsync # tapAsync :: S.MonadAsync m => Int -> SerialT m Int -> m () tapAsync n = composeN n $ Internal.tapAsync FL.sum o_1_space_merge_app_tap :: Int -> [Benchmark] o_1_space_merge_app_tap value = [ bgroup "merge-app-tap" [ benchIOSrc fromSerial "mergeAsyncBy (2,x/2)" (mergeAsyncBy (value `div` 2)) , benchIOSrc fromSerial "mergeAsyncByM (2,x/2)" (mergeAsyncByM (value `div` 2)) Parallel stages in a pipeline , benchIOSink value "parAppMap" parAppMap , benchIOSink value "parAppSum" parAppSum , benchIOSink value "(|&)" (|&) , benchIOSink value "(|&.)" (|&.) , benchIOSink value "tapAsync" (tapAsync 1) , benchIOSink value "tapAsyncS" (tapAsyncS 1) ] ] o_n_heap_generation :: Int -> [Benchmark] o_n_heap_generation value = [ bgroup "generation" [ benchIOSrc fromParallel "unfoldr" (sourceUnfoldr value) , benchIOSrc fromParallel "unfoldrM" (sourceUnfoldrM value) , benchIOSrc fromParallel "fromFoldable" (sourceFromFoldable value) , benchIOSrc fromParallel "fromFoldableM" (sourceFromFoldableM value) , benchIOSrc fromParallel "unfoldrM maxThreads 1" (maxThreads 1 . sourceUnfoldrM value) , benchIOSrc fromParallel "unfoldrM maxBuffer 1 (x/10 ops)" (maxBuffer 1 . sourceUnfoldrM (value `div` 10)) ] ] o_n_heap_mapping :: Int -> [Benchmark] o_n_heap_mapping value = [ bgroup "mapping" [ benchIOSink value "map" $ mapN fromParallel 1 , benchIOSink value "fmap" $ fmapN fromParallel 1 , benchIOSink value "mapM" $ mapM fromParallel 1 . fromSerial ] ] # INLINE parallel2 # parallel2 :: Int -> Int -> IO () parallel2 count n = S.drain $ (sourceUnfoldrM count n) `parallel` (sourceUnfoldrM count (n + 1)) o_1_space_joining :: Int -> [Benchmark] o_1_space_joining value = [ bgroup "joining" [ benchIOSrc1 "parallel (2 of n/2)" (parallel2 (value `div` 2)) ] ] Concat o_n_heap_concatFoldable :: Int -> [Benchmark] o_n_heap_concatFoldable value = [ bgroup "concat-foldable" [ benchIOSrc fromParallel "foldMapWith (<>) (List)" (sourceFoldMapWith value) , benchIOSrc fromParallel "foldMapWith (<>) (Stream)" (sourceFoldMapWithStream value) , benchIOSrc fromParallel "foldMapWithM (<>) (List)" (sourceFoldMapWithM value) , benchIOSrc fromSerial "S.concatFoldableWith (<>) (List)" (concatFoldableWith value) , benchIOSrc fromSerial "S.concatForFoldableWith (<>) (List)" (concatForFoldableWith value) , benchIOSrc fromParallel "foldMapM (List)" (sourceFoldMapM value) ] ] o_n_heap_concat :: Int -> [Benchmark] o_n_heap_concat value = value2 `seq` [ bgroup "concat" This is for comparison with foldMapWith [ benchIOSrc fromSerial "concatMapWithId (n of 1) (fromFoldable)" (S.concatMapWith parallel id . sourceConcatMapId value) , benchIO "concatMapWith (n of 1)" (concatStreamsWith parallel value 1) , benchIO "concatMapWith (sqrt x of sqrt x)" (concatStreamsWith parallel value2 value2) , benchIO "concatMapWith (1 of n)" (concatStreamsWith parallel 1 value) ] ] where value2 = round $ sqrt (fromIntegral value :: Double) Monadic outer product o_n_heap_outerProduct :: Int -> [Benchmark] o_n_heap_outerProduct value = [ bgroup "monad-outer-product" [ benchIO "toNullAp" $ toNullAp value fromParallel , benchIO "toNull" $ toNullM value fromParallel , benchIO "toNull3" $ toNullM3 value fromParallel , benchIO "filterAllOut" $ filterAllOutM value fromParallel , benchIO "filterAllIn" $ filterAllInM value fromParallel , benchIO "filterSome" $ filterSome value fromParallel , benchIO "breakAfterSome" $ breakAfterSome value fromParallel ] ] o_n_space_outerProduct :: Int -> [Benchmark] o_n_space_outerProduct value = [ bgroup "monad-outer-product" [ benchIO "toList" $ toListM value fromParallel ] ] main :: IO () main = runWithCLIOpts defaultStreamSize allBenchmarks where allBenchmarks value = [ bgroup (o_1_space_prefix moduleName) $ concat [ o_1_space_merge_app_tap value , o_1_space_joining value ] , bgroup (o_n_heap_prefix moduleName) $ concat [ o_n_heap_generation value , o_n_heap_mapping value , o_n_heap_concatFoldable value , o_n_heap_concat value , o_n_heap_outerProduct value ] , bgroup (o_n_space_prefix moduleName) (o_n_space_outerProduct value) ]
34bb95422625f353fe9f528945680aadeaf87fc0a6f03a931b3bca06f4fbfa21
gorillalabs/sparkling
validation.clj
(ns sparkling.ml.validation (:import [org.apache.spark.api.java JavaRDD JavaPairRDD JavaSparkContext] [org.apache.spark.ml.tuning ParamGridBuilder CrossValidator CrossValidatorModel TrainValidationSplit TrainValidationSplitModel] [org.apache.spark.ml.param ParamMap] [org.apache.spark.mllib.evaluation BinaryClassificationMetrics ] [org.apache.spark.mllib.regression LabeledPoint] [org.apache.spark.ml Pipeline PipelineModel PipelineStage] [org.apache.spark.ml.evaluation BinaryClassificationEvaluator MulticlassClassificationEvaluator] [org.apache.spark.sql SQLContext Dataset RowFactory Row Encoders Encoder])) (defn param-grid "Return a ParamMap array, built using ParamGridBuilder . Values is a seq where every element is a 2-element vector. The first is the parameter name and the second is the list of values " ([] (.build (ParamGridBuilder.))) ([values] (.build (reduce (fn[pgb [k v]] (.addGrid pgb k v) ) (ParamGridBuilder.) values)))) (defn binary-classification-evaluator "Returns a BinaryClassificationEvaluator object. The default metric is areaUnderROC. The other metric available is 'areaUnderPR' " ([] (binary-classification-evaluator {})) ([{:keys [metric-name]}] (let [bce (BinaryClassificationEvaluator.)] (when metric-name (.setMetricName bce metric-name)) bce))) (defn multiclass-classification-evaluator "Returns a MulticlassClassificationEvaluator object. The default metric is f1. The other metrics available are 'precision','recall', 'weightedPrecision','weightedRecall'" ([] (multiclass-classification-evaluator {})) ([{:keys [ metric-name]}] (let [mce (MulticlassClassificationEvaluator.)] (when metric-name (.setMetricName mce metric-name)) mce))) (defn avg-cv-metrics "Takes 2 arguments, the first is the Crossvalidator, the second is the data frame to run CV on. Returns a seq of average metrics by training the model on cross validated sets of data. The metric is specified in the evaluator object" [^CrossValidatorModel cv df] (seq (.avgMetrics (.fit cv df)))) (defn tv-metrics "Takes 2 arguments, the first is the TraintestValidator, the second is the data frame to run TV on. Returns the validation metrics. The metric is specified in the evaluator object" [^TrainValidationSplitModel tv df] (seq (.validationMetrics (.fit tv df)))) (defn cross-validator "Takes a map argument where mandatory keys are :estimator (e.g. a classifier like LogisticRegression) and :evaluator. (e.g. a BinaryClassificationEvaluator) Returns a cross-validator. " [{:keys [estimator evaluator estimator-param-maps num-folds] :as m}] {:pre [(every? m [:estimator :evaluator])]} (let [cv (doto (CrossValidator.) (.setEstimator estimator) (.setEvaluator evaluator) (.setEstimatorParamMaps (if estimator-param-maps estimator-param-maps (param-grid))))] (when num-folds (.setNumFolds cv num-folds)) cv)) (defn train-val-split-validator "Takes a map argument where mandatory keys are :estimator (e.g. a classifier like LogisticRegression) and :evaluator. (e.g. a BinaryClassificationEvaluator) . Returns a train-validation split object. " [{:keys [estimator evaluator estimator-param-maps train-ratio] :as m}] {:pre [(every? m [:estimator :evaluator])]} (let [tv (doto (TrainValidationSplit.) (.setEstimator estimator) (.setEvaluator evaluator) (.setEstimatorParamMaps (if estimator-param-maps estimator-param-maps (param-grid))))] (when train-ratio (.setTrainRatio tv train-ratio)) tv))
null
https://raw.githubusercontent.com/gorillalabs/sparkling/ffedcc70fd46bf1b48405be8b1f5a1e1c4f9f578/src/clojure/sparkling/ml/validation.clj
clojure
(ns sparkling.ml.validation (:import [org.apache.spark.api.java JavaRDD JavaPairRDD JavaSparkContext] [org.apache.spark.ml.tuning ParamGridBuilder CrossValidator CrossValidatorModel TrainValidationSplit TrainValidationSplitModel] [org.apache.spark.ml.param ParamMap] [org.apache.spark.mllib.evaluation BinaryClassificationMetrics ] [org.apache.spark.mllib.regression LabeledPoint] [org.apache.spark.ml Pipeline PipelineModel PipelineStage] [org.apache.spark.ml.evaluation BinaryClassificationEvaluator MulticlassClassificationEvaluator] [org.apache.spark.sql SQLContext Dataset RowFactory Row Encoders Encoder])) (defn param-grid "Return a ParamMap array, built using ParamGridBuilder . Values is a seq where every element is a 2-element vector. The first is the parameter name and the second is the list of values " ([] (.build (ParamGridBuilder.))) ([values] (.build (reduce (fn[pgb [k v]] (.addGrid pgb k v) ) (ParamGridBuilder.) values)))) (defn binary-classification-evaluator "Returns a BinaryClassificationEvaluator object. The default metric is areaUnderROC. The other metric available is 'areaUnderPR' " ([] (binary-classification-evaluator {})) ([{:keys [metric-name]}] (let [bce (BinaryClassificationEvaluator.)] (when metric-name (.setMetricName bce metric-name)) bce))) (defn multiclass-classification-evaluator "Returns a MulticlassClassificationEvaluator object. The default metric is f1. The other metrics available are 'precision','recall', 'weightedPrecision','weightedRecall'" ([] (multiclass-classification-evaluator {})) ([{:keys [ metric-name]}] (let [mce (MulticlassClassificationEvaluator.)] (when metric-name (.setMetricName mce metric-name)) mce))) (defn avg-cv-metrics "Takes 2 arguments, the first is the Crossvalidator, the second is the data frame to run CV on. Returns a seq of average metrics by training the model on cross validated sets of data. The metric is specified in the evaluator object" [^CrossValidatorModel cv df] (seq (.avgMetrics (.fit cv df)))) (defn tv-metrics "Takes 2 arguments, the first is the TraintestValidator, the second is the data frame to run TV on. Returns the validation metrics. The metric is specified in the evaluator object" [^TrainValidationSplitModel tv df] (seq (.validationMetrics (.fit tv df)))) (defn cross-validator "Takes a map argument where mandatory keys are :estimator (e.g. a classifier like LogisticRegression) and :evaluator. (e.g. a BinaryClassificationEvaluator) Returns a cross-validator. " [{:keys [estimator evaluator estimator-param-maps num-folds] :as m}] {:pre [(every? m [:estimator :evaluator])]} (let [cv (doto (CrossValidator.) (.setEstimator estimator) (.setEvaluator evaluator) (.setEstimatorParamMaps (if estimator-param-maps estimator-param-maps (param-grid))))] (when num-folds (.setNumFolds cv num-folds)) cv)) (defn train-val-split-validator "Takes a map argument where mandatory keys are :estimator (e.g. a classifier like LogisticRegression) and :evaluator. (e.g. a BinaryClassificationEvaluator) . Returns a train-validation split object. " [{:keys [estimator evaluator estimator-param-maps train-ratio] :as m}] {:pre [(every? m [:estimator :evaluator])]} (let [tv (doto (TrainValidationSplit.) (.setEstimator estimator) (.setEvaluator evaluator) (.setEstimatorParamMaps (if estimator-param-maps estimator-param-maps (param-grid))))] (when train-ratio (.setTrainRatio tv train-ratio)) tv))
5424e5678f98d2c8c64f56d46bb5856a2f9b6f68b120b896c795120a0f8bab41
stedolan/ocaml-afl-persistent
aflPersistent.mli
val run : (unit -> unit) -> unit
null
https://raw.githubusercontent.com/stedolan/ocaml-afl-persistent/a37c4f581ba417d7e09a6efb34fdd8a90a7e9ede/aflPersistent.mli
ocaml
val run : (unit -> unit) -> unit
03bd01d7df34e4657ed9813f654770aa0c50898c3a752dacb7d9c695b2dd1c21
vim-erlang/vim-erlang-tags
vim-erlang-tags.erl
#!/usr/bin/env escript -mode(compile). main(_Args) -> Help = "The vim-erlang-tags.erl script has been moved to vim_erlang_tags.erl. Please use that script instead." , io:format("~s", [Help]).
null
https://raw.githubusercontent.com/vim-erlang/vim-erlang-tags/d7eaa8f6986de0f266dac48b7dcfbf41d67ce611/bin/vim-erlang-tags.erl
erlang
#!/usr/bin/env escript -mode(compile). main(_Args) -> Help = "The vim-erlang-tags.erl script has been moved to vim_erlang_tags.erl. Please use that script instead." , io:format("~s", [Help]).
57fa15eb6c8f1e53277d5bcb84d7b56027ea9a90123a53dd8addab419b933db2
circleci/stefon
expires.clj
(ns stefon.middleware.expires "Middleware for overriding expiration headers for cached Stefon resources" (:require [ring.util.response :as res] [ring.middleware.file :as file] [stefon.path :as path] [stefon.util :refer (dump)]) (:import (java.util Date Locale TimeZone) java.text.SimpleDateFormat)) (defn ^SimpleDateFormat make-http-format "Formats or parses dates into HTTP date format (RFC 822/1123)." [] (doto (SimpleDateFormat. "EEE, dd MMM yyyy HH:mm:ss ZZZ" Locale/US) (.setTimeZone (TimeZone/getTimeZone "UTC")))) (defn wrap-expires-never "Middleware that overrides any existing headers for browser-side caching. This is meant to be used with Stefon's cached resources, since it sets the expiration headers to one year in the future (maximum suggested as per RFC 2616, Sec. 14.21)." [handler & [opts]] (fn [req] (if-let [resp (handler req)] (res/header resp "Expires" (.format (make-http-format) (Date. (+ (System/currentTimeMillis) (* 1000 1 365 24 60 60)))))))) (defn wrap-file-expires-never "Given a root path to the previously cached Stefon resources, check that the request points to something that is a cacheable URL for a precompiled resource. If so, pass the request to the ring file middleware and then set the expiration header, otherwise just pass the request along to the handlers down the chain." [app root-path & [opts]] (fn [req] (let [path (:uri req)] (if (path/asset-uri? path) (if-let [resp ((file/wrap-file (constantly nil) root-path) req)] (res/header resp "Expires" (.format (make-http-format) (Date. (+ (System/currentTimeMillis) (* 1000 1 365 24 60 60))))) (app req)) (app req)))))
null
https://raw.githubusercontent.com/circleci/stefon/7c36114923ef7ec41316e22354d2e31217a1a416/stefon-core/src/stefon/middleware/expires.clj
clojure
(ns stefon.middleware.expires "Middleware for overriding expiration headers for cached Stefon resources" (:require [ring.util.response :as res] [ring.middleware.file :as file] [stefon.path :as path] [stefon.util :refer (dump)]) (:import (java.util Date Locale TimeZone) java.text.SimpleDateFormat)) (defn ^SimpleDateFormat make-http-format "Formats or parses dates into HTTP date format (RFC 822/1123)." [] (doto (SimpleDateFormat. "EEE, dd MMM yyyy HH:mm:ss ZZZ" Locale/US) (.setTimeZone (TimeZone/getTimeZone "UTC")))) (defn wrap-expires-never "Middleware that overrides any existing headers for browser-side caching. This is meant to be used with Stefon's cached resources, since it sets the expiration headers to one year in the future (maximum suggested as per RFC 2616, Sec. 14.21)." [handler & [opts]] (fn [req] (if-let [resp (handler req)] (res/header resp "Expires" (.format (make-http-format) (Date. (+ (System/currentTimeMillis) (* 1000 1 365 24 60 60)))))))) (defn wrap-file-expires-never "Given a root path to the previously cached Stefon resources, check that the request points to something that is a cacheable URL for a precompiled resource. If so, pass the request to the ring file middleware and then set the expiration header, otherwise just pass the request along to the handlers down the chain." [app root-path & [opts]] (fn [req] (let [path (:uri req)] (if (path/asset-uri? path) (if-let [resp ((file/wrap-file (constantly nil) root-path) req)] (res/header resp "Expires" (.format (make-http-format) (Date. (+ (System/currentTimeMillis) (* 1000 1 365 24 60 60))))) (app req)) (app req)))))
0f490980f837e2ed294399a2edd4ec27cbc6716edcbdf4fd275a68f3c378bf9c
cmsc430/www
env.rkt
#lang racket (provide lookup ext) ;; Env Variable -> Answer (define (lookup env x) (match env ['() 'err] [(cons (list y i) env) (match (symbol=? x y) [#t i] [#f (lookup env x)])])) ;; Env Variable Value -> Value (define (ext r x i) (cons (list x i) r))
null
https://raw.githubusercontent.com/cmsc430/www/3a2cc63191b75e477660961794958cead7cae35a/langs/outlaw/env.rkt
racket
Env Variable -> Answer Env Variable Value -> Value
#lang racket (provide lookup ext) (define (lookup env x) (match env ['() 'err] [(cons (list y i) env) (match (symbol=? x y) [#t i] [#f (lookup env x)])])) (define (ext r x i) (cons (list x i) r))
df884ed0e63fe000176ea4b723531d1cb1027bae62a2bcc23337839bb9837503
lulf/hcoap
Main.hs
import Network.CoAP.Server import Network.CoAP.Transport import Network.Socket import qualified Data.ByteString.Char8 as B findPath :: [Option] -> B.ByteString findPath [] = B.empty findPath (option:options) = case option of UriPath value -> value _ -> findPath options requestHandler :: RequestHandler requestHandler (request, _) = do let options = requestOptions request let path = findPath options let payload = Just (B.pack ("{\"path\":\"" ++ B.unpack path ++ "\"}")) return (Response Content [ContentFormat ApplicationJson] payload) main :: IO () main = withSocketsDo $ do sock <- socket AF_INET6 Datagram defaultProtocol bind sock (SockAddrInet6 12345 0 (0, 0, 0, 0) 0) server <- createServer (createUDPTransport sock) requestHandler runServer server
null
https://raw.githubusercontent.com/lulf/hcoap/8127520b767430b5513be6cfe646894ae7a2e616/example-server/Main.hs
haskell
import Network.CoAP.Server import Network.CoAP.Transport import Network.Socket import qualified Data.ByteString.Char8 as B findPath :: [Option] -> B.ByteString findPath [] = B.empty findPath (option:options) = case option of UriPath value -> value _ -> findPath options requestHandler :: RequestHandler requestHandler (request, _) = do let options = requestOptions request let path = findPath options let payload = Just (B.pack ("{\"path\":\"" ++ B.unpack path ++ "\"}")) return (Response Content [ContentFormat ApplicationJson] payload) main :: IO () main = withSocketsDo $ do sock <- socket AF_INET6 Datagram defaultProtocol bind sock (SockAddrInet6 12345 0 (0, 0, 0, 0) 0) server <- createServer (createUDPTransport sock) requestHandler runServer server
491d0e8a6824d3673cd2e5bee6baac91b482d1bcb126c864e844b1d91382a07e
cblp/crdt
TwoPSet.hs
module CRDT.Cv.TwoPSet ( TwoPSet (..) , add , initial , member , remove , singleton , isKnown ) where import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map import Data.Semilattice (Semilattice) newtype TwoPSet a = TwoPSet (Map a Bool) deriving (Eq, Show) instance Ord a => Semigroup (TwoPSet a) where TwoPSet m1 <> TwoPSet m2 = TwoPSet (Map.unionWith (&&) m1 m2) instance Ord a => Semilattice (TwoPSet a) add :: Ord a => a -> TwoPSet a -> TwoPSet a add e (TwoPSet m) = TwoPSet (Map.insertWith (&&) e True m) initial :: TwoPSet a initial = TwoPSet Map.empty member :: Ord a => a -> TwoPSet a -> Bool member e (TwoPSet m) = Just True == Map.lookup e m remove :: Ord a => a -> TwoPSet a -> TwoPSet a remove e (TwoPSet m) = TwoPSet $ Map.adjust (const False) e m singleton :: Ord a => a -> TwoPSet a singleton a = add a initial -- | XXX Internal isKnown :: Ord a => a -> TwoPSet a -> Bool isKnown e (TwoPSet m) = Map.member e m
null
https://raw.githubusercontent.com/cblp/crdt/175d7ee7df66de1f013ee167ac31719752e0c20b/crdt/lib/CRDT/Cv/TwoPSet.hs
haskell
| XXX Internal
module CRDT.Cv.TwoPSet ( TwoPSet (..) , add , initial , member , remove , singleton , isKnown ) where import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map import Data.Semilattice (Semilattice) newtype TwoPSet a = TwoPSet (Map a Bool) deriving (Eq, Show) instance Ord a => Semigroup (TwoPSet a) where TwoPSet m1 <> TwoPSet m2 = TwoPSet (Map.unionWith (&&) m1 m2) instance Ord a => Semilattice (TwoPSet a) add :: Ord a => a -> TwoPSet a -> TwoPSet a add e (TwoPSet m) = TwoPSet (Map.insertWith (&&) e True m) initial :: TwoPSet a initial = TwoPSet Map.empty member :: Ord a => a -> TwoPSet a -> Bool member e (TwoPSet m) = Just True == Map.lookup e m remove :: Ord a => a -> TwoPSet a -> TwoPSet a remove e (TwoPSet m) = TwoPSet $ Map.adjust (const False) e m singleton :: Ord a => a -> TwoPSet a singleton a = add a initial isKnown :: Ord a => a -> TwoPSet a -> Bool isKnown e (TwoPSet m) = Map.member e m
2a2df0e21e0352ffc13eb766b983115dc4ee3814cd2d5f66a04299c38f0b9190
Clojure2D/clojure2d-examples
motion101_acceleration_list_1_11.clj
(ns examples.NOC.ch01.motion101-acceleration-list-1-11 (:require [clojure2d.core :refer :all] [fastmath.random :as r] [fastmath.vector :as v] [clojure2d.color :as c]) (:import fastmath.vector.Vec2)) (set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (def ^:const ^double topspeed 5.0) (def ^:const ^int movers-no 20) (defprotocol MoverProto (update-mover [t window]) (display-mover [t canvas])) (deftype Mover [^Vec2 position velocity] MoverProto (update-mover [_ window] (let [acceleration (-> (mouse-pos window) (v/sub position) (v/normalize) (v/mult 0.2)) nvelocity (-> velocity (v/add acceleration) (v/limit topspeed)) ^Vec2 nposition (v/add position velocity)] (Mover. nposition nvelocity))) (display-mover [m canvas] (-> canvas (set-stroke 2.0) (filled-with-stroke (c/gray 127 200) :black ellipse (.x position) (.y position) 48 48)) m)) (defn make-mover "Create random Mover" [w h] (Mover. (Vec2. (r/drand w) (r/drand h)) (Vec2. 0 0))) (defn draw "Process and display Movers" [canvas window _ movers] (let [m (or movers (repeatedly movers-no #(make-mover (width window) (height window))))] (set-background canvas 255 255 255) (mapv #(display-mover (update-mover % window) canvas) m))) (def window (show-window (canvas 640 360) "Motion 101 Acceleration List (1.11)" draw)) ;; it's slower than original version, probably due to overhead in mapv and immutable way of updating
null
https://raw.githubusercontent.com/Clojure2D/clojure2d-examples/9de82f5ac0737b7e78e07a17cf03ac577d973817/src/NOC/ch01/motion101_acceleration_list_1_11.clj
clojure
it's slower than original version, probably due to overhead in mapv and immutable way of updating
(ns examples.NOC.ch01.motion101-acceleration-list-1-11 (:require [clojure2d.core :refer :all] [fastmath.random :as r] [fastmath.vector :as v] [clojure2d.color :as c]) (:import fastmath.vector.Vec2)) (set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (def ^:const ^double topspeed 5.0) (def ^:const ^int movers-no 20) (defprotocol MoverProto (update-mover [t window]) (display-mover [t canvas])) (deftype Mover [^Vec2 position velocity] MoverProto (update-mover [_ window] (let [acceleration (-> (mouse-pos window) (v/sub position) (v/normalize) (v/mult 0.2)) nvelocity (-> velocity (v/add acceleration) (v/limit topspeed)) ^Vec2 nposition (v/add position velocity)] (Mover. nposition nvelocity))) (display-mover [m canvas] (-> canvas (set-stroke 2.0) (filled-with-stroke (c/gray 127 200) :black ellipse (.x position) (.y position) 48 48)) m)) (defn make-mover "Create random Mover" [w h] (Mover. (Vec2. (r/drand w) (r/drand h)) (Vec2. 0 0))) (defn draw "Process and display Movers" [canvas window _ movers] (let [m (or movers (repeatedly movers-no #(make-mover (width window) (height window))))] (set-background canvas 255 255 255) (mapv #(display-mover (update-mover % window) canvas) m))) (def window (show-window (canvas 640 360) "Motion 101 Acceleration List (1.11)" draw))
c6621e95acaf8cb7f64880ad2b0f16a7b7fc4d498828e6c4b92d0d57ff08bd35
jeffshrager/biobike
converter.lisp
(in-package :pb) ;;; This has to be loaded into the running Trouble server and ;;; excecuted. It does a major reorganization of the knowledge ;;; base. (defvar *pub-id->frame* (make-hash-table :test #'equal)) (defvar *author-id->frame* (make-hash-table :test #'equal)) (defvar *temp-table* (make-hash-table :test #'equal)) (defvar *pdb* nil) ; Server connection (defvar *year-frames* nil) (eval-when (:compile-toplevel :load-toplevel :execute) (export '(*year-frames*))) (defun reorg-and-thread-trbl (&key (minyear 1991) (reload? nil) (authors? t)) (when reload? ; Get the descriptions?? (load-organism :arabidopsis_thaliana :descriptions? t :reload? t)) (setq *pdb* (make-db-server-connection :mysql :dbname "isipubtest" :cl-user "trbl" :file "/var/lib/mysql/mysql.sock")) (cformatt "Doing base load") (rearrange-base-load) (cformatt "Doing publications.") (arrange-publications minyear) (when authors? (cformatt "Doing authors") (arrange-authors)) (misc-final-setup) (clrhash *temp-table*) (cformatt "Reorg and thread complete.") ) (defun rearrange-base-load () ;; The #^genes are actually gene models; For each we create a ;; locus object which holds onto the positions, and the genes point ;; to the loci. The loci get stored in a hash table, and then ;; stuck into the chromosomes. (loop for cs in (#^Contiguous-Sequences #$arabidopsis_thaliana) do (clrhash *temp-table*) (loop for gene-model across (#^Genes-Sorted-by-Position cs) as from = (#^from gene-model) as to = (#^to gene-model) as locusid = (#^locus-id gene-model) as locus = (gethash locusid *temp-table*) do (when (null locus) (setq locus (frame-fnamed (format nil "Gene.~a" locusid) t)) (setf (gethash locusid *temp-table*) locus) (setf (#^from locus) from) (setf (#^to locus) to) (setf (#^Contiguous-Sequence locus) cs) (push locus (#^loci #$arabidopsis_thaliana)) ) (push gene-model (#^gene-models locus)) (setf (#^locus gene-model) locus)) ;; Now jam the loci back into the chromosome (setf (#^loci cs) (lmaphash #'(lambda (k v) (declare (ignore k)) v) *temp-table*)) ) ;; Reset the gene and gene-models for the organism, and whack the loci! (setf (#^gene-models #$arabidopsis_thaliana) (#^genes #$arabidopsis_thaliana)) (setf (#^genes #$arabidopsis_thaliana) (#^loci #$arabidopsis_thaliana)) Now we can thread the model into the loci . More could be done here . ;; (This should go into the postload for aracyc!) (mapframes #'(lambda (frame) (when (eq :ocelot (#^source frame)) (let* ((gene (#^oc.gene frame)) (cname (and gene (isframe? gene) (#^oc.common-name gene))) (locus (frame-fnamed (format nil "Gene.~a" cname)))) (when locus (setf (#^gene gene) locus) (setf (#^oc.gene locus) gene) (setf (#^oc.dblinks gene) (cons locus (remove gene (#^oc.dblinks gene))))) )))) Remove remnant nils from the GO - ID slots which were left from postload go - id conversion where no go concept was found . These nils ;; screw everyone downsteam. (loop for gene-model in (#^gene-models #$arabidopsis_thaliana) do (setf (#^go-id gene-model) (remove-duplicates (remove nil (#^go-id gene-model))))) ) (defun arrange-publications (minyear) (clrhash *pub-id->frame*) ; This will be used to facilitate author binding (loop for (string-year title gene pub-gene-id pub-id nil) in (xsql *pdb* (one-string "select all publication.year, publication.title, " "genes.gene, genes.pub_gene_id, gene_match.pub_id, " "gene_match.gene_id from publication, genes, gene_match " "where genes.gene_id = gene_match.gene_id and " "publication.pub_id = gene_match.pub_id;")) Could be nil if the gene is n't in TAIR as year = (parse-integer string-year) when (>= year minyear) do (let ((pub-frame (frame-fnamed (format nil "Pub.~a" pub-id) t))) (when gene-frame (push pub-frame (#^pubs gene-frame))) ;; Set up all the info on the publication frame (which may already exist). (push gene (#^gene-names pub-frame)) (if gene-frame (push gene-frame (#^genes pub-frame)) (push gene (#^genes-not-found pub-frame))) (setf (#^year pub-frame) year) (setf (#^pub-id pub-frame) pub-id) (setf (#^pub-gene-id pub-frame) pub-gene-id) (setf (#^title pub-frame) title) (setf (gethash pub-id *pub-id->frame*) pub-frame) )) Create year frames containing pubs for that year . (setq *year-frames* nil) (for-all-frames (f) (when (initial-subsequence-of? (#^fname f) "Pub.") (let* ((year (#^year f)) (yf (frame-fnamed (formatn "Year.~a" year) t))) (setf (#^year yf) year) (pushnew yf *year-frames* :test #'eq) (push f (#^pubs yf))))) ;; Sort them into chron order: (setq *year-frames* (sort *year-frames* #'< :key #'#^year)) ) (defun arrange-authors () (clrhash *author-id->frame*) (loop for (author-id pub-id author-name) in (xsql *pdb* (one-string "select author.author_id, publication.pub_id, " "author.author_name from author, map_auth, " "publication where publication.pub_id = map_auth.pub_id " "and map_auth.author_id = author.author_id")) as auth-frame = (frame-fnamed (format nil "Author.~a" author-id) t) as pub-frame = (gethash pub-id *pub-id->frame*) do (setf (gethash author-id *author-id->frame*) auth-frame) (setf (#^author-id auth-frame) author-id) (setf (#^name auth-frame) author-name) (when pub-frame (push pub-frame (#^pubs auth-frame)) (push auth-frame (#^authors pub-frame))) ) Assign PI author frames to each publication and . (let ((aids/piids (xsql pb::*pdb* "select author.author_id, auth2api.pi_id from author, auth2api where author.author_id = auth2api.author_id ")) (pubids/pidds (xsql pb::*pdb* "select arpiTpubs.pub_id, arpiTpubs.pi_id from arpiTpubs")) ) (clrhash *temp-table*) (loop for (aiid piid) in aids/piids do (setf (gethash piid *temp-table*) (gethash aiid *author-id->frame*))) (loop for (pubid piid) in pubids/pidds as auth-frame = (gethash piid *temp-table*) as pub-frame = (gethash pubid *pub-id->frame*) when (and auth-frame pub-frame) do (setf (#^pi pub-frame) auth-frame) (push pub-frame (#^pid-pubs auth-frame))) ) ) (defun misc-final-setup () Create the parent path in each GO frame . (loop for frame in *go-frames* do (setf (#^parents frame) (frame->related-and-containing-frames frame #$isa))))
null
https://raw.githubusercontent.com/jeffshrager/biobike/5313ec1fe8e82c21430d645e848ecc0386436f57/BioLisp/Trbl/converter.lisp
lisp
This has to be loaded into the running Trouble server and excecuted. It does a major reorganization of the knowledge base. Server connection Get the descriptions?? The #^genes are actually gene models; For each we create a locus object which holds onto the positions, and the genes point to the loci. The loci get stored in a hash table, and then stuck into the chromosomes. Now jam the loci back into the chromosome Reset the gene and gene-models for the organism, and whack the loci! (This should go into the postload for aracyc!) screw everyone downsteam. This will be used to facilitate author binding Set up all the info on the publication frame (which may already exist). Sort them into chron order:
(in-package :pb) (defvar *pub-id->frame* (make-hash-table :test #'equal)) (defvar *author-id->frame* (make-hash-table :test #'equal)) (defvar *temp-table* (make-hash-table :test #'equal)) (defvar *year-frames* nil) (eval-when (:compile-toplevel :load-toplevel :execute) (export '(*year-frames*))) (defun reorg-and-thread-trbl (&key (minyear 1991) (reload? nil) (authors? t)) (load-organism :arabidopsis_thaliana :descriptions? t :reload? t)) (setq *pdb* (make-db-server-connection :mysql :dbname "isipubtest" :cl-user "trbl" :file "/var/lib/mysql/mysql.sock")) (cformatt "Doing base load") (rearrange-base-load) (cformatt "Doing publications.") (arrange-publications minyear) (when authors? (cformatt "Doing authors") (arrange-authors)) (misc-final-setup) (clrhash *temp-table*) (cformatt "Reorg and thread complete.") ) (defun rearrange-base-load () (loop for cs in (#^Contiguous-Sequences #$arabidopsis_thaliana) do (clrhash *temp-table*) (loop for gene-model across (#^Genes-Sorted-by-Position cs) as from = (#^from gene-model) as to = (#^to gene-model) as locusid = (#^locus-id gene-model) as locus = (gethash locusid *temp-table*) do (when (null locus) (setq locus (frame-fnamed (format nil "Gene.~a" locusid) t)) (setf (gethash locusid *temp-table*) locus) (setf (#^from locus) from) (setf (#^to locus) to) (setf (#^Contiguous-Sequence locus) cs) (push locus (#^loci #$arabidopsis_thaliana)) ) (push gene-model (#^gene-models locus)) (setf (#^locus gene-model) locus)) (setf (#^loci cs) (lmaphash #'(lambda (k v) (declare (ignore k)) v) *temp-table*)) ) (setf (#^gene-models #$arabidopsis_thaliana) (#^genes #$arabidopsis_thaliana)) (setf (#^genes #$arabidopsis_thaliana) (#^loci #$arabidopsis_thaliana)) Now we can thread the model into the loci . More could be done here . (mapframes #'(lambda (frame) (when (eq :ocelot (#^source frame)) (let* ((gene (#^oc.gene frame)) (cname (and gene (isframe? gene) (#^oc.common-name gene))) (locus (frame-fnamed (format nil "Gene.~a" cname)))) (when locus (setf (#^gene gene) locus) (setf (#^oc.gene locus) gene) (setf (#^oc.dblinks gene) (cons locus (remove gene (#^oc.dblinks gene))))) )))) Remove remnant nils from the GO - ID slots which were left from postload go - id conversion where no go concept was found . These nils (loop for gene-model in (#^gene-models #$arabidopsis_thaliana) do (setf (#^go-id gene-model) (remove-duplicates (remove nil (#^go-id gene-model))))) ) (defun arrange-publications (minyear) (loop for (string-year title gene pub-gene-id pub-id nil) in (xsql *pdb* (one-string "select all publication.year, publication.title, " "genes.gene, genes.pub_gene_id, gene_match.pub_id, " "gene_match.gene_id from publication, genes, gene_match " "where genes.gene_id = gene_match.gene_id and " "publication.pub_id = gene_match.pub_id;")) Could be nil if the gene is n't in TAIR as year = (parse-integer string-year) when (>= year minyear) do (let ((pub-frame (frame-fnamed (format nil "Pub.~a" pub-id) t))) (when gene-frame (push pub-frame (#^pubs gene-frame))) (push gene (#^gene-names pub-frame)) (if gene-frame (push gene-frame (#^genes pub-frame)) (push gene (#^genes-not-found pub-frame))) (setf (#^year pub-frame) year) (setf (#^pub-id pub-frame) pub-id) (setf (#^pub-gene-id pub-frame) pub-gene-id) (setf (#^title pub-frame) title) (setf (gethash pub-id *pub-id->frame*) pub-frame) )) Create year frames containing pubs for that year . (setq *year-frames* nil) (for-all-frames (f) (when (initial-subsequence-of? (#^fname f) "Pub.") (let* ((year (#^year f)) (yf (frame-fnamed (formatn "Year.~a" year) t))) (setf (#^year yf) year) (pushnew yf *year-frames* :test #'eq) (push f (#^pubs yf))))) (setq *year-frames* (sort *year-frames* #'< :key #'#^year)) ) (defun arrange-authors () (clrhash *author-id->frame*) (loop for (author-id pub-id author-name) in (xsql *pdb* (one-string "select author.author_id, publication.pub_id, " "author.author_name from author, map_auth, " "publication where publication.pub_id = map_auth.pub_id " "and map_auth.author_id = author.author_id")) as auth-frame = (frame-fnamed (format nil "Author.~a" author-id) t) as pub-frame = (gethash pub-id *pub-id->frame*) do (setf (gethash author-id *author-id->frame*) auth-frame) (setf (#^author-id auth-frame) author-id) (setf (#^name auth-frame) author-name) (when pub-frame (push pub-frame (#^pubs auth-frame)) (push auth-frame (#^authors pub-frame))) ) Assign PI author frames to each publication and . (let ((aids/piids (xsql pb::*pdb* "select author.author_id, auth2api.pi_id from author, auth2api where author.author_id = auth2api.author_id ")) (pubids/pidds (xsql pb::*pdb* "select arpiTpubs.pub_id, arpiTpubs.pi_id from arpiTpubs")) ) (clrhash *temp-table*) (loop for (aiid piid) in aids/piids do (setf (gethash piid *temp-table*) (gethash aiid *author-id->frame*))) (loop for (pubid piid) in pubids/pidds as auth-frame = (gethash piid *temp-table*) as pub-frame = (gethash pubid *pub-id->frame*) when (and auth-frame pub-frame) do (setf (#^pi pub-frame) auth-frame) (push pub-frame (#^pid-pubs auth-frame))) ) ) (defun misc-final-setup () Create the parent path in each GO frame . (loop for frame in *go-frames* do (setf (#^parents frame) (frame->related-and-containing-frames frame #$isa))))
d45c64d4422db49c54679595b4337e7c36caa3c33df317f0fc2d1eb377b509e7
c4-project/c4f
abstract_expr.mli
This file is part of c4f . Copyright ( c ) 2018 - 2022 C4 Project c4 t itself is licensed under the MIT License . See the LICENSE file in the project root for more information . Parts of c4 t are based on code from the Herdtools7 project ( ) : see the LICENSE.herd file in the project root for more information . Copyright (c) 2018-2022 C4 Project c4t itself is licensed under the MIT License. See the LICENSE file in the project root for more information. Parts of c4t are based on code from the Herdtools7 project () : see the LICENSE.herd file in the project root for more information. *) * Abstracting expression ASTs into FIR . See { ! Abstract } for the big picture . See {!Abstract} for the big picture. *) open Base val model : Ast.Expr.t -> C4f_fir.Expression.t Or_error.t * [ model ast ] tries to model a C expression AST as a FIR expression .
null
https://raw.githubusercontent.com/c4-project/c4f/8939477732861789abc807c8c1532a302b2848a5/lib/litmus_c/src/abstract_expr.mli
ocaml
This file is part of c4f . Copyright ( c ) 2018 - 2022 C4 Project c4 t itself is licensed under the MIT License . See the LICENSE file in the project root for more information . Parts of c4 t are based on code from the Herdtools7 project ( ) : see the LICENSE.herd file in the project root for more information . Copyright (c) 2018-2022 C4 Project c4t itself is licensed under the MIT License. See the LICENSE file in the project root for more information. Parts of c4t are based on code from the Herdtools7 project () : see the LICENSE.herd file in the project root for more information. *) * Abstracting expression ASTs into FIR . See { ! Abstract } for the big picture . See {!Abstract} for the big picture. *) open Base val model : Ast.Expr.t -> C4f_fir.Expression.t Or_error.t * [ model ast ] tries to model a C expression AST as a FIR expression .
22ff3e244757ec525d3c01a3789aab67e5475c3edaf59cfad8266ef3153d76b5
JeanHuguesdeRaigniac/effects-landscape
Polysemy.hs
module Internal.Polysemy ( module Polysemy, module Polysemy.Error, module Polysemy.Reader, module Polysemy.State, module Polysemy.Trace, module Polysemy.Writer, Trace embeddedLog, -- Error throwError, State get, ) where import Polysemy import Polysemy.Error import Polysemy.Reader import Polysemy.State hiding (get) import qualified Polysemy.State as State import Polysemy.Trace import Polysemy.Writer import Types (Steps, Value) embeddedLog :: Member Trace r => String -> Sem r () embeddedLog = trace throwError :: Member (Error String) r => String -> Sem r Value throwError = throw get :: Member (State Steps) r => Sem r Steps get = State.get
null
https://raw.githubusercontent.com/JeanHuguesdeRaigniac/effects-landscape/e44aea11053ac4db85b862fab027d3777d35e232/app/Internal/Polysemy.hs
haskell
Error
module Internal.Polysemy ( module Polysemy, module Polysemy.Error, module Polysemy.Reader, module Polysemy.State, module Polysemy.Trace, module Polysemy.Writer, Trace embeddedLog, throwError, State get, ) where import Polysemy import Polysemy.Error import Polysemy.Reader import Polysemy.State hiding (get) import qualified Polysemy.State as State import Polysemy.Trace import Polysemy.Writer import Types (Steps, Value) embeddedLog :: Member Trace r => String -> Sem r () embeddedLog = trace throwError :: Member (Error String) r => String -> Sem r Value throwError = throw get :: Member (State Steps) r => Sem r Steps get = State.get
693eea68255325b12e9c00e004fc86af16b1384e8774017375d9e26ef86c0a55
lixiangqi/medic
src3-medic.rkt
#lang medic (layer layer1 (in #:module "src3.rkt" ; scope of multiple functions [(g inc) [on-entry @log{function @function-name : x = @x}]] ; each-function primitive [each-function [on-entry @log{function @function-name entered}]]))
null
https://raw.githubusercontent.com/lixiangqi/medic/0920090d3c77d6873b8481841622a5f2d13a732c/demos/demo3/src3-medic.rkt
racket
scope of multiple functions each-function primitive
#lang medic (layer layer1 (in #:module "src3.rkt" [(g inc) [on-entry @log{function @function-name : x = @x}]] [each-function [on-entry @log{function @function-name entered}]]))
360a0f84cb1bc33842ba4f70ed6146ad2751c28562ec640ea105aeb78075dd2f
ghosthamlet/algorithm-data-structure
project.clj
(defproject algorithm-data-structure "0.1.0-SNAPSHOT" :description "FIXME: write description" :url "" :license {:name "Eclipse Public License" :url "-v10.html"} :plugins [[lein-kibit "0.1.6"] check / fix [lein-cljfmt "0.5.7"] [lein-with-env-vars "0.1.0"]] use neanderthal : with - env - vars repl :env-vars {:LD_LIBRARY_PATH "/opt/intel/mkl/lib/intel64:/opt/intel/lib"} ;; category thoery to reduce functional programming duplicate codes? :dependencies [[org.clojure/clojure "1.9.0"] [uncomplicate/neanderthal "0.21.0"]])
null
https://raw.githubusercontent.com/ghosthamlet/algorithm-data-structure/017f41a79d8b1d62ff5a6cceffa1b0f0ad3ead6b/project.clj
clojure
category thoery to reduce functional programming duplicate codes?
(defproject algorithm-data-structure "0.1.0-SNAPSHOT" :description "FIXME: write description" :url "" :license {:name "Eclipse Public License" :url "-v10.html"} :plugins [[lein-kibit "0.1.6"] check / fix [lein-cljfmt "0.5.7"] [lein-with-env-vars "0.1.0"]] use neanderthal : with - env - vars repl :env-vars {:LD_LIBRARY_PATH "/opt/intel/mkl/lib/intel64:/opt/intel/lib"} :dependencies [[org.clojure/clojure "1.9.0"] [uncomplicate/neanderthal "0.21.0"]])
bf7fa71fddec9366e3ba9f7d7bd6ce17b66a7292505ff587c83ca8be3d15be4c
pixlsus/registry.gimp.org_static
10pct_edge_guides.scm
;=============================================================== = = GIMP Add Guides Vertically and Horizontally @ 10 % and 90 % = = = = Copyright ( c ) 2006 = = ;=============================================================== (define (script-fu-10%-edge-guides img drawable) (let* ((ImageW (car (gimp-drawable-width drawable))) (ImageH (car (gimp-drawable-height drawable))) (Vert_Offset (car (gimp-drawable-offsets drawable))) (Horz_Offset (cadr (gimp-drawable-offsets drawable))) (Vert_10 (+ (* ImageW 0.1)Vert_Offset)) (Horz_10 (+ (* ImageH 0.1)Horz_Offset)) (Vert_90 (+ (* ImageW 0.9)Vert_Offset)) (Horz_90 (+ (* ImageH 0.9)Horz_Offset)) ) (gimp-image-undo-group-start img) (gimp-image-add-vguide img Vert_10) (gimp-image-add-hguide img Horz_10) (gimp-image-add-vguide img Vert_90) (gimp-image-add-hguide img Horz_90) (gimp-image-undo-group-end img) (gimp-displays-flush))) (script-fu-register "script-fu-10%-edge-guides" "<Image>/View/10% Edge Guides" "Add Guides at 10% in on all sides" "Gregory M. Ross" "Gregory M. Ross" "September 2006" "" SF-IMAGE "Image" 0 SF-DRAWABLE "Drawable" 0)
null
https://raw.githubusercontent.com/pixlsus/registry.gimp.org_static/ffcde7400f402728373ff6579947c6ffe87d1a5e/registry.gimp.org/files/10pct_edge_guides.scm
scheme
=============================================================== ===============================================================
= = GIMP Add Guides Vertically and Horizontally @ 10 % and 90 % = = = = Copyright ( c ) 2006 = = (define (script-fu-10%-edge-guides img drawable) (let* ((ImageW (car (gimp-drawable-width drawable))) (ImageH (car (gimp-drawable-height drawable))) (Vert_Offset (car (gimp-drawable-offsets drawable))) (Horz_Offset (cadr (gimp-drawable-offsets drawable))) (Vert_10 (+ (* ImageW 0.1)Vert_Offset)) (Horz_10 (+ (* ImageH 0.1)Horz_Offset)) (Vert_90 (+ (* ImageW 0.9)Vert_Offset)) (Horz_90 (+ (* ImageH 0.9)Horz_Offset)) ) (gimp-image-undo-group-start img) (gimp-image-add-vguide img Vert_10) (gimp-image-add-hguide img Horz_10) (gimp-image-add-vguide img Vert_90) (gimp-image-add-hguide img Horz_90) (gimp-image-undo-group-end img) (gimp-displays-flush))) (script-fu-register "script-fu-10%-edge-guides" "<Image>/View/10% Edge Guides" "Add Guides at 10% in on all sides" "Gregory M. Ross" "Gregory M. Ross" "September 2006" "" SF-IMAGE "Image" 0 SF-DRAWABLE "Drawable" 0)
6671cb1c5167070e354b2952b9c06e4b03ff38cc3ceae43cbe9a0b5a143b8a3c
Haskell-OpenAPI-Code-Generator/Stripe-Haskell-Library
PaymentMethodDetailsAchDebit.hs
{-# LANGUAGE MultiWayIf #-} CHANGE WITH CAUTION : This is a generated code file generated by -OpenAPI-Code-Generator/Haskell-OpenAPI-Client-Code-Generator . {-# LANGUAGE OverloadedStrings #-} -- | Contains the types generated from the schema PaymentMethodDetailsAchDebit module StripeAPI.Types.PaymentMethodDetailsAchDebit where import qualified Control.Monad.Fail import qualified Data.Aeson import qualified Data.Aeson as Data.Aeson.Encoding.Internal import qualified Data.Aeson as Data.Aeson.Types import qualified Data.Aeson as Data.Aeson.Types.FromJSON import qualified Data.Aeson as Data.Aeson.Types.Internal import qualified Data.Aeson as Data.Aeson.Types.ToJSON import qualified Data.ByteString.Char8 import qualified Data.ByteString.Char8 as Data.ByteString.Internal import qualified Data.Foldable import qualified Data.Functor import qualified Data.Maybe import qualified Data.Scientific import qualified Data.Text import qualified Data.Text.Internal import qualified Data.Time.Calendar as Data.Time.Calendar.Days import qualified Data.Time.LocalTime as Data.Time.LocalTime.Internal.ZonedTime import qualified GHC.Base import qualified GHC.Classes import qualified GHC.Int import qualified GHC.Show import qualified GHC.Types import qualified StripeAPI.Common import StripeAPI.TypeAlias import qualified Prelude as GHC.Integer.Type import qualified Prelude as GHC.Maybe -- | Defines the object schema located at @components.schemas.payment_method_details_ach_debit@ in the specification. data PaymentMethodDetailsAchDebit = PaymentMethodDetailsAchDebit | account_holder_type : Type of entity that holds the account . This can be either \`individual\ ` or \`company\ ` . paymentMethodDetailsAchDebitAccountHolderType :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable PaymentMethodDetailsAchDebitAccountHolderType'NonNullable)), -- | bank_name: Name of the bank associated with the bank account. -- -- Constraints: -- * Maximum length of 5000 paymentMethodDetailsAchDebitBankName :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable Data.Text.Internal.Text)), | country : Two - letter ISO code representing the country the bank account is located in . -- -- Constraints: -- * Maximum length of 5000 paymentMethodDetailsAchDebitCountry :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable Data.Text.Internal.Text)), | fingerprint : Uniquely identifies this particular bank account . You can use this attribute to check whether two bank accounts are the same . -- -- Constraints: -- * Maximum length of 5000 paymentMethodDetailsAchDebitFingerprint :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable Data.Text.Internal.Text)), | last4 : Last four digits of the bank account number . -- -- Constraints: -- * Maximum length of 5000 paymentMethodDetailsAchDebitLast4 :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable Data.Text.Internal.Text)), -- | routing_number: Routing transit number of the bank account. -- -- Constraints: -- * Maximum length of 5000 paymentMethodDetailsAchDebitRoutingNumber :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable Data.Text.Internal.Text)) } deriving ( GHC.Show.Show, GHC.Classes.Eq ) instance Data.Aeson.Types.ToJSON.ToJSON PaymentMethodDetailsAchDebit where toJSON obj = Data.Aeson.Types.Internal.object (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("account_holder_type" Data.Aeson.Types.ToJSON..=)) (paymentMethodDetailsAchDebitAccountHolderType obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("bank_name" Data.Aeson.Types.ToJSON..=)) (paymentMethodDetailsAchDebitBankName obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("country" Data.Aeson.Types.ToJSON..=)) (paymentMethodDetailsAchDebitCountry obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("fingerprint" Data.Aeson.Types.ToJSON..=)) (paymentMethodDetailsAchDebitFingerprint obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("last4" Data.Aeson.Types.ToJSON..=)) (paymentMethodDetailsAchDebitLast4 obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("routing_number" Data.Aeson.Types.ToJSON..=)) (paymentMethodDetailsAchDebitRoutingNumber obj) : GHC.Base.mempty)) toEncoding obj = Data.Aeson.Encoding.Internal.pairs (GHC.Base.mconcat (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("account_holder_type" Data.Aeson.Types.ToJSON..=)) (paymentMethodDetailsAchDebitAccountHolderType obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("bank_name" Data.Aeson.Types.ToJSON..=)) (paymentMethodDetailsAchDebitBankName obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("country" Data.Aeson.Types.ToJSON..=)) (paymentMethodDetailsAchDebitCountry obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("fingerprint" Data.Aeson.Types.ToJSON..=)) (paymentMethodDetailsAchDebitFingerprint obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("last4" Data.Aeson.Types.ToJSON..=)) (paymentMethodDetailsAchDebitLast4 obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("routing_number" Data.Aeson.Types.ToJSON..=)) (paymentMethodDetailsAchDebitRoutingNumber obj) : GHC.Base.mempty))) instance Data.Aeson.Types.FromJSON.FromJSON PaymentMethodDetailsAchDebit where parseJSON = Data.Aeson.Types.FromJSON.withObject "PaymentMethodDetailsAchDebit" (\obj -> (((((GHC.Base.pure PaymentMethodDetailsAchDebit GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "account_holder_type")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "bank_name")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "country")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "fingerprint")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "last4")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "routing_number")) -- | Create a new 'PaymentMethodDetailsAchDebit' with all required fields. mkPaymentMethodDetailsAchDebit :: PaymentMethodDetailsAchDebit mkPaymentMethodDetailsAchDebit = PaymentMethodDetailsAchDebit { paymentMethodDetailsAchDebitAccountHolderType = GHC.Maybe.Nothing, paymentMethodDetailsAchDebitBankName = GHC.Maybe.Nothing, paymentMethodDetailsAchDebitCountry = GHC.Maybe.Nothing, paymentMethodDetailsAchDebitFingerprint = GHC.Maybe.Nothing, paymentMethodDetailsAchDebitLast4 = GHC.Maybe.Nothing, paymentMethodDetailsAchDebitRoutingNumber = GHC.Maybe.Nothing } -- | Defines the enum schema located at @components.schemas.payment_method_details_ach_debit.properties.account_holder_type@ in the specification. -- Type of entity that holds the account . This can be either \`individual\ ` or \`company\ ` . data PaymentMethodDetailsAchDebitAccountHolderType'NonNullable = -- | This case is used if the value encountered during decoding does not match any of the provided cases in the specification. PaymentMethodDetailsAchDebitAccountHolderType'NonNullableOther Data.Aeson.Types.Internal.Value | -- | This constructor can be used to send values to the server which are not present in the specification yet. PaymentMethodDetailsAchDebitAccountHolderType'NonNullableTyped Data.Text.Internal.Text | Represents the JSON value @"company"@ PaymentMethodDetailsAchDebitAccountHolderType'NonNullableEnumCompany | Represents the JSON value @"individual"@ PaymentMethodDetailsAchDebitAccountHolderType'NonNullableEnumIndividual deriving (GHC.Show.Show, GHC.Classes.Eq) instance Data.Aeson.Types.ToJSON.ToJSON PaymentMethodDetailsAchDebitAccountHolderType'NonNullable where toJSON (PaymentMethodDetailsAchDebitAccountHolderType'NonNullableOther val) = val toJSON (PaymentMethodDetailsAchDebitAccountHolderType'NonNullableTyped val) = Data.Aeson.Types.ToJSON.toJSON val toJSON (PaymentMethodDetailsAchDebitAccountHolderType'NonNullableEnumCompany) = "company" toJSON (PaymentMethodDetailsAchDebitAccountHolderType'NonNullableEnumIndividual) = "individual" instance Data.Aeson.Types.FromJSON.FromJSON PaymentMethodDetailsAchDebitAccountHolderType'NonNullable where parseJSON val = GHC.Base.pure ( if | val GHC.Classes.== "company" -> PaymentMethodDetailsAchDebitAccountHolderType'NonNullableEnumCompany | val GHC.Classes.== "individual" -> PaymentMethodDetailsAchDebitAccountHolderType'NonNullableEnumIndividual | GHC.Base.otherwise -> PaymentMethodDetailsAchDebitAccountHolderType'NonNullableOther val )
null
https://raw.githubusercontent.com/Haskell-OpenAPI-Code-Generator/Stripe-Haskell-Library/ba4401f083ff054f8da68c741f762407919de42f/src/StripeAPI/Types/PaymentMethodDetailsAchDebit.hs
haskell
# LANGUAGE MultiWayIf # # LANGUAGE OverloadedStrings # | Contains the types generated from the schema PaymentMethodDetailsAchDebit | Defines the object schema located at @components.schemas.payment_method_details_ach_debit@ in the specification. | bank_name: Name of the bank associated with the bank account. Constraints: Constraints: Constraints: Constraints: | routing_number: Routing transit number of the bank account. Constraints: | Create a new 'PaymentMethodDetailsAchDebit' with all required fields. | Defines the enum schema located at @components.schemas.payment_method_details_ach_debit.properties.account_holder_type@ in the specification. | This case is used if the value encountered during decoding does not match any of the provided cases in the specification. | This constructor can be used to send values to the server which are not present in the specification yet.
CHANGE WITH CAUTION : This is a generated code file generated by -OpenAPI-Code-Generator/Haskell-OpenAPI-Client-Code-Generator . module StripeAPI.Types.PaymentMethodDetailsAchDebit where import qualified Control.Monad.Fail import qualified Data.Aeson import qualified Data.Aeson as Data.Aeson.Encoding.Internal import qualified Data.Aeson as Data.Aeson.Types import qualified Data.Aeson as Data.Aeson.Types.FromJSON import qualified Data.Aeson as Data.Aeson.Types.Internal import qualified Data.Aeson as Data.Aeson.Types.ToJSON import qualified Data.ByteString.Char8 import qualified Data.ByteString.Char8 as Data.ByteString.Internal import qualified Data.Foldable import qualified Data.Functor import qualified Data.Maybe import qualified Data.Scientific import qualified Data.Text import qualified Data.Text.Internal import qualified Data.Time.Calendar as Data.Time.Calendar.Days import qualified Data.Time.LocalTime as Data.Time.LocalTime.Internal.ZonedTime import qualified GHC.Base import qualified GHC.Classes import qualified GHC.Int import qualified GHC.Show import qualified GHC.Types import qualified StripeAPI.Common import StripeAPI.TypeAlias import qualified Prelude as GHC.Integer.Type import qualified Prelude as GHC.Maybe data PaymentMethodDetailsAchDebit = PaymentMethodDetailsAchDebit | account_holder_type : Type of entity that holds the account . This can be either \`individual\ ` or \`company\ ` . paymentMethodDetailsAchDebitAccountHolderType :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable PaymentMethodDetailsAchDebitAccountHolderType'NonNullable)), * Maximum length of 5000 paymentMethodDetailsAchDebitBankName :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable Data.Text.Internal.Text)), | country : Two - letter ISO code representing the country the bank account is located in . * Maximum length of 5000 paymentMethodDetailsAchDebitCountry :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable Data.Text.Internal.Text)), | fingerprint : Uniquely identifies this particular bank account . You can use this attribute to check whether two bank accounts are the same . * Maximum length of 5000 paymentMethodDetailsAchDebitFingerprint :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable Data.Text.Internal.Text)), | last4 : Last four digits of the bank account number . * Maximum length of 5000 paymentMethodDetailsAchDebitLast4 :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable Data.Text.Internal.Text)), * Maximum length of 5000 paymentMethodDetailsAchDebitRoutingNumber :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable Data.Text.Internal.Text)) } deriving ( GHC.Show.Show, GHC.Classes.Eq ) instance Data.Aeson.Types.ToJSON.ToJSON PaymentMethodDetailsAchDebit where toJSON obj = Data.Aeson.Types.Internal.object (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("account_holder_type" Data.Aeson.Types.ToJSON..=)) (paymentMethodDetailsAchDebitAccountHolderType obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("bank_name" Data.Aeson.Types.ToJSON..=)) (paymentMethodDetailsAchDebitBankName obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("country" Data.Aeson.Types.ToJSON..=)) (paymentMethodDetailsAchDebitCountry obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("fingerprint" Data.Aeson.Types.ToJSON..=)) (paymentMethodDetailsAchDebitFingerprint obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("last4" Data.Aeson.Types.ToJSON..=)) (paymentMethodDetailsAchDebitLast4 obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("routing_number" Data.Aeson.Types.ToJSON..=)) (paymentMethodDetailsAchDebitRoutingNumber obj) : GHC.Base.mempty)) toEncoding obj = Data.Aeson.Encoding.Internal.pairs (GHC.Base.mconcat (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("account_holder_type" Data.Aeson.Types.ToJSON..=)) (paymentMethodDetailsAchDebitAccountHolderType obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("bank_name" Data.Aeson.Types.ToJSON..=)) (paymentMethodDetailsAchDebitBankName obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("country" Data.Aeson.Types.ToJSON..=)) (paymentMethodDetailsAchDebitCountry obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("fingerprint" Data.Aeson.Types.ToJSON..=)) (paymentMethodDetailsAchDebitFingerprint obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("last4" Data.Aeson.Types.ToJSON..=)) (paymentMethodDetailsAchDebitLast4 obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("routing_number" Data.Aeson.Types.ToJSON..=)) (paymentMethodDetailsAchDebitRoutingNumber obj) : GHC.Base.mempty))) instance Data.Aeson.Types.FromJSON.FromJSON PaymentMethodDetailsAchDebit where parseJSON = Data.Aeson.Types.FromJSON.withObject "PaymentMethodDetailsAchDebit" (\obj -> (((((GHC.Base.pure PaymentMethodDetailsAchDebit GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "account_holder_type")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "bank_name")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "country")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "fingerprint")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "last4")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "routing_number")) mkPaymentMethodDetailsAchDebit :: PaymentMethodDetailsAchDebit mkPaymentMethodDetailsAchDebit = PaymentMethodDetailsAchDebit { paymentMethodDetailsAchDebitAccountHolderType = GHC.Maybe.Nothing, paymentMethodDetailsAchDebitBankName = GHC.Maybe.Nothing, paymentMethodDetailsAchDebitCountry = GHC.Maybe.Nothing, paymentMethodDetailsAchDebitFingerprint = GHC.Maybe.Nothing, paymentMethodDetailsAchDebitLast4 = GHC.Maybe.Nothing, paymentMethodDetailsAchDebitRoutingNumber = GHC.Maybe.Nothing } Type of entity that holds the account . This can be either \`individual\ ` or \`company\ ` . data PaymentMethodDetailsAchDebitAccountHolderType'NonNullable PaymentMethodDetailsAchDebitAccountHolderType'NonNullableOther Data.Aeson.Types.Internal.Value PaymentMethodDetailsAchDebitAccountHolderType'NonNullableTyped Data.Text.Internal.Text | Represents the JSON value @"company"@ PaymentMethodDetailsAchDebitAccountHolderType'NonNullableEnumCompany | Represents the JSON value @"individual"@ PaymentMethodDetailsAchDebitAccountHolderType'NonNullableEnumIndividual deriving (GHC.Show.Show, GHC.Classes.Eq) instance Data.Aeson.Types.ToJSON.ToJSON PaymentMethodDetailsAchDebitAccountHolderType'NonNullable where toJSON (PaymentMethodDetailsAchDebitAccountHolderType'NonNullableOther val) = val toJSON (PaymentMethodDetailsAchDebitAccountHolderType'NonNullableTyped val) = Data.Aeson.Types.ToJSON.toJSON val toJSON (PaymentMethodDetailsAchDebitAccountHolderType'NonNullableEnumCompany) = "company" toJSON (PaymentMethodDetailsAchDebitAccountHolderType'NonNullableEnumIndividual) = "individual" instance Data.Aeson.Types.FromJSON.FromJSON PaymentMethodDetailsAchDebitAccountHolderType'NonNullable where parseJSON val = GHC.Base.pure ( if | val GHC.Classes.== "company" -> PaymentMethodDetailsAchDebitAccountHolderType'NonNullableEnumCompany | val GHC.Classes.== "individual" -> PaymentMethodDetailsAchDebitAccountHolderType'NonNullableEnumIndividual | GHC.Base.otherwise -> PaymentMethodDetailsAchDebitAccountHolderType'NonNullableOther val )
8e7be9021e1d84dca04aa6201a10f633c27c80c6ea42729f59b51bd33199fb0e
input-output-hk/plutus
Type.hs
{-# LANGUAGE OverloadedStrings #-} # LANGUAGE TypeApplications # module Normalization.Type ( test_typeNormalization ) where import PlutusCore import PlutusCore.Generators.Hedgehog.AST import PlutusCore.MkPlc import PlutusCore.Normalize import Control.Monad.Morph (hoist) import Hedgehog import Hedgehog.Internal.Property (forAllT) import Test.Tasty import Test.Tasty.Hedgehog import Test.Tasty.HUnit test_appAppLamLam :: IO () test_appAppLamLam = do let integer2 = mkTyBuiltin @_ @Integer @DefaultUni () Normalized integer2' = runQuote $ do x <- freshTyName "x" y <- freshTyName "y" normalizeType $ mkIterTyApp () (TyLam () x (Type ()) (TyLam () y (Type ()) $ TyVar () y)) [integer2, integer2] integer2 @?= integer2' test_normalizeTypesInIdempotent :: Property test_normalizeTypesInIdempotent = property . hoist (pure . runQuote) $ do termNormTypes <- forAllT $ runAstGen (genTerm @DefaultFun) >>= normalizeTypesIn termNormTypes' <- normalizeTypesIn termNormTypes termNormTypes === termNormTypes' test_typeNormalization :: TestTree test_typeNormalization = testGroup "typeNormalization" [ testCase "appAppLamLam" test_appAppLamLam , testPropertyNamed "normalizeTypesInIdempotent" "normalizeTypesInIdempotent" test_normalizeTypesInIdempotent ]
null
https://raw.githubusercontent.com/input-output-hk/plutus/867fd234301d28525404de839d9a3c8220cbea63/plutus-core/plutus-core/test/Normalization/Type.hs
haskell
# LANGUAGE OverloadedStrings #
# LANGUAGE TypeApplications # module Normalization.Type ( test_typeNormalization ) where import PlutusCore import PlutusCore.Generators.Hedgehog.AST import PlutusCore.MkPlc import PlutusCore.Normalize import Control.Monad.Morph (hoist) import Hedgehog import Hedgehog.Internal.Property (forAllT) import Test.Tasty import Test.Tasty.Hedgehog import Test.Tasty.HUnit test_appAppLamLam :: IO () test_appAppLamLam = do let integer2 = mkTyBuiltin @_ @Integer @DefaultUni () Normalized integer2' = runQuote $ do x <- freshTyName "x" y <- freshTyName "y" normalizeType $ mkIterTyApp () (TyLam () x (Type ()) (TyLam () y (Type ()) $ TyVar () y)) [integer2, integer2] integer2 @?= integer2' test_normalizeTypesInIdempotent :: Property test_normalizeTypesInIdempotent = property . hoist (pure . runQuote) $ do termNormTypes <- forAllT $ runAstGen (genTerm @DefaultFun) >>= normalizeTypesIn termNormTypes' <- normalizeTypesIn termNormTypes termNormTypes === termNormTypes' test_typeNormalization :: TestTree test_typeNormalization = testGroup "typeNormalization" [ testCase "appAppLamLam" test_appAppLamLam , testPropertyNamed "normalizeTypesInIdempotent" "normalizeTypesInIdempotent" test_normalizeTypesInIdempotent ]
8e84b6775f102db3f3ea3e82f1e0ca181300ec12194d895811ef8d2acd507fa1
koji-kojiro/lem-pygments-colorthemes
murphy.lisp
(in-package :lem-user) (define-color-theme "murphy" () (foreground "#000000") (background "#ffffff") (cursor :foreground "#ffffff" :background "#000000") (syntax-warning-attribute :foreground "#ff0000" :background "#ffffff") (syntax-string-attribute :foreground nil :background "#ffffff") (syntax-comment-attribute :foreground "#666666" :background "#ffffff") (syntax-keyword-attribute :foreground "#008787" :background "#ffffff") (syntax-constant-attribute :foreground "#5fffd7" :background "#ffffff") (syntax-function-name-attribute :foreground "#5fffd7" :background "#ffffff") (syntax-variable-attribute :foreground "#005f5f" :background "#ffffff") (syntax-type-attribute :foreground "#5f5fff" :background "#ffffff") (syntax-builtin-attribute :foreground "#008000" :background "#ffffff"))
null
https://raw.githubusercontent.com/koji-kojiro/lem-pygments-colorthemes/f7de93ca7a68be7fb99ec48cc571e132292a6712/themes/murphy.lisp
lisp
(in-package :lem-user) (define-color-theme "murphy" () (foreground "#000000") (background "#ffffff") (cursor :foreground "#ffffff" :background "#000000") (syntax-warning-attribute :foreground "#ff0000" :background "#ffffff") (syntax-string-attribute :foreground nil :background "#ffffff") (syntax-comment-attribute :foreground "#666666" :background "#ffffff") (syntax-keyword-attribute :foreground "#008787" :background "#ffffff") (syntax-constant-attribute :foreground "#5fffd7" :background "#ffffff") (syntax-function-name-attribute :foreground "#5fffd7" :background "#ffffff") (syntax-variable-attribute :foreground "#005f5f" :background "#ffffff") (syntax-type-attribute :foreground "#5f5fff" :background "#ffffff") (syntax-builtin-attribute :foreground "#008000" :background "#ffffff"))
f842d56abdb1c2c0609689e7bb5af2c2c44dfc63ec71c4c6bdad75902c1ce847
tomjridge/kv-lite
trace.ml
(** Some utility code for traces *) open Sexplib.Std type op = string * [ `Insert of string | `Delete | `Find of string option ][@@deriving sexp] type ops = op list[@@deriving sexp] let write fn ops = let oc = Stdlib.open_out_bin fn in Sexplib.Sexp.output_hum oc (sexp_of_ops ops); Stdlib.close_out_noerr oc let read fn = let ic = Stdlib.open_in_bin fn in Sexplib.Sexp.input_sexp ic |> ops_of_sexp
null
https://raw.githubusercontent.com/tomjridge/kv-lite/4f5377a37f3ff55504613912f38af661e4df4d4d/src/trace.ml
ocaml
* Some utility code for traces
open Sexplib.Std type op = string * [ `Insert of string | `Delete | `Find of string option ][@@deriving sexp] type ops = op list[@@deriving sexp] let write fn ops = let oc = Stdlib.open_out_bin fn in Sexplib.Sexp.output_hum oc (sexp_of_ops ops); Stdlib.close_out_noerr oc let read fn = let ic = Stdlib.open_in_bin fn in Sexplib.Sexp.input_sexp ic |> ops_of_sexp
70445631ce54c8b2ac456c5cfaac172078da59769211a9df0c08cc43de5f19fc
masateruk/micro-caml
env.ml
type t = { venv : Type.t M.t; tenv : Type.t M.t; tycons : Type.tycon M.t } let predeftypes = [ ("bool", Type.TyFun([], Type.App(Type.Bool, []))); ("int", Type.TyFun([], Type.App(Type.Int, []))); ("list", Type.TyFun(["a"], Type.App(Type.Variant("list", [("Nil", []); ("Cons", [Type.Var("a"); Type.App(Type.NameTycon("list", ref None), [Type.Var("a")])])]), []))); ] let predeffuns = [ ( " print_int " , ( Type . Poly ( [ ] , ( Type . App(Type . Arrow , [ Type . App(Type . Int , [ ] ) ; Type . App(Type . Unit , [ ] ) ] ) ) ) ) ) ; ( " assert " , ( Type . Poly ( [ ] , ( Type . App(Type . Arrow , [ Type . App(Type . , [ ] ) ; Type . App(Type . Unit , [ ] ) ] ) ) ) ) ) ; ("print_int", (Type.Poly([], (Type.App(Type.Arrow, [Type.App(Type.Int, []); Type.App(Type.Unit, [])]))))); ("assert", (Type.Poly([], (Type.App(Type.Arrow, [Type.App(Type.Bool, []); Type.App(Type.Unit, [])]))))); *) ] let empty = ref { venv = M.empty; tenv = M.empty; tycons = M.empty } let () = empty := List.fold_left (fun { venv = venv; tenv = tenv; tycons = tycons } (x, t) -> { venv = M.add_list (Type.vars t) venv; tenv = M.add_list (Type.types t) tenv; tycons = M.add x t tycons }) !empty predeftypes; empty := { !empty with venv = M.add_list predeffuns !empty.venv } let extenv = ref { venv = M.empty; tenv = M.empty; tycons = M.empty } let () = extenv := { !extenv with venv = M.add_list [ ("print_int", (Type.Poly([], (Type.App(Type.Arrow, [Type.App(Type.Int, []); Type.App(Type.Unit, [])]))))); ("assert", (Type.Poly([], (Type.App(Type.Arrow, [Type.App(Type.Bool, []); Type.App(Type.Unit, [])]))))); ] M.empty } let add_var env x t = { env with venv = M.add x t env.venv } let exists_tycon { tycons = tycons } x = M.mem x tycons let find_tycon { tycons = tycons } x = M.find x tycons
null
https://raw.githubusercontent.com/masateruk/micro-caml/0c0bd066b87cf54ce33709355c422993a85a86a1/env.ml
ocaml
type t = { venv : Type.t M.t; tenv : Type.t M.t; tycons : Type.tycon M.t } let predeftypes = [ ("bool", Type.TyFun([], Type.App(Type.Bool, []))); ("int", Type.TyFun([], Type.App(Type.Int, []))); ("list", Type.TyFun(["a"], Type.App(Type.Variant("list", [("Nil", []); ("Cons", [Type.Var("a"); Type.App(Type.NameTycon("list", ref None), [Type.Var("a")])])]), []))); ] let predeffuns = [ ( " print_int " , ( Type . Poly ( [ ] , ( Type . App(Type . Arrow , [ Type . App(Type . Int , [ ] ) ; Type . App(Type . Unit , [ ] ) ] ) ) ) ) ) ; ( " assert " , ( Type . Poly ( [ ] , ( Type . App(Type . Arrow , [ Type . App(Type . , [ ] ) ; Type . App(Type . Unit , [ ] ) ] ) ) ) ) ) ; ("print_int", (Type.Poly([], (Type.App(Type.Arrow, [Type.App(Type.Int, []); Type.App(Type.Unit, [])]))))); ("assert", (Type.Poly([], (Type.App(Type.Arrow, [Type.App(Type.Bool, []); Type.App(Type.Unit, [])]))))); *) ] let empty = ref { venv = M.empty; tenv = M.empty; tycons = M.empty } let () = empty := List.fold_left (fun { venv = venv; tenv = tenv; tycons = tycons } (x, t) -> { venv = M.add_list (Type.vars t) venv; tenv = M.add_list (Type.types t) tenv; tycons = M.add x t tycons }) !empty predeftypes; empty := { !empty with venv = M.add_list predeffuns !empty.venv } let extenv = ref { venv = M.empty; tenv = M.empty; tycons = M.empty } let () = extenv := { !extenv with venv = M.add_list [ ("print_int", (Type.Poly([], (Type.App(Type.Arrow, [Type.App(Type.Int, []); Type.App(Type.Unit, [])]))))); ("assert", (Type.Poly([], (Type.App(Type.Arrow, [Type.App(Type.Bool, []); Type.App(Type.Unit, [])]))))); ] M.empty } let add_var env x t = { env with venv = M.add x t env.venv } let exists_tycon { tycons = tycons } x = M.mem x tycons let find_tycon { tycons = tycons } x = M.find x tycons
ed7e6e7691b778ba7a67e33e4c128bbee7e3a6e0f2faba032fdc1afdbc398948
onaio/hatti
views.cljs
(ns hatti.views (:require [om.core :as om])) ;; GENERIC DISPATCHER (def view-type-dispatcher (fn [_ owner & args] (om/get-shared owner :view-type))) (def view-type-fn-dispatcher (fn [owner] (om/get-shared owner :view-type))) TABBED DATAVIEW (defmulti tabbed-dataview view-type-dispatcher) (defmulti dataview-infobar view-type-dispatcher) (defmulti dataview-actions view-type-dispatcher) ;; MAP (defmulti map-page view-type-dispatcher) (defmulti map-geofield-chooser view-type-dispatcher) (defmulti map-and-markers view-type-dispatcher) (defmulti map-record-legend view-type-dispatcher) (defmulti map-viewby-legend view-type-dispatcher) (defmulti map-viewby-menu view-type-dispatcher) (defmulti map-viewby-answer-legend view-type-dispatcher) (defmulti map-viewby-answer-close view-type-dispatcher) (defmulti viewby-answer-list view-type-dispatcher) (defmulti viewby-answer-list-filter view-type-dispatcher) ;; TABLE (defmulti table-page view-type-dispatcher) (defmulti table-header view-type-dispatcher) (defmulti table-search view-type-dispatcher) (defmulti label-changer view-type-dispatcher) (defmulti action-buttons view-type-fn-dispatcher) (defmulti actions-column view-type-fn-dispatcher) ;; MAP TABLE (defmulti report-view-page view-type-dispatcher) CHART (defmulti chart-page view-type-dispatcher) (defmulti chart-chooser view-type-dispatcher) (defmulti single-chart view-type-dispatcher) (defmulti list-of-charts view-type-dispatcher) INDIVIDUAL RECORDS (defmulti submission-view view-type-dispatcher) (defmulti print-xls-report-btn view-type-dispatcher) (defmulti repeat-view view-type-dispatcher) (defmulti edit-delete view-type-dispatcher) ;; DETAILS PAGE (defmulti settings-page view-type-dispatcher) (defmulti form-details view-type-dispatcher) OVERVIEW PAGE (defmulti overview-page view-type-dispatcher) ;; PHOTOS PAGE (defmulti photos-page view-type-dispatcher) ;; SAVED CHARTS PAGE - temporary (defmulti saved-charts-page view-type-dispatcher) ;; USER GUIDE PAGE (defmulti user-guide-page view-type-dispatcher)
null
https://raw.githubusercontent.com/onaio/hatti/7dc23c1c60b9fc46e1ff5b023eb6c794ebd04773/src/hatti/views.cljs
clojure
GENERIC DISPATCHER MAP TABLE MAP TABLE DETAILS PAGE PHOTOS PAGE SAVED CHARTS PAGE - temporary USER GUIDE PAGE
(ns hatti.views (:require [om.core :as om])) (def view-type-dispatcher (fn [_ owner & args] (om/get-shared owner :view-type))) (def view-type-fn-dispatcher (fn [owner] (om/get-shared owner :view-type))) TABBED DATAVIEW (defmulti tabbed-dataview view-type-dispatcher) (defmulti dataview-infobar view-type-dispatcher) (defmulti dataview-actions view-type-dispatcher) (defmulti map-page view-type-dispatcher) (defmulti map-geofield-chooser view-type-dispatcher) (defmulti map-and-markers view-type-dispatcher) (defmulti map-record-legend view-type-dispatcher) (defmulti map-viewby-legend view-type-dispatcher) (defmulti map-viewby-menu view-type-dispatcher) (defmulti map-viewby-answer-legend view-type-dispatcher) (defmulti map-viewby-answer-close view-type-dispatcher) (defmulti viewby-answer-list view-type-dispatcher) (defmulti viewby-answer-list-filter view-type-dispatcher) (defmulti table-page view-type-dispatcher) (defmulti table-header view-type-dispatcher) (defmulti table-search view-type-dispatcher) (defmulti label-changer view-type-dispatcher) (defmulti action-buttons view-type-fn-dispatcher) (defmulti actions-column view-type-fn-dispatcher) (defmulti report-view-page view-type-dispatcher) CHART (defmulti chart-page view-type-dispatcher) (defmulti chart-chooser view-type-dispatcher) (defmulti single-chart view-type-dispatcher) (defmulti list-of-charts view-type-dispatcher) INDIVIDUAL RECORDS (defmulti submission-view view-type-dispatcher) (defmulti print-xls-report-btn view-type-dispatcher) (defmulti repeat-view view-type-dispatcher) (defmulti edit-delete view-type-dispatcher) (defmulti settings-page view-type-dispatcher) (defmulti form-details view-type-dispatcher) OVERVIEW PAGE (defmulti overview-page view-type-dispatcher) (defmulti photos-page view-type-dispatcher) (defmulti saved-charts-page view-type-dispatcher) (defmulti user-guide-page view-type-dispatcher)
e0f9dc794ad4d28dd73103f9a1060da4e1d30f36c69d37c11d1e29b8dc36b48a
rtoy/ansi-cl-tests
rassoc-if.lsp
;-*- Mode: Lisp -*- Author : Created : Sun Apr 20 07:34:59 2003 ;;;; Contains: Tests of RASSOC-IF (in-package :cl-test) (compile-and-load "cons-aux.lsp") (deftest rassoc-if.1 (let* ((x (rev-assoc-list '((1 . a) (3 . b) (6 . c) (7 . d)))) (xcopy (make-scaffold-copy x)) (result (rassoc-if #'evenp x))) (and (check-scaffold-copy x xcopy) (eqt result (third x)) result)) (c . 6)) (deftest rassoc-if.2 (let* ((x (rev-assoc-list '((1 . a) (3 . b) (6 . c) (7 . d)))) (xcopy (make-scaffold-copy x)) (result (rassoc-if #'oddp x :key #'1+))) (and (check-scaffold-copy x xcopy) (eqt result (third x)) result)) (c . 6)) (deftest rassoc-if.3 (let* ((x (rev-assoc-list '((1 . a) nil (3 . b) (6 . c) (7 . d)))) (xcopy (make-scaffold-copy x)) (result (rassoc-if #'evenp x))) (and (check-scaffold-copy x xcopy) (eqt result (fourth x)) result)) (c . 6)) (deftest rassoc-if.4 (rassoc-if #'null (rev-assoc-list '((a . b) nil (c . d) (nil . e) (f . g)))) (e)) ;;; Order of argument evaluation (deftest rassoc-if.order.1 (let ((i 0) x y) (values (rassoc-if (progn (setf x (incf i)) #'null) (progn (setf y (incf i)) '((1 . a) (2 . b) (17) (4 . d)))) i x y)) (17) 2 1 2) (deftest rassoc-if.order.2 (let ((i 0) x y z) (values (rassoc-if (progn (setf x (incf i)) #'null) (progn (setf y (incf i)) '((1 . a) (2 . b) (17) (4 . d))) :key (progn (setf z (incf i)) #'null)) i x y z)) (1 . a) 3 1 2 3) ;;; Keyword tests (deftest rassoc-if.allow-other-keys.1 (rassoc-if #'null '((1 . a) (2) (3 . c)) :bad t :allow-other-keys t) (2)) (deftest rassoc-if.allow-other-keys.2 (rassoc-if #'null '((1 . a) (2) (3 . c)) :allow-other-keys t :bad t) (2)) (deftest rassoc-if.allow-other-keys.3 (rassoc-if #'identity '((1 . a) (2) (3 . c)) :allow-other-keys t :bad t :key 'not) (2)) (deftest rassoc-if.allow-other-keys.4 (rassoc-if #'null '((1 . a) (2) (3 . c)) :allow-other-keys t) (2)) (deftest rassoc-if.allow-other-keys.5 (rassoc-if #'null '((1 . a) (2) (3 . c)) :allow-other-keys nil) (2)) (deftest rassoc-if.keywords.6 (rassoc-if #'identity '((1 . a) (2) (3 . c)) :key #'not :key #'identity) (2)) ;;; Error tests (deftest rassoc-if.error.1 (signals-error (rassoc-if) program-error) t) (deftest rassoc-if.error.2 (signals-error (rassoc-if #'null) program-error) t) (deftest rassoc-if.error.3 (signals-error (rassoc-if #'null nil :bad t) program-error) t) (deftest rassoc-if.error.4 (signals-error (rassoc-if #'null nil :key) program-error) t) (deftest rassoc-if.error.5 (signals-error (rassoc-if #'null nil 1 1) program-error) t) (deftest rassoc-if.error.6 (signals-error (rassoc-if #'null nil :bad t :allow-other-keys nil) program-error) t) (deftest rassoc-if.error.7 (signals-error (rassoc-if #'cons '((a . b)(c . d))) program-error) t) (deftest rassoc-if.error.8 (signals-error (rassoc-if #'car '((a . b)(c . d))) type-error) t) (deftest rassoc-if.error.9 (signals-error (rassoc-if #'identity '((a . b)(c . d)) :key #'cons) program-error) t) (deftest rassoc-if.error.10 (signals-error (rassoc-if #'identity '((a . b)(c . d)) :key #'car) type-error) t) (deftest rassoc-if.error.11 (signals-error (rassoc-if #'not '((a . b) . c)) type-error) t) (deftest rassoc-if.error.12 (check-type-error #'(lambda (x) (rassoc-if #'identity x)) #'listp) nil)
null
https://raw.githubusercontent.com/rtoy/ansi-cl-tests/9708f3977220c46def29f43bb237e97d62033c1d/rassoc-if.lsp
lisp
-*- Mode: Lisp -*- Contains: Tests of RASSOC-IF Order of argument evaluation Keyword tests Error tests
Author : Created : Sun Apr 20 07:34:59 2003 (in-package :cl-test) (compile-and-load "cons-aux.lsp") (deftest rassoc-if.1 (let* ((x (rev-assoc-list '((1 . a) (3 . b) (6 . c) (7 . d)))) (xcopy (make-scaffold-copy x)) (result (rassoc-if #'evenp x))) (and (check-scaffold-copy x xcopy) (eqt result (third x)) result)) (c . 6)) (deftest rassoc-if.2 (let* ((x (rev-assoc-list '((1 . a) (3 . b) (6 . c) (7 . d)))) (xcopy (make-scaffold-copy x)) (result (rassoc-if #'oddp x :key #'1+))) (and (check-scaffold-copy x xcopy) (eqt result (third x)) result)) (c . 6)) (deftest rassoc-if.3 (let* ((x (rev-assoc-list '((1 . a) nil (3 . b) (6 . c) (7 . d)))) (xcopy (make-scaffold-copy x)) (result (rassoc-if #'evenp x))) (and (check-scaffold-copy x xcopy) (eqt result (fourth x)) result)) (c . 6)) (deftest rassoc-if.4 (rassoc-if #'null (rev-assoc-list '((a . b) nil (c . d) (nil . e) (f . g)))) (e)) (deftest rassoc-if.order.1 (let ((i 0) x y) (values (rassoc-if (progn (setf x (incf i)) #'null) (progn (setf y (incf i)) '((1 . a) (2 . b) (17) (4 . d)))) i x y)) (17) 2 1 2) (deftest rassoc-if.order.2 (let ((i 0) x y z) (values (rassoc-if (progn (setf x (incf i)) #'null) (progn (setf y (incf i)) '((1 . a) (2 . b) (17) (4 . d))) :key (progn (setf z (incf i)) #'null)) i x y z)) (1 . a) 3 1 2 3) (deftest rassoc-if.allow-other-keys.1 (rassoc-if #'null '((1 . a) (2) (3 . c)) :bad t :allow-other-keys t) (2)) (deftest rassoc-if.allow-other-keys.2 (rassoc-if #'null '((1 . a) (2) (3 . c)) :allow-other-keys t :bad t) (2)) (deftest rassoc-if.allow-other-keys.3 (rassoc-if #'identity '((1 . a) (2) (3 . c)) :allow-other-keys t :bad t :key 'not) (2)) (deftest rassoc-if.allow-other-keys.4 (rassoc-if #'null '((1 . a) (2) (3 . c)) :allow-other-keys t) (2)) (deftest rassoc-if.allow-other-keys.5 (rassoc-if #'null '((1 . a) (2) (3 . c)) :allow-other-keys nil) (2)) (deftest rassoc-if.keywords.6 (rassoc-if #'identity '((1 . a) (2) (3 . c)) :key #'not :key #'identity) (2)) (deftest rassoc-if.error.1 (signals-error (rassoc-if) program-error) t) (deftest rassoc-if.error.2 (signals-error (rassoc-if #'null) program-error) t) (deftest rassoc-if.error.3 (signals-error (rassoc-if #'null nil :bad t) program-error) t) (deftest rassoc-if.error.4 (signals-error (rassoc-if #'null nil :key) program-error) t) (deftest rassoc-if.error.5 (signals-error (rassoc-if #'null nil 1 1) program-error) t) (deftest rassoc-if.error.6 (signals-error (rassoc-if #'null nil :bad t :allow-other-keys nil) program-error) t) (deftest rassoc-if.error.7 (signals-error (rassoc-if #'cons '((a . b)(c . d))) program-error) t) (deftest rassoc-if.error.8 (signals-error (rassoc-if #'car '((a . b)(c . d))) type-error) t) (deftest rassoc-if.error.9 (signals-error (rassoc-if #'identity '((a . b)(c . d)) :key #'cons) program-error) t) (deftest rassoc-if.error.10 (signals-error (rassoc-if #'identity '((a . b)(c . d)) :key #'car) type-error) t) (deftest rassoc-if.error.11 (signals-error (rassoc-if #'not '((a . b) . c)) type-error) t) (deftest rassoc-if.error.12 (check-type-error #'(lambda (x) (rassoc-if #'identity x)) #'listp) nil)
936ade32152b7813c58a7a9f2c3842d603ee82d0eaabb92c8ab13dd3a6b1ef98
modular-macros/ocaml-macros
camlinternalAST.mli
type constant = Pconst_integer of string * char option 3 3l 3L 3n Suffixes [ g - z][G - Z ] are accepted by the parser . Suffixes except ' l ' , ' L ' and ' n ' are rejected by the typechecker Suffixes [g-z][G-Z] are accepted by the parser. Suffixes except 'l', 'L' and 'n' are rejected by the typechecker *) | Pconst_char of char (* 'c' *) | Pconst_string of string * string option " constant " { } {delim|other constant|delim} *) | Pconst_float of string * char option (* 3.4 2e5 1.4e-4 Suffixes [g-z][G-Z] are accepted by the parser. Suffixes are rejected by the typechecker. *) type rec_flag = Nonrecursive | Recursive type direction_flag = Upto | Downto type override_flag = Override | Fresh type closed_flag = Closed | Open type label = string type arg_label = Nolabel | Labelled of string (* label:T -> ... *) | Optional of string (* ?label:T -> ... *) type location = { loc_start: Lexing.position; loc_end: Lexing.position; loc_ghost: bool; } type 'a loc = { txt : 'a; loc : location; } type lid = Lident of string | Ldot of lid * string | Lapply of lid * lid | Lglobal of string | Lfrommacro of lid * string * int (* 'a = attribute 'b = core_type 'c = module_expr 'd = class_structure *) type ('a, 'b, 'c, 'd) pattern = { ppat_desc: ('a, 'b, 'c, 'd) pattern_desc; ppat_loc: location; ppat_attributes: 'a list; } and ('a, 'b, 'c, 'd) pattern_desc = | Ppat_any | Ppat_var of string loc | Ppat_alias of ('a, 'b, 'c, 'd) pattern * string loc | Ppat_constant of constant | Ppat_interval of constant * constant | Ppat_tuple of ('a, 'b, 'c, 'd) pattern list | Ppat_construct of lid loc * ('a, 'b, 'c, 'd) pattern option | Ppat_variant of label * ('a, 'b, 'c, 'd) pattern option | Ppat_record of (lid loc * ('a, 'b, 'c, 'd) pattern) list * closed_flag | Ppat_array of ('a, 'b, 'c, 'd) pattern list | Ppat_or of ('a, 'b, 'c, 'd) pattern * ('a, 'b, 'c, 'd) pattern | Ppat_constraint of ('a, 'b, 'c, 'd) pattern * 'b | Ppat_type of lid loc | Ppat_lazy of ('a, 'b, 'c, 'd) pattern | Ppat_unpack of string loc | Ppat_exception of ('a, 'b, 'c, 'd) pattern | Ppat_extension of 'a | Ppat_open of lid loc * ('a, 'b, 'c, 'd) pattern and ('a, 'b, 'c, 'd) expression = { pexp_desc: ('a, 'b, 'c, 'd) expression_desc; pexp_loc: location; pexp_attributes: 'a list; } and ('a, 'b, 'c, 'd) expression_desc = | Pexp_ident of lid loc | Pexp_constant of constant | Pexp_let of rec_flag * ('a, 'b, 'c, 'd) value_binding list * ('a, 'b, 'c, 'd) expression | Pexp_function of ('a, 'b, 'c, 'd) case list | Pexp_fun of arg_label * ('a, 'b, 'c, 'd) expression option * ('a, 'b, 'c, 'd) pattern * ('a, 'b, 'c, 'd) expression | Pexp_apply of ('a, 'b, 'c, 'd) expression * (arg_label * ('a, 'b, 'c, 'd) expression) list | Pexp_match of ('a, 'b, 'c, 'd) expression * ('a, 'b, 'c, 'd) case list | Pexp_try of ('a, 'b, 'c, 'd) expression * ('a, 'b, 'c, 'd) case list | Pexp_tuple of ('a, 'b, 'c, 'd) expression list | Pexp_construct of lid loc * ('a, 'b, 'c, 'd) expression option | Pexp_variant of label * ('a, 'b, 'c, 'd) expression option | Pexp_record of (lid loc * ('a, 'b, 'c, 'd) expression) list * ('a, 'b, 'c, 'd) expression option | Pexp_field of ('a, 'b, 'c, 'd) expression * lid loc | Pexp_setfield of ('a, 'b, 'c, 'd) expression * lid loc * ('a, 'b, 'c, 'd) expression | Pexp_array of ('a, 'b, 'c, 'd) expression list | Pexp_ifthenelse of ('a, 'b, 'c, 'd) expression * ('a, 'b, 'c, 'd) expression * ('a, 'b, 'c, 'd) expression option | Pexp_sequence of ('a, 'b, 'c, 'd) expression * ('a, 'b, 'c, 'd) expression | Pexp_while of ('a, 'b, 'c, 'd) expression * ('a, 'b, 'c, 'd) expression | Pexp_for of ('a, 'b, 'c, 'd) pattern * ('a, 'b, 'c, 'd) expression * ('a, 'b, 'c, 'd) expression * direction_flag * ('a, 'b, 'c, 'd) expression | Pexp_constraint of ('a, 'b, 'c, 'd) expression * 'b | Pexp_coerce of ('a, 'b, 'c, 'd) expression * 'b option * 'b | Pexp_send of ('a, 'b, 'c, 'd) expression * string | Pexp_new of lid loc | Pexp_setinstvar of string loc * ('a, 'b, 'c, 'd) expression | Pexp_override of (string loc * ('a, 'b, 'c, 'd) expression) list | Pexp_letmodule of string loc * 'c * ('a, 'b, 'c, 'd) expression | Pexp_letexception of extension_constructor * ('a, 'b, 'c, 'd) expression | Pexp_assert of ('a, 'b, 'c, 'd) expression | Pexp_lazy of ('a, 'b, 'c, 'd) expression | Pexp_poly of ('a, 'b, 'c, 'd) expression * 'b option | Pexp_object of 'd | Pexp_newtype of string * ('a, 'b, 'c, 'd) expression | Pexp_pack of 'c | Pexp_open of override_flag * lid loc * ('a, 'b, 'c, 'd) expression | Pexp_quote of ('a, 'b, 'c, 'd) expression | Pexp_escape of ('a, 'b, 'c, 'd) expression | Pexp_extension of 'a | Pexp_unreachable and ('a, 'b, 'c, 'd) case = { pc_lhs: ('a, 'b, 'c, 'd) pattern; pc_guard: ('a, 'b, 'c, 'd) expression option; pc_rhs: ('a, 'b, 'c, 'd) expression; } and ('a, 'b, 'c, 'd) value_binding = { pvb_pat: ('a, 'b, 'c, 'd) pattern; pvb_expr: ('a, 'b, 'c, 'd) expression; pvb_attributes: 'a list; pvb_loc: location; }
null
https://raw.githubusercontent.com/modular-macros/ocaml-macros/05372c7248b5a7b1aa507b3c581f710380f17fcd/stdlib/camlinternalAST.mli
ocaml
'c' 3.4 2e5 1.4e-4 Suffixes [g-z][G-Z] are accepted by the parser. Suffixes are rejected by the typechecker. label:T -> ... ?label:T -> ... 'a = attribute 'b = core_type 'c = module_expr 'd = class_structure
type constant = Pconst_integer of string * char option 3 3l 3L 3n Suffixes [ g - z][G - Z ] are accepted by the parser . Suffixes except ' l ' , ' L ' and ' n ' are rejected by the typechecker Suffixes [g-z][G-Z] are accepted by the parser. Suffixes except 'l', 'L' and 'n' are rejected by the typechecker *) | Pconst_char of char | Pconst_string of string * string option " constant " { } {delim|other constant|delim} *) | Pconst_float of string * char option type rec_flag = Nonrecursive | Recursive type direction_flag = Upto | Downto type override_flag = Override | Fresh type closed_flag = Closed | Open type label = string type arg_label = Nolabel type location = { loc_start: Lexing.position; loc_end: Lexing.position; loc_ghost: bool; } type 'a loc = { txt : 'a; loc : location; } type lid = Lident of string | Ldot of lid * string | Lapply of lid * lid | Lglobal of string | Lfrommacro of lid * string * int type ('a, 'b, 'c, 'd) pattern = { ppat_desc: ('a, 'b, 'c, 'd) pattern_desc; ppat_loc: location; ppat_attributes: 'a list; } and ('a, 'b, 'c, 'd) pattern_desc = | Ppat_any | Ppat_var of string loc | Ppat_alias of ('a, 'b, 'c, 'd) pattern * string loc | Ppat_constant of constant | Ppat_interval of constant * constant | Ppat_tuple of ('a, 'b, 'c, 'd) pattern list | Ppat_construct of lid loc * ('a, 'b, 'c, 'd) pattern option | Ppat_variant of label * ('a, 'b, 'c, 'd) pattern option | Ppat_record of (lid loc * ('a, 'b, 'c, 'd) pattern) list * closed_flag | Ppat_array of ('a, 'b, 'c, 'd) pattern list | Ppat_or of ('a, 'b, 'c, 'd) pattern * ('a, 'b, 'c, 'd) pattern | Ppat_constraint of ('a, 'b, 'c, 'd) pattern * 'b | Ppat_type of lid loc | Ppat_lazy of ('a, 'b, 'c, 'd) pattern | Ppat_unpack of string loc | Ppat_exception of ('a, 'b, 'c, 'd) pattern | Ppat_extension of 'a | Ppat_open of lid loc * ('a, 'b, 'c, 'd) pattern and ('a, 'b, 'c, 'd) expression = { pexp_desc: ('a, 'b, 'c, 'd) expression_desc; pexp_loc: location; pexp_attributes: 'a list; } and ('a, 'b, 'c, 'd) expression_desc = | Pexp_ident of lid loc | Pexp_constant of constant | Pexp_let of rec_flag * ('a, 'b, 'c, 'd) value_binding list * ('a, 'b, 'c, 'd) expression | Pexp_function of ('a, 'b, 'c, 'd) case list | Pexp_fun of arg_label * ('a, 'b, 'c, 'd) expression option * ('a, 'b, 'c, 'd) pattern * ('a, 'b, 'c, 'd) expression | Pexp_apply of ('a, 'b, 'c, 'd) expression * (arg_label * ('a, 'b, 'c, 'd) expression) list | Pexp_match of ('a, 'b, 'c, 'd) expression * ('a, 'b, 'c, 'd) case list | Pexp_try of ('a, 'b, 'c, 'd) expression * ('a, 'b, 'c, 'd) case list | Pexp_tuple of ('a, 'b, 'c, 'd) expression list | Pexp_construct of lid loc * ('a, 'b, 'c, 'd) expression option | Pexp_variant of label * ('a, 'b, 'c, 'd) expression option | Pexp_record of (lid loc * ('a, 'b, 'c, 'd) expression) list * ('a, 'b, 'c, 'd) expression option | Pexp_field of ('a, 'b, 'c, 'd) expression * lid loc | Pexp_setfield of ('a, 'b, 'c, 'd) expression * lid loc * ('a, 'b, 'c, 'd) expression | Pexp_array of ('a, 'b, 'c, 'd) expression list | Pexp_ifthenelse of ('a, 'b, 'c, 'd) expression * ('a, 'b, 'c, 'd) expression * ('a, 'b, 'c, 'd) expression option | Pexp_sequence of ('a, 'b, 'c, 'd) expression * ('a, 'b, 'c, 'd) expression | Pexp_while of ('a, 'b, 'c, 'd) expression * ('a, 'b, 'c, 'd) expression | Pexp_for of ('a, 'b, 'c, 'd) pattern * ('a, 'b, 'c, 'd) expression * ('a, 'b, 'c, 'd) expression * direction_flag * ('a, 'b, 'c, 'd) expression | Pexp_constraint of ('a, 'b, 'c, 'd) expression * 'b | Pexp_coerce of ('a, 'b, 'c, 'd) expression * 'b option * 'b | Pexp_send of ('a, 'b, 'c, 'd) expression * string | Pexp_new of lid loc | Pexp_setinstvar of string loc * ('a, 'b, 'c, 'd) expression | Pexp_override of (string loc * ('a, 'b, 'c, 'd) expression) list | Pexp_letmodule of string loc * 'c * ('a, 'b, 'c, 'd) expression | Pexp_letexception of extension_constructor * ('a, 'b, 'c, 'd) expression | Pexp_assert of ('a, 'b, 'c, 'd) expression | Pexp_lazy of ('a, 'b, 'c, 'd) expression | Pexp_poly of ('a, 'b, 'c, 'd) expression * 'b option | Pexp_object of 'd | Pexp_newtype of string * ('a, 'b, 'c, 'd) expression | Pexp_pack of 'c | Pexp_open of override_flag * lid loc * ('a, 'b, 'c, 'd) expression | Pexp_quote of ('a, 'b, 'c, 'd) expression | Pexp_escape of ('a, 'b, 'c, 'd) expression | Pexp_extension of 'a | Pexp_unreachable and ('a, 'b, 'c, 'd) case = { pc_lhs: ('a, 'b, 'c, 'd) pattern; pc_guard: ('a, 'b, 'c, 'd) expression option; pc_rhs: ('a, 'b, 'c, 'd) expression; } and ('a, 'b, 'c, 'd) value_binding = { pvb_pat: ('a, 'b, 'c, 'd) pattern; pvb_expr: ('a, 'b, 'c, 'd) expression; pvb_attributes: 'a list; pvb_loc: location; }