_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
dafe7853fb1ab7aca6e3f097288defb5c89b55066f9517266a0f1d9133e42717
goldfirere/thesis
cpdt8.hs
# LANGUAGE TemplateHaskell , PolyKinds , DataKinds , RankNTypes , TypeFamilies , GADTs , NoImplicitPrelude , TypeOperators , LambdaCase , EmptyCase , TypeHoles # GADTs, NoImplicitPrelude, TypeOperators, LambdaCase, EmptyCase, TypeHoles #-} import Prelude ((++), Either(..), undefined, ($)) import Data.Singletons $(singletons [d| data Char = CA | CB | CC | CD | CE data Nat = Zero | Succ Nat length :: [a] -> Nat length [] = Zero length (_:t) = Succ (length t) truncate :: Nat -> [Char] -> [Char] truncate Zero s = [] truncate (Succ n) (h : t) = h : (truncate n t) truncate (Succ _) [] = [] substring :: Nat -> Nat -> [Char] -> [Char] substring Zero n s = truncate n s substring (Succ start) n (h : t) = substring start n t substring (Succ _) n [] = [] (-) :: Nat -> Nat -> Nat Zero - a = Zero (Succ n) - (Succ m) = n - m (Succ n) - Zero = Succ n |]) data a :~: b where Refl :: a :~: a data False absurd :: False -> a absurd = \case {} type Refuted a = a -> False type Decidable a = Either a (Refuted a) data Star :: ([Char] -> *) -> [Char] -> * where Empty :: Star p '[] Iter :: p s1 -> Star p s2 -> Star p (s1 :++ s2) data Existential :: (k -> *) -> * where Exists :: Sing x -> p x -> Existential p data ConcatCond p1 p2 s where ConcatCondC :: Sing s1 -> Sing s2 -> (s :~: (s1 :++ s2)) -> p1 s1 -> p2 s2 -> ConcatCond p1 p2 s data OrCond p1 p2 s where OrCondC :: Either (p1 s) (p2 s) -> OrCond p1 p2 s data Regexp :: ([Char] -> *) -> * where RChar :: SChar ch -> Regexp ((:~:) '[ch]) RConcat :: Regexp p1 -> Regexp p2 -> Regexp (ConcatCond p1 p2) ROr :: Regexp p1 -> Regexp p2 -> Regexp (OrCond p1 p2) RStar :: Regexp p -> Regexp (Star p) data a <= b where LEZero :: Zero <= b LESucc :: a <= b -> (Succ a) <= (Succ b) le_succ :: Sing a -> a <= Succ (Succ a) le_succ SZero = LEZero le_succ (SSucc n') = LESucc $ le_succ n' data Split'L n s p1 p2 where Split'LC :: Sing s1 -> Sing s2 -> Length s1 <= n -> (s1 :++ s2) :~: s -> p1 s1 -> p2 s2 -> Split'L n s p1 p2 data Split'R n s p1 p2 where Split'RC :: (forall s1 s2. Sing s1 -> Sing s2 -> Length s1 <= n -> (s1 :++ s2) :~: s -> Either (Refuted (p1 s1)) (Refuted (p2 s2))) -> Split'R n s p1 p2 (&&) :: Either a b -> Either c d -> Either (a, c) (Either b d) (Left a) && (Left c) = Left (a, c) (Left _) && (Right d) = Right (Right d) (Right b) && (Left _) = Right (Left b) (Right b) && (Right _) = Right (Left b) (||) :: Either a b -> Either c d -> (a -> e) -> (b -> c -> e) -> (b -> d -> f) -> Either e f (Left x) || _ = \first _ _ -> Left $ first x (Right x) || (Left y) = \_ second _ -> Left $ second x y (Right x) || (Right y) = \_ _ third -> Right $ third x y split' :: (forall s. Sing s -> Decidable (p1 s)) -> (forall s. Sing s -> Decidable (p2 s)) -> Sing (s :: [Char]) -> SNat n -> n <= Length s -> Either (Split'L n s p1 p2) (Split'R n s p1 p2) split' p1_dec p2_dec s n = case n of { SZero -> \_ -> case p1_dec SNil && p2_dec s of { Right contra -> Right $ Split'RC $ \s1 _ pf_le pf_eq -> case s1 of { SNil -> case pf_eq of { Refl -> contra } ; SCons _ _ -> case pf_le of { } } ; Left (p1_pf, p2_pf) -> Left $ Split'LC SNil s LEZero Refl p1_pf p2_pf } ; SSucc n' -> \(LESucc pf_le) -> ((p1_dec (sSubstring sZero (sSucc n') s) && p2_dec (sSubstring (sSucc n') (sLength s %:- sSucc n') s)) || split' p1_dec p2_dec s n' _) (\(p1_prefix, p2_suffix) -> Split'LC (sSubstring sZero (sSucc n') s) (sSubstring (sSucc n') (sLength s %:- sSucc n') s) pf_le Refl p1_prefix p2_suffix) (\_ (Split'LC prefix suffix pf_le' pf_eq p1_prefix p2_suffix) -> Split'LC prefix suffix pf_le pf_eq p1_prefix p2_suffix) (\bad_pre_or_suff (Split'RC contra) -> Split'RC $ \s1 s2 pf_le' pf_eq -> case bad_pre_or_suff of { Left bad_pre -> Left bad_pre ; Right bad_suf -> Right bad_suf }) }
null
https://raw.githubusercontent.com/goldfirere/thesis/22f066bc26b1147530525aabb3df686416b3e4aa/hs/dephs/cpdt8.hs
haskell
# LANGUAGE TemplateHaskell , PolyKinds , DataKinds , RankNTypes , TypeFamilies , GADTs , NoImplicitPrelude , TypeOperators , LambdaCase , EmptyCase , TypeHoles # GADTs, NoImplicitPrelude, TypeOperators, LambdaCase, EmptyCase, TypeHoles #-} import Prelude ((++), Either(..), undefined, ($)) import Data.Singletons $(singletons [d| data Char = CA | CB | CC | CD | CE data Nat = Zero | Succ Nat length :: [a] -> Nat length [] = Zero length (_:t) = Succ (length t) truncate :: Nat -> [Char] -> [Char] truncate Zero s = [] truncate (Succ n) (h : t) = h : (truncate n t) truncate (Succ _) [] = [] substring :: Nat -> Nat -> [Char] -> [Char] substring Zero n s = truncate n s substring (Succ start) n (h : t) = substring start n t substring (Succ _) n [] = [] (-) :: Nat -> Nat -> Nat Zero - a = Zero (Succ n) - (Succ m) = n - m (Succ n) - Zero = Succ n |]) data a :~: b where Refl :: a :~: a data False absurd :: False -> a absurd = \case {} type Refuted a = a -> False type Decidable a = Either a (Refuted a) data Star :: ([Char] -> *) -> [Char] -> * where Empty :: Star p '[] Iter :: p s1 -> Star p s2 -> Star p (s1 :++ s2) data Existential :: (k -> *) -> * where Exists :: Sing x -> p x -> Existential p data ConcatCond p1 p2 s where ConcatCondC :: Sing s1 -> Sing s2 -> (s :~: (s1 :++ s2)) -> p1 s1 -> p2 s2 -> ConcatCond p1 p2 s data OrCond p1 p2 s where OrCondC :: Either (p1 s) (p2 s) -> OrCond p1 p2 s data Regexp :: ([Char] -> *) -> * where RChar :: SChar ch -> Regexp ((:~:) '[ch]) RConcat :: Regexp p1 -> Regexp p2 -> Regexp (ConcatCond p1 p2) ROr :: Regexp p1 -> Regexp p2 -> Regexp (OrCond p1 p2) RStar :: Regexp p -> Regexp (Star p) data a <= b where LEZero :: Zero <= b LESucc :: a <= b -> (Succ a) <= (Succ b) le_succ :: Sing a -> a <= Succ (Succ a) le_succ SZero = LEZero le_succ (SSucc n') = LESucc $ le_succ n' data Split'L n s p1 p2 where Split'LC :: Sing s1 -> Sing s2 -> Length s1 <= n -> (s1 :++ s2) :~: s -> p1 s1 -> p2 s2 -> Split'L n s p1 p2 data Split'R n s p1 p2 where Split'RC :: (forall s1 s2. Sing s1 -> Sing s2 -> Length s1 <= n -> (s1 :++ s2) :~: s -> Either (Refuted (p1 s1)) (Refuted (p2 s2))) -> Split'R n s p1 p2 (&&) :: Either a b -> Either c d -> Either (a, c) (Either b d) (Left a) && (Left c) = Left (a, c) (Left _) && (Right d) = Right (Right d) (Right b) && (Left _) = Right (Left b) (Right b) && (Right _) = Right (Left b) (||) :: Either a b -> Either c d -> (a -> e) -> (b -> c -> e) -> (b -> d -> f) -> Either e f (Left x) || _ = \first _ _ -> Left $ first x (Right x) || (Left y) = \_ second _ -> Left $ second x y (Right x) || (Right y) = \_ _ third -> Right $ third x y split' :: (forall s. Sing s -> Decidable (p1 s)) -> (forall s. Sing s -> Decidable (p2 s)) -> Sing (s :: [Char]) -> SNat n -> n <= Length s -> Either (Split'L n s p1 p2) (Split'R n s p1 p2) split' p1_dec p2_dec s n = case n of { SZero -> \_ -> case p1_dec SNil && p2_dec s of { Right contra -> Right $ Split'RC $ \s1 _ pf_le pf_eq -> case s1 of { SNil -> case pf_eq of { Refl -> contra } ; SCons _ _ -> case pf_le of { } } ; Left (p1_pf, p2_pf) -> Left $ Split'LC SNil s LEZero Refl p1_pf p2_pf } ; SSucc n' -> \(LESucc pf_le) -> ((p1_dec (sSubstring sZero (sSucc n') s) && p2_dec (sSubstring (sSucc n') (sLength s %:- sSucc n') s)) || split' p1_dec p2_dec s n' _) (\(p1_prefix, p2_suffix) -> Split'LC (sSubstring sZero (sSucc n') s) (sSubstring (sSucc n') (sLength s %:- sSucc n') s) pf_le Refl p1_prefix p2_suffix) (\_ (Split'LC prefix suffix pf_le' pf_eq p1_prefix p2_suffix) -> Split'LC prefix suffix pf_le pf_eq p1_prefix p2_suffix) (\bad_pre_or_suff (Split'RC contra) -> Split'RC $ \s1 s2 pf_le' pf_eq -> case bad_pre_or_suff of { Left bad_pre -> Left bad_pre ; Right bad_suf -> Right bad_suf }) }
9d166bb223b84b63cdd81f16d0f98159778c7d86a2c69deffa7c9c1d4515d955
docker-in-aws/docker-in-aws
info.cljs
(ns swarmpit.component.stack.info (:require [material.icon :as icon] [material.component :as comp] [material.component.form :as form] [material.component.panel :as panel] [material.component.list-table-auto :as list] [swarmpit.component.message :as message] [swarmpit.component.state :as state] [swarmpit.component.mixin :as mixin] [swarmpit.component.progress :as progress] [swarmpit.component.service.list :as services] [swarmpit.component.network.list :as networks] [swarmpit.component.volume.list :as volumes] [swarmpit.component.config.list :as configs] [swarmpit.component.secret.list :as secrets] [swarmpit.ajax :as ajax] [swarmpit.url :refer [dispatch!]] [swarmpit.routes :as routes] [rum.core :as rum] [material.component.label :as label] [swarmpit.docker.utils :as utils] [clojure.string :refer [includes?]])) (enable-console-print!) (defn- stack-services-handler [stack-name] (ajax/get (routes/path-for-backend :stack-services {:name stack-name}) {:state [:loading?] :on-success (fn [{:keys [response]}] (state/update-value [:services] response state/form-value-cursor))})) (defn- stack-networks-handler [stack-name] (ajax/get (routes/path-for-backend :stack-networks {:name stack-name}) {:on-success (fn [{:keys [response]}] (state/update-value [:networks] response state/form-value-cursor))})) (defn- stack-volumes-handler [stack-name] (ajax/get (routes/path-for-backend :stack-volumes {:name stack-name}) {:on-success (fn [{:keys [response]}] (state/update-value [:volumes] response state/form-value-cursor))})) (defn- stack-configs-handler [stack-name] (ajax/get (routes/path-for-backend :stack-configs {:name stack-name}) {:on-success (fn [{:keys [response]}] (state/update-value [:configs] response state/form-value-cursor))})) (defn- stack-secrets-handler [stack-name] (ajax/get (routes/path-for-backend :stack-secrets {:name stack-name}) {:on-success (fn [{:keys [response]}] (state/update-value [:secrets] response state/form-value-cursor))})) (defn- stackfile-handler [stack-name] (ajax/get (routes/path-for-backend :stack-file {:name stack-name}) {:on-success (fn [{:keys [response]}] (state/update-value [:stackfile] response state/form-value-cursor)) :on-error (fn [_])})) (defn- delete-stack-handler [stack-name] (ajax/delete (routes/path-for-backend :stack-delete {:name stack-name}) {:on-success (fn [_] (dispatch! (routes/path-for-frontend :stack-list)) (message/info (str "Stack " stack-name " has been removed."))) :on-error (fn [{:keys [response]}] (message/error (str "Stack removing failed. " (:error response))))})) (defn- redeploy-stack-handler [stack-name] (message/info (str "Stack " stack-name " redeploy triggered.")) (ajax/post (routes/path-for-backend :stack-redeploy {:name stack-name}) {:on-success (fn [_] (message/info (str "Stack " stack-name " redeploy finished."))) :on-error (fn [{:keys [response]}] (message/error (str "Stack redeploy failed. " (:error response))))})) (defn- rollback-stack-handler [stack-name] (message/info (str "Stack " stack-name " rollback triggered.")) (ajax/post (routes/path-for-backend :stack-rollback {:name stack-name}) {:on-success (fn [_] (message/info (str "Stack " stack-name " rollback finished."))) :on-error (fn [{:keys [response]}] (message/error (str "Stack rollback failed. " (:error response))))})) (def action-menu-style {:position "relative" :marginTop "13px" :marginLeft "66px"}) (def action-menu-item-style {:padding "0px 10px 0px 52px"}) (defn- form-action-menu [stack-name stackfile opened?] (comp/mui (comp/icon-menu {:iconButtonElement (comp/icon-button nil nil) :open opened? :style action-menu-style :onRequestChange (fn [state] (state/update-value [:menu?] state state/form-state-cursor))} (comp/menu-item {:key "action-edit" :innerDivStyle action-menu-item-style :leftIcon (comp/svg nil icon/edit) :onClick (fn [] (dispatch! (routes/path-for-frontend :stack-compose {:name stack-name}))) :primaryText "Edit"}) (comp/menu-item {:key "action-redeploy" :innerDivStyle action-menu-item-style :leftIcon (comp/svg nil icon/redeploy) :onClick #(redeploy-stack-handler stack-name) :disabled (not (some? (:spec stackfile))) :primaryText "Redeploy"}) (comp/menu-item {:key "action-rollback" :innerDivStyle action-menu-item-style :leftIcon (comp/svg nil icon/rollback) :onClick #(rollback-stack-handler stack-name) :disabled (not (some? (:previousSpec stackfile))) :primaryText "Rollback"}) (comp/menu-item {:key "action-delete" :innerDivStyle action-menu-item-style :leftIcon (comp/svg nil icon/trash) :onClick #(delete-stack-handler stack-name) :primaryText "Delete"})))) (defn- stack-render-item [stack-name name-key default-render-item] (fn [item row] (case (key item) :stack (if (not= stack-name (val item)) (label/info "external")) (if (= name-key (key item)) (if (= stack-name (:stack row)) (utils/trim-stack stack-name (val item)) (val item)) (default-render-item item row))))) (rum/defc form-services < rum/static [stack-name services] (when (not-empty services) [:div.form-layout-group (form/section "Services") (list/table (map :name services/headers) (sort-by :serviceName services) (stack-render-item stack-name :serviceName services/render-item) services/render-item-keys services/onclick-handler)])) (rum/defc form-networks < rum/static [stack-name networks] (when (not-empty networks) [:div.form-layout-group.form-layout-group-border (form/section "Networks") (list/table (map :name networks/headers) (sort-by :networkName networks) (stack-render-item stack-name :networkName networks/render-item) (conj networks/render-item-keys [:stack]) networks/onclick-handler)])) (rum/defc form-volumes < rum/static [stack-name volumes] (when (not-empty volumes) [:div.form-layout-group.form-layout-group-border (form/section "Volumes") (list/table (map :name volumes/headers) (sort-by :volumeName volumes) (stack-render-item stack-name :volumeName volumes/render-item) (conj volumes/render-item-keys [:stack]) volumes/onclick-handler)])) (rum/defc form-configs < rum/static [stack-name configs] (when (not-empty configs) [:div.form-layout-group.form-layout-group-border (form/section "Configs") (list/table (map :name configs/headers) (sort-by :configName configs) (stack-render-item stack-name :configName configs/render-item) (conj configs/render-item-keys [:stack]) configs/onclick-handler)])) (rum/defc form-secrets < rum/static [stack-name secrets] (when (not-empty secrets) [:div.form-layout-group.form-layout-group-border (form/section "Secrets") (list/table (map :name configs/headers) (sort-by :secretName secrets) (stack-render-item stack-name :secretName secrets/render-item) (conj secrets/render-item-keys [:stack]) secrets/onclick-handler)])) (defn- init-form-state [] (state/set-value {:menu? false :loading? true} state/form-state-cursor)) (def mixin-init-form (mixin/init-form (fn [{{:keys [name]} :params}] (init-form-state) (stack-services-handler name) (stack-networks-handler name) (stack-volumes-handler name) (stack-configs-handler name) (stack-secrets-handler name) (stackfile-handler name)))) (rum/defc form-info < rum/static [stack-name {:keys [services networks volumes configs secrets stackfile]} {:keys [menu?]}] [:div [:div.form-panel [:div.form-panel-left (panel/info icon/stacks stack-name)] [:div.form-panel-right [:div (comp/mui (comp/raised-button {:onClick (fn [_] (state/update-value [:menu?] true state/form-state-cursor)) :icon (comp/button-icon icon/expand-18) :labelPosition "before" :label "Actions"})) (form-action-menu stack-name stackfile menu?)]]] [:div.form-layout (form-services stack-name services) (form-networks stack-name networks) (form-volumes stack-name volumes) (form-configs stack-name configs) (form-secrets stack-name secrets)]]) (rum/defc form < rum/reactive mixin-init-form mixin/subscribe-form [{{:keys [name]} :params}] (let [state (state/react state/form-state-cursor) item (state/react state/form-value-cursor)] (progress/form (:loading? state) (form-info name item state))))
null
https://raw.githubusercontent.com/docker-in-aws/docker-in-aws/bfc7e82ac82ea158bfb03445da6aec167b1a14a3/ch16/swarmpit/src/cljs/swarmpit/component/stack/info.cljs
clojure
(ns swarmpit.component.stack.info (:require [material.icon :as icon] [material.component :as comp] [material.component.form :as form] [material.component.panel :as panel] [material.component.list-table-auto :as list] [swarmpit.component.message :as message] [swarmpit.component.state :as state] [swarmpit.component.mixin :as mixin] [swarmpit.component.progress :as progress] [swarmpit.component.service.list :as services] [swarmpit.component.network.list :as networks] [swarmpit.component.volume.list :as volumes] [swarmpit.component.config.list :as configs] [swarmpit.component.secret.list :as secrets] [swarmpit.ajax :as ajax] [swarmpit.url :refer [dispatch!]] [swarmpit.routes :as routes] [rum.core :as rum] [material.component.label :as label] [swarmpit.docker.utils :as utils] [clojure.string :refer [includes?]])) (enable-console-print!) (defn- stack-services-handler [stack-name] (ajax/get (routes/path-for-backend :stack-services {:name stack-name}) {:state [:loading?] :on-success (fn [{:keys [response]}] (state/update-value [:services] response state/form-value-cursor))})) (defn- stack-networks-handler [stack-name] (ajax/get (routes/path-for-backend :stack-networks {:name stack-name}) {:on-success (fn [{:keys [response]}] (state/update-value [:networks] response state/form-value-cursor))})) (defn- stack-volumes-handler [stack-name] (ajax/get (routes/path-for-backend :stack-volumes {:name stack-name}) {:on-success (fn [{:keys [response]}] (state/update-value [:volumes] response state/form-value-cursor))})) (defn- stack-configs-handler [stack-name] (ajax/get (routes/path-for-backend :stack-configs {:name stack-name}) {:on-success (fn [{:keys [response]}] (state/update-value [:configs] response state/form-value-cursor))})) (defn- stack-secrets-handler [stack-name] (ajax/get (routes/path-for-backend :stack-secrets {:name stack-name}) {:on-success (fn [{:keys [response]}] (state/update-value [:secrets] response state/form-value-cursor))})) (defn- stackfile-handler [stack-name] (ajax/get (routes/path-for-backend :stack-file {:name stack-name}) {:on-success (fn [{:keys [response]}] (state/update-value [:stackfile] response state/form-value-cursor)) :on-error (fn [_])})) (defn- delete-stack-handler [stack-name] (ajax/delete (routes/path-for-backend :stack-delete {:name stack-name}) {:on-success (fn [_] (dispatch! (routes/path-for-frontend :stack-list)) (message/info (str "Stack " stack-name " has been removed."))) :on-error (fn [{:keys [response]}] (message/error (str "Stack removing failed. " (:error response))))})) (defn- redeploy-stack-handler [stack-name] (message/info (str "Stack " stack-name " redeploy triggered.")) (ajax/post (routes/path-for-backend :stack-redeploy {:name stack-name}) {:on-success (fn [_] (message/info (str "Stack " stack-name " redeploy finished."))) :on-error (fn [{:keys [response]}] (message/error (str "Stack redeploy failed. " (:error response))))})) (defn- rollback-stack-handler [stack-name] (message/info (str "Stack " stack-name " rollback triggered.")) (ajax/post (routes/path-for-backend :stack-rollback {:name stack-name}) {:on-success (fn [_] (message/info (str "Stack " stack-name " rollback finished."))) :on-error (fn [{:keys [response]}] (message/error (str "Stack rollback failed. " (:error response))))})) (def action-menu-style {:position "relative" :marginTop "13px" :marginLeft "66px"}) (def action-menu-item-style {:padding "0px 10px 0px 52px"}) (defn- form-action-menu [stack-name stackfile opened?] (comp/mui (comp/icon-menu {:iconButtonElement (comp/icon-button nil nil) :open opened? :style action-menu-style :onRequestChange (fn [state] (state/update-value [:menu?] state state/form-state-cursor))} (comp/menu-item {:key "action-edit" :innerDivStyle action-menu-item-style :leftIcon (comp/svg nil icon/edit) :onClick (fn [] (dispatch! (routes/path-for-frontend :stack-compose {:name stack-name}))) :primaryText "Edit"}) (comp/menu-item {:key "action-redeploy" :innerDivStyle action-menu-item-style :leftIcon (comp/svg nil icon/redeploy) :onClick #(redeploy-stack-handler stack-name) :disabled (not (some? (:spec stackfile))) :primaryText "Redeploy"}) (comp/menu-item {:key "action-rollback" :innerDivStyle action-menu-item-style :leftIcon (comp/svg nil icon/rollback) :onClick #(rollback-stack-handler stack-name) :disabled (not (some? (:previousSpec stackfile))) :primaryText "Rollback"}) (comp/menu-item {:key "action-delete" :innerDivStyle action-menu-item-style :leftIcon (comp/svg nil icon/trash) :onClick #(delete-stack-handler stack-name) :primaryText "Delete"})))) (defn- stack-render-item [stack-name name-key default-render-item] (fn [item row] (case (key item) :stack (if (not= stack-name (val item)) (label/info "external")) (if (= name-key (key item)) (if (= stack-name (:stack row)) (utils/trim-stack stack-name (val item)) (val item)) (default-render-item item row))))) (rum/defc form-services < rum/static [stack-name services] (when (not-empty services) [:div.form-layout-group (form/section "Services") (list/table (map :name services/headers) (sort-by :serviceName services) (stack-render-item stack-name :serviceName services/render-item) services/render-item-keys services/onclick-handler)])) (rum/defc form-networks < rum/static [stack-name networks] (when (not-empty networks) [:div.form-layout-group.form-layout-group-border (form/section "Networks") (list/table (map :name networks/headers) (sort-by :networkName networks) (stack-render-item stack-name :networkName networks/render-item) (conj networks/render-item-keys [:stack]) networks/onclick-handler)])) (rum/defc form-volumes < rum/static [stack-name volumes] (when (not-empty volumes) [:div.form-layout-group.form-layout-group-border (form/section "Volumes") (list/table (map :name volumes/headers) (sort-by :volumeName volumes) (stack-render-item stack-name :volumeName volumes/render-item) (conj volumes/render-item-keys [:stack]) volumes/onclick-handler)])) (rum/defc form-configs < rum/static [stack-name configs] (when (not-empty configs) [:div.form-layout-group.form-layout-group-border (form/section "Configs") (list/table (map :name configs/headers) (sort-by :configName configs) (stack-render-item stack-name :configName configs/render-item) (conj configs/render-item-keys [:stack]) configs/onclick-handler)])) (rum/defc form-secrets < rum/static [stack-name secrets] (when (not-empty secrets) [:div.form-layout-group.form-layout-group-border (form/section "Secrets") (list/table (map :name configs/headers) (sort-by :secretName secrets) (stack-render-item stack-name :secretName secrets/render-item) (conj secrets/render-item-keys [:stack]) secrets/onclick-handler)])) (defn- init-form-state [] (state/set-value {:menu? false :loading? true} state/form-state-cursor)) (def mixin-init-form (mixin/init-form (fn [{{:keys [name]} :params}] (init-form-state) (stack-services-handler name) (stack-networks-handler name) (stack-volumes-handler name) (stack-configs-handler name) (stack-secrets-handler name) (stackfile-handler name)))) (rum/defc form-info < rum/static [stack-name {:keys [services networks volumes configs secrets stackfile]} {:keys [menu?]}] [:div [:div.form-panel [:div.form-panel-left (panel/info icon/stacks stack-name)] [:div.form-panel-right [:div (comp/mui (comp/raised-button {:onClick (fn [_] (state/update-value [:menu?] true state/form-state-cursor)) :icon (comp/button-icon icon/expand-18) :labelPosition "before" :label "Actions"})) (form-action-menu stack-name stackfile menu?)]]] [:div.form-layout (form-services stack-name services) (form-networks stack-name networks) (form-volumes stack-name volumes) (form-configs stack-name configs) (form-secrets stack-name secrets)]]) (rum/defc form < rum/reactive mixin-init-form mixin/subscribe-form [{{:keys [name]} :params}] (let [state (state/react state/form-state-cursor) item (state/react state/form-value-cursor)] (progress/form (:loading? state) (form-info name item state))))
d7ec7c9af8c20f17d692403bf4271b2b69edff8d55671e987900b5ab51ba1406
bytekid/mkbtt
connected.ml
Copyright 2010 * GNU Lesser General Public License * * This file is part of MKBtt . * * is free software : you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the * Free Software Foundation , either version 3 of the License , or ( at your * option ) any later version . * * 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 MKBtt . If not , see < / > . * GNU Lesser General Public License * * This file is part of MKBtt. * * MKBtt is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * MKBtt 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 MKBtt. If not, see </>. *) * Inferences for non - ordered multicompletion with termination tools . @author @since 2011/03/01 @author Sarah Winkler @since 2011/03/01 *) * * OPENS ( 1 ) * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * open Util;; (*** SUBMODULES **********************************************************) module Pos = Rewriting.Position;; module Sub = U.Substitution;; module Term = U.Term;; module Rule = U.Rule;; module W = World;; module Monad = W.Monad;; module N = IndexedNode;; module NI = NodeTermIndex;; module CC = CPCCache;; * * OPENS ( 2 ) * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * open Monad;; (*** FUNCTIONS ***********************************************************) let intersect = List.intersect;; let union = List.union;; let diff = List.diff;; let is_empty = List.is_empty;; * * OPENS ( 2 ) * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * open Monad;; let lookup_redundant_processes o = failwith "CCP does not support caching" let normalize u v = W.M.Equation.oriented_of_terms u v >>= fun (eqn, _) -> return (Equation.terms eqn) ;; let considered_for outer p inner = W.M.Rulex.narrow (Rule.lhs outer) inner p >>= function | Some (u, sigma, inner') -> let v = Sub.apply_term sigma (Rule.rhs outer) in normalize u v >>= fun (u,v) -> N.considered_for u v | None -> return [] ;; let output_considered c u outer p inner ps = W.M.Term.to_stringm u >>= fun us -> W.M.Rule.to_stringm outer >>= fun o -> W.M.Rule.to_stringm inner >>= fun i -> Format.printf "case (%s) reducing %s:\n CP <%s, %s, %s> already considered for %s\n%!" c us i (Pos.to_string p) o (CompletionProcessx.set_to_string ps); return () ;; let mem = List.mem;; let inter = List.foldl1 List.intersect for positions p , q where p = q.r , without p q returns r. Fails otherwise let without p q = let rec without p q = match p,q with | _, [] -> p | i ::p', j::q' when i=j -> without p' q' | _ -> failwith "without for position failed" in Pos.of_list (without (Pos.to_list p) (Pos.to_list q)) ;; rl0 is outer , rl2 inner rule of cp at position p in lhs of rl0 . rl1 reduces overlapped term u at position equational proofs connect s = t : s < -^epsilon_rl0 u ->^q_rl1 w ( P1 ) w < -^q_rl1 u - > p_rl2 t ( P2 ) Returns process set , subset of ps for which the CP is NOT connected rl1 reduces overlapped term u at position q. Two equational proofs connect s=t: s <-^epsilon_rl0 u ->^q_rl1 w (P1) w <-^q_rl1 u -> p_rl2 t (P2) Returns process set, subset of ps for which the CP is NOT connected*) let connected_below ps rl1 q (u,((rl0,_,_),p,(rl2,_,_)),_) = let (>) = Pos.(>) in (* (alpha) *) (if mem q (Term.funs_pos (Rule.lhs rl0)) then considered_for rl0 q rl1 else return ps) >>= fun psa -> (* (beta) *) (if (p > q) && (mem (without p q) (Term.funs_pos (Rule.lhs rl1))) then considered_for rl1 (without p q) rl2 else return ps) >>= fun psb -> (* (gamma) *) (if q=Pos.root then considered_for rl1 q rl0 else return ps) >>= fun psc -> (* (delta) *) (if (q > p) && (mem (without q p) (Term.funs_pos (Rule.lhs rl2))) then considered_for rl2 (without q p) rl1 else return ps) >>= fun psd -> return (diff ps (inter [psa;psb;psc;psd])) ;; let remove_rule_label overlap ps ((i, b), q) = N.brule b i >>= W.M.Rule.rename >>= fun rule -> N.brc b i >>= fun ps' -> if is_empty (intersect ps ps') then return ps else connected_below (intersect ps ps') rule q overlap >>= fun connected -> return (union (diff ps ps') connected) ;; let compute_nonredundant ((u,o,_) as overlap) pset = let usable ((_,_,m),_,(_,_,d)) ((i,_),_) = (fst m <> i) && (fst d <> i) in NI.encompassment_candidates u >>= fun matches -> let matches = List.filter (usable o) matches in foldl (remove_rule_label overlap) pset matches ;; looks up redundant processes in hashtable , and reduced different set if entry was found for this overlap . otherwise , redundnats are computed and stored . note that due to caching , fewer redundants might be returned than actually possible if entry was found for this overlap. otherwise, redundnats are computed and stored. note that due to caching, fewer redundants might be returned than actually possible *) let filter_nonredundant overlap process_set = CC.caching_active >>= fun cache -> if cache then ( lookup_redundant_processes overlap >>= function | None -> compute_nonredundant overlap process_set >>= fun nonred -> let red = diff process_set nonred in if not ( is_empty red ) then CC.store_redundant_for_term ( term overlap ) red > > return nonred else if not (is_empty red) then CC.store_redundant_for_term (term overlap) red >> return nonred else*) return nonred | Some red -> return (diff process_set red)) else compute_nonredundant overlap process_set ;;
null
https://raw.githubusercontent.com/bytekid/mkbtt/c2f8e0615389b52eabd12655fe48237aa0fe83fd/src/mascott/src/connected.ml
ocaml
** SUBMODULES ********************************************************* ** FUNCTIONS ********************************************************** (alpha) (beta) (gamma) (delta)
Copyright 2010 * GNU Lesser General Public License * * This file is part of MKBtt . * * is free software : you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the * Free Software Foundation , either version 3 of the License , or ( at your * option ) any later version . * * 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 MKBtt . If not , see < / > . * GNU Lesser General Public License * * This file is part of MKBtt. * * MKBtt is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * MKBtt 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 MKBtt. If not, see </>. *) * Inferences for non - ordered multicompletion with termination tools . @author @since 2011/03/01 @author Sarah Winkler @since 2011/03/01 *) * * OPENS ( 1 ) * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * open Util;; module Pos = Rewriting.Position;; module Sub = U.Substitution;; module Term = U.Term;; module Rule = U.Rule;; module W = World;; module Monad = W.Monad;; module N = IndexedNode;; module NI = NodeTermIndex;; module CC = CPCCache;; * * OPENS ( 2 ) * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * open Monad;; let intersect = List.intersect;; let union = List.union;; let diff = List.diff;; let is_empty = List.is_empty;; * * OPENS ( 2 ) * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * open Monad;; let lookup_redundant_processes o = failwith "CCP does not support caching" let normalize u v = W.M.Equation.oriented_of_terms u v >>= fun (eqn, _) -> return (Equation.terms eqn) ;; let considered_for outer p inner = W.M.Rulex.narrow (Rule.lhs outer) inner p >>= function | Some (u, sigma, inner') -> let v = Sub.apply_term sigma (Rule.rhs outer) in normalize u v >>= fun (u,v) -> N.considered_for u v | None -> return [] ;; let output_considered c u outer p inner ps = W.M.Term.to_stringm u >>= fun us -> W.M.Rule.to_stringm outer >>= fun o -> W.M.Rule.to_stringm inner >>= fun i -> Format.printf "case (%s) reducing %s:\n CP <%s, %s, %s> already considered for %s\n%!" c us i (Pos.to_string p) o (CompletionProcessx.set_to_string ps); return () ;; let mem = List.mem;; let inter = List.foldl1 List.intersect for positions p , q where p = q.r , without p q returns r. Fails otherwise let without p q = let rec without p q = match p,q with | _, [] -> p | i ::p', j::q' when i=j -> without p' q' | _ -> failwith "without for position failed" in Pos.of_list (without (Pos.to_list p) (Pos.to_list q)) ;; rl0 is outer , rl2 inner rule of cp at position p in lhs of rl0 . rl1 reduces overlapped term u at position equational proofs connect s = t : s < -^epsilon_rl0 u ->^q_rl1 w ( P1 ) w < -^q_rl1 u - > p_rl2 t ( P2 ) Returns process set , subset of ps for which the CP is NOT connected rl1 reduces overlapped term u at position q. Two equational proofs connect s=t: s <-^epsilon_rl0 u ->^q_rl1 w (P1) w <-^q_rl1 u -> p_rl2 t (P2) Returns process set, subset of ps for which the CP is NOT connected*) let connected_below ps rl1 q (u,((rl0,_,_),p,(rl2,_,_)),_) = let (>) = Pos.(>) in (if mem q (Term.funs_pos (Rule.lhs rl0)) then considered_for rl0 q rl1 else return ps) >>= fun psa -> (if (p > q) && (mem (without p q) (Term.funs_pos (Rule.lhs rl1))) then considered_for rl1 (without p q) rl2 else return ps) >>= fun psb -> (if q=Pos.root then considered_for rl1 q rl0 else return ps) >>= fun psc -> (if (q > p) && (mem (without q p) (Term.funs_pos (Rule.lhs rl2))) then considered_for rl2 (without q p) rl1 else return ps) >>= fun psd -> return (diff ps (inter [psa;psb;psc;psd])) ;; let remove_rule_label overlap ps ((i, b), q) = N.brule b i >>= W.M.Rule.rename >>= fun rule -> N.brc b i >>= fun ps' -> if is_empty (intersect ps ps') then return ps else connected_below (intersect ps ps') rule q overlap >>= fun connected -> return (union (diff ps ps') connected) ;; let compute_nonredundant ((u,o,_) as overlap) pset = let usable ((_,_,m),_,(_,_,d)) ((i,_),_) = (fst m <> i) && (fst d <> i) in NI.encompassment_candidates u >>= fun matches -> let matches = List.filter (usable o) matches in foldl (remove_rule_label overlap) pset matches ;; looks up redundant processes in hashtable , and reduced different set if entry was found for this overlap . otherwise , redundnats are computed and stored . note that due to caching , fewer redundants might be returned than actually possible if entry was found for this overlap. otherwise, redundnats are computed and stored. note that due to caching, fewer redundants might be returned than actually possible *) let filter_nonredundant overlap process_set = CC.caching_active >>= fun cache -> if cache then ( lookup_redundant_processes overlap >>= function | None -> compute_nonredundant overlap process_set >>= fun nonred -> let red = diff process_set nonred in if not ( is_empty red ) then CC.store_redundant_for_term ( term overlap ) red > > return nonred else if not (is_empty red) then CC.store_redundant_for_term (term overlap) red >> return nonred else*) return nonred | Some red -> return (diff process_set red)) else compute_nonredundant overlap process_set ;;
ab11803472f1a8ceeb375d021c0b0dd53f2d6d4e4113e408358fb6abb2fcc016
ocaml/ocaml-lsp
metrics.ml
open Test.Import let%expect_test "metrics" = let handler = let on_request (type r) _ (r : r Lsp.Server_request.t) : (r Lsp_fiber.Rpc.Reply.t * unit) Fiber.t = match r with | ShowDocumentRequest p -> print_endline "client: received show document params"; let json = ShowDocumentParams.yojson_of_t { p with uri = Uri.of_path "<redacted>" } in Yojson.Safe.to_channel stdout json; print_endline ""; print_endline "metrics contents:"; print_endline (Stdune.Io.String_path.read_file (Uri.to_path p.uri)); let res = ShowDocumentResult.create ~success:true in Fiber.return (Lsp_fiber.Rpc.Reply.now res, ()) | _ -> assert false in let on_request = { Client.Handler.on_request } in let on_notification (_ : _ Client.t) (_ : Client.in_notification) = (* ignore notifications *) Fiber.return () in Client.Handler.make ~on_request ~on_notification () in ( Test.run ~handler @@ fun client -> let run_client () = let capabilities = ClientCapabilities.create () in Client.start client (InitializeParams.create ~capabilities ()) in let run = let* (_ : InitializeResult.t) = Client.initialized client in let view_metrics = ExecuteCommandParams.create ~command:"ocamllsp/view-metrics" () in let+ res = Client.request client (ExecuteCommand view_metrics) in print_endline "server: receiving response"; Yojson.Safe.to_channel stdout res; print_endline "" in Fiber.fork_and_join_unit run_client (fun () -> run >>> Client.stop client) ); [%expect {| client: received show document params {"takeFocus":true,"uri":"file"} metrics contents: {"traceEvents":[]} server: receiving response null |}]
null
https://raw.githubusercontent.com/ocaml/ocaml-lsp/cc609ef1c9f3653cfc14227630a896274f74b966/ocaml-lsp-server/test/e2e-new/metrics.ml
ocaml
ignore notifications
open Test.Import let%expect_test "metrics" = let handler = let on_request (type r) _ (r : r Lsp.Server_request.t) : (r Lsp_fiber.Rpc.Reply.t * unit) Fiber.t = match r with | ShowDocumentRequest p -> print_endline "client: received show document params"; let json = ShowDocumentParams.yojson_of_t { p with uri = Uri.of_path "<redacted>" } in Yojson.Safe.to_channel stdout json; print_endline ""; print_endline "metrics contents:"; print_endline (Stdune.Io.String_path.read_file (Uri.to_path p.uri)); let res = ShowDocumentResult.create ~success:true in Fiber.return (Lsp_fiber.Rpc.Reply.now res, ()) | _ -> assert false in let on_request = { Client.Handler.on_request } in let on_notification (_ : _ Client.t) (_ : Client.in_notification) = Fiber.return () in Client.Handler.make ~on_request ~on_notification () in ( Test.run ~handler @@ fun client -> let run_client () = let capabilities = ClientCapabilities.create () in Client.start client (InitializeParams.create ~capabilities ()) in let run = let* (_ : InitializeResult.t) = Client.initialized client in let view_metrics = ExecuteCommandParams.create ~command:"ocamllsp/view-metrics" () in let+ res = Client.request client (ExecuteCommand view_metrics) in print_endline "server: receiving response"; Yojson.Safe.to_channel stdout res; print_endline "" in Fiber.fork_and_join_unit run_client (fun () -> run >>> Client.stop client) ); [%expect {| client: received show document params {"takeFocus":true,"uri":"file"} metrics contents: {"traceEvents":[]} server: receiving response null |}]
2c169199ee44b0c34289357f455f5c43e1779fee56feb1a316371789dbc2f571
bobzhang/ocaml-book
ast_map.ml
open Printf; type a = [ A of b | C] and b = [ B of a | D ] ; class map = Camlp4MapGenerator.generated; let v = object inherit map as super; method! b x = match super#b x with [ D -> B C | x -> x]; end in assert (v#b D = B (C));
null
https://raw.githubusercontent.com/bobzhang/ocaml-book/09a575b0d1fedfce565ecb9a0ae9cf0df37fdc75/code/camlp4/filters/ast_map/ast_map.ml
ocaml
open Printf; type a = [ A of b | C] and b = [ B of a | D ] ; class map = Camlp4MapGenerator.generated; let v = object inherit map as super; method! b x = match super#b x with [ D -> B C | x -> x]; end in assert (v#b D = B (C));
a77c20ce886c20f04da11746b42fe24d7c16e6fb0fa6bb5f24ea38172a5b8d56
rfkm/zou
handler_test.clj
(ns zou.web.handler-test (:require [clojure.test :as t] [midje.sweet :refer :all] [ring.mock.request :as mock] [zou.util.namespace :as un] [zou.web.handler :as sut])) (def req (assoc (mock/request :get "/") :params {:a :aa :b {:c :d}} :zou/container {:view :view'})) (t/deftest args-mapper-impl-test (fact (sut/defhandler a [a b|c |params|b $view $req $request |params :as {aa :a}] [a c b $view $req $request aa]) (sut/invoke-with-mapper a req) => [:aa :d {:c :d} :view' req req :aa]) (fact (sut/defhandler b "doc" {:a :b} [a]) (meta #'b) => (contains {:doc "doc" :a :b}))) (t/deftest defhandler-metadata-test (fact (sut/defhandler ^:foo c []) (contains? (meta #'c) :foo) => true) (fact "defhandler accepts handler name (for metadata-based finder)" (sut/defhandler d :d []) (:zou/handler (meta #'d)) => :d) (fact "default handler name" (sut/defhandler e []) (:zou/handler (meta #'e)) => :zou.web.handler-test/e) (fact "defhandler attaches `:zou/handler-ns` tag to the current ns" (un/with-temp-ns [ns '((zou.web.handler/defhandler foo []))] (:zou/handler-ns (meta ns)) => true)))
null
https://raw.githubusercontent.com/rfkm/zou/228feefae3e008f56806589cb8019511981f7b01/web/test/zou/web/handler_test.clj
clojure
(ns zou.web.handler-test (:require [clojure.test :as t] [midje.sweet :refer :all] [ring.mock.request :as mock] [zou.util.namespace :as un] [zou.web.handler :as sut])) (def req (assoc (mock/request :get "/") :params {:a :aa :b {:c :d}} :zou/container {:view :view'})) (t/deftest args-mapper-impl-test (fact (sut/defhandler a [a b|c |params|b $view $req $request |params :as {aa :a}] [a c b $view $req $request aa]) (sut/invoke-with-mapper a req) => [:aa :d {:c :d} :view' req req :aa]) (fact (sut/defhandler b "doc" {:a :b} [a]) (meta #'b) => (contains {:doc "doc" :a :b}))) (t/deftest defhandler-metadata-test (fact (sut/defhandler ^:foo c []) (contains? (meta #'c) :foo) => true) (fact "defhandler accepts handler name (for metadata-based finder)" (sut/defhandler d :d []) (:zou/handler (meta #'d)) => :d) (fact "default handler name" (sut/defhandler e []) (:zou/handler (meta #'e)) => :zou.web.handler-test/e) (fact "defhandler attaches `:zou/handler-ns` tag to the current ns" (un/with-temp-ns [ns '((zou.web.handler/defhandler foo []))] (:zou/handler-ns (meta ns)) => true)))
06e60b52cbadb55892f93ee2a9cdd41a7e071201a1b574219f400aec6b6f7c66
ocamllabs/ocaml-modular-implicits
event.mli
(***********************************************************************) (* *) (* OCaml *) (* *) and , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with (* the special exception on linking described in file ../../LICENSE. *) (* *) (***********************************************************************) * First - class synchronous communication . This module implements synchronous inter - thread communications over channels . As in Concurrent ML system , the communication events are first - class values : they can be built and combined independently before being offered for communication . This module implements synchronous inter-thread communications over channels. As in John Reppy's Concurrent ML system, the communication events are first-class values: they can be built and combined independently before being offered for communication. *) type 'a channel (** The type of communication channels carrying values of type ['a]. *) val new_channel : unit -> 'a channel (** Return a new channel. *) type +'a event (** The type of communication events returning a result of type ['a]. *) (** [send ch v] returns the event consisting in sending the value [v] over the channel [ch]. The result value of this event is [()]. *) val send : 'a channel -> 'a -> unit event (** [receive ch] returns the event consisting in receiving a value from the channel [ch]. The result value of this event is the value received. *) val receive : 'a channel -> 'a event val always : 'a -> 'a event (** [always v] returns an event that is always ready for synchronization. The result value of this event is [v]. *) val choose : 'a event list -> 'a event (** [choose evl] returns the event that is the alternative of all the events in the list [evl]. *) val wrap : 'a event -> ('a -> 'b) -> 'b event (** [wrap ev fn] returns the event that performs the same communications as [ev], then applies the post-processing function [fn] on the return value. *) val wrap_abort : 'a event -> (unit -> unit) -> 'a event * [ ] returns the event that performs the same communications as [ ev ] , but if it is not selected the function [ fn ] is called after the synchronization . the same communications as [ev], but if it is not selected the function [fn] is called after the synchronization. *) val guard : (unit -> 'a event) -> 'a event (** [guard fn] returns the event that, when synchronized, computes [fn()] and behaves as the resulting event. This allows events with side-effects to be computed at the time of the synchronization operation. *) val sync : 'a event -> 'a * ` ` Synchronize '' on an event : offer all the communication possibilities specified in the event to the outside world , and block until one of the communications succeed . The result value of that communication is returned . possibilities specified in the event to the outside world, and block until one of the communications succeed. The result value of that communication is returned. *) val select : 'a event list -> 'a * ` ` Synchronize '' on an alternative of events . [ select evl ] is shorthand for [ sync(choose evl ) ] . [select evl] is shorthand for [sync(choose evl)]. *) val poll : 'a event -> 'a option (** Non-blocking version of {!Event.sync}: offer all the communication possibilities specified in the event to the outside world, and if one can take place immediately, perform it and return [Some r] where [r] is the result value of that communication. Otherwise, return [None] without blocking. *)
null
https://raw.githubusercontent.com/ocamllabs/ocaml-modular-implicits/92e45da5c8a4c2db8b2cd5be28a5bec2ac2181f1/otherlibs/threads/event.mli
ocaml
********************************************************************* OCaml the special exception on linking described in file ../../LICENSE. ********************************************************************* * The type of communication channels carrying values of type ['a]. * Return a new channel. * The type of communication events returning a result of type ['a]. * [send ch v] returns the event consisting in sending the value [v] over the channel [ch]. The result value of this event is [()]. * [receive ch] returns the event consisting in receiving a value from the channel [ch]. The result value of this event is the value received. * [always v] returns an event that is always ready for synchronization. The result value of this event is [v]. * [choose evl] returns the event that is the alternative of all the events in the list [evl]. * [wrap ev fn] returns the event that performs the same communications as [ev], then applies the post-processing function [fn] on the return value. * [guard fn] returns the event that, when synchronized, computes [fn()] and behaves as the resulting event. This allows events with side-effects to be computed at the time of the synchronization operation. * Non-blocking version of {!Event.sync}: offer all the communication possibilities specified in the event to the outside world, and if one can take place immediately, perform it and return [Some r] where [r] is the result value of that communication. Otherwise, return [None] without blocking.
and , projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with * First - class synchronous communication . This module implements synchronous inter - thread communications over channels . As in Concurrent ML system , the communication events are first - class values : they can be built and combined independently before being offered for communication . This module implements synchronous inter-thread communications over channels. As in John Reppy's Concurrent ML system, the communication events are first-class values: they can be built and combined independently before being offered for communication. *) type 'a channel val new_channel : unit -> 'a channel type +'a event val send : 'a channel -> 'a -> unit event val receive : 'a channel -> 'a event val always : 'a -> 'a event val choose : 'a event list -> 'a event val wrap : 'a event -> ('a -> 'b) -> 'b event val wrap_abort : 'a event -> (unit -> unit) -> 'a event * [ ] returns the event that performs the same communications as [ ev ] , but if it is not selected the function [ fn ] is called after the synchronization . the same communications as [ev], but if it is not selected the function [fn] is called after the synchronization. *) val guard : (unit -> 'a event) -> 'a event val sync : 'a event -> 'a * ` ` Synchronize '' on an event : offer all the communication possibilities specified in the event to the outside world , and block until one of the communications succeed . The result value of that communication is returned . possibilities specified in the event to the outside world, and block until one of the communications succeed. The result value of that communication is returned. *) val select : 'a event list -> 'a * ` ` Synchronize '' on an alternative of events . [ select evl ] is shorthand for [ sync(choose evl ) ] . [select evl] is shorthand for [sync(choose evl)]. *) val poll : 'a event -> 'a option
ade6ecd10816040742b9a6b03ebda6c004579f3b5bcb807763079fea344f6ff3
runtimeverification/haskell-backend
ProductionID.hs
module Test.Kore.Attribute.ProductionID ( test_productionID, test_Attributes, test_duplicate, test_zeroArguments, test_twoArguments, test_parameters, ) where import Kore.Attribute.ProductionID import Kore.Syntax.Pattern import Prelude.Kore import Test.Kore.Attribute.Parser import Test.Tasty import Test.Tasty.HUnit parseProductionID :: Attributes -> Parser ProductionID parseProductionID = parseAttributes test_productionID :: TestTree test_productionID = testCase "[productionID{}(\"string\")] :: ProductionID" $ expectSuccess ProductionID{getProductionID = Just "string"} $ parseProductionID $ Attributes [productionIDAttribute "string"] test_Attributes :: TestTree test_Attributes = testCase "[productionID{}(\"string\")] :: Attributes" $ expectSuccess attrs $ parseAttributes attrs where attrs = Attributes [productionIDAttribute "string"] test_duplicate :: TestTree test_duplicate = testCase "[productionID{}(\"string\"), productionID{}(\"string\")]" $ expectFailure $ parseProductionID $ Attributes [attr, attr] where attr = productionIDAttribute "string" test_zeroArguments :: TestTree test_zeroArguments = testCase "[productionID{}()]" $ expectFailure $ parseProductionID $ Attributes [illegalAttribute] where illegalAttribute = (asAttributePattern . ApplicationF) Application { applicationSymbolOrAlias = productionIDSymbol , applicationChildren = [] } test_twoArguments :: TestTree test_twoArguments = testCase "[productionID{}()]" $ expectFailure $ parseProductionID $ Attributes [illegalAttribute] where illegalAttribute = attributePattern productionIDSymbol [attributeString "illegal", attributeString "illegal"] test_parameters :: TestTree test_parameters = testCase "[productionID{illegal}(\"string\")]" $ expectFailure $ parseProductionID $ Attributes [illegalAttribute] where illegalAttribute = attributePattern SymbolOrAlias { symbolOrAliasConstructor = productionIDId , symbolOrAliasParams = [SortVariableSort (SortVariable "illegal")] } [attributeString "string"]
null
https://raw.githubusercontent.com/runtimeverification/haskell-backend/b06757e252ee01fdd5ab8f07de2910711997d845/kore/test/Test/Kore/Attribute/ProductionID.hs
haskell
module Test.Kore.Attribute.ProductionID ( test_productionID, test_Attributes, test_duplicate, test_zeroArguments, test_twoArguments, test_parameters, ) where import Kore.Attribute.ProductionID import Kore.Syntax.Pattern import Prelude.Kore import Test.Kore.Attribute.Parser import Test.Tasty import Test.Tasty.HUnit parseProductionID :: Attributes -> Parser ProductionID parseProductionID = parseAttributes test_productionID :: TestTree test_productionID = testCase "[productionID{}(\"string\")] :: ProductionID" $ expectSuccess ProductionID{getProductionID = Just "string"} $ parseProductionID $ Attributes [productionIDAttribute "string"] test_Attributes :: TestTree test_Attributes = testCase "[productionID{}(\"string\")] :: Attributes" $ expectSuccess attrs $ parseAttributes attrs where attrs = Attributes [productionIDAttribute "string"] test_duplicate :: TestTree test_duplicate = testCase "[productionID{}(\"string\"), productionID{}(\"string\")]" $ expectFailure $ parseProductionID $ Attributes [attr, attr] where attr = productionIDAttribute "string" test_zeroArguments :: TestTree test_zeroArguments = testCase "[productionID{}()]" $ expectFailure $ parseProductionID $ Attributes [illegalAttribute] where illegalAttribute = (asAttributePattern . ApplicationF) Application { applicationSymbolOrAlias = productionIDSymbol , applicationChildren = [] } test_twoArguments :: TestTree test_twoArguments = testCase "[productionID{}()]" $ expectFailure $ parseProductionID $ Attributes [illegalAttribute] where illegalAttribute = attributePattern productionIDSymbol [attributeString "illegal", attributeString "illegal"] test_parameters :: TestTree test_parameters = testCase "[productionID{illegal}(\"string\")]" $ expectFailure $ parseProductionID $ Attributes [illegalAttribute] where illegalAttribute = attributePattern SymbolOrAlias { symbolOrAliasConstructor = productionIDId , symbolOrAliasParams = [SortVariableSort (SortVariable "illegal")] } [attributeString "string"]
0e64c649a49b59f28441166c1ee67f5f95249d97a34fa74a4d1c0de7f4216174
gsakkas/rite
0016.ml
TupleG [ListG [],ListG []] ([] , []) ([x + 1] , [x + 1]) ([x + 1] , [x + 2]) ([0] , [0]) ([(h1 + h2) / 10] , [(h1 + h2) mod 10])
null
https://raw.githubusercontent.com/gsakkas/rite/958a0ad2460e15734447bc07bd181f5d35956d3b/data/sp14/clusters/0016.ml
ocaml
TupleG [ListG [],ListG []] ([] , []) ([x + 1] , [x + 1]) ([x + 1] , [x + 2]) ([0] , [0]) ([(h1 + h2) / 10] , [(h1 + h2) mod 10])
d3b6e37efa2a0f171716f9fbf56accb9e182705dae9969947015f5c90d6a6690
GetShopTV/swagger2
ParamSchema.hs
# LANGUAGE DataKinds # # LANGUAGE DefaultSignatures # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE KindSignatures # {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PackageImports #-} # LANGUAGE PolyKinds # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # {-# LANGUAGE TypeSynonymInstances #-} # LANGUAGE UndecidableInstances # Generic a is redundant in ToParamSchema a default imple {-# OPTIONS_GHC -Wno-redundant-constraints #-} For TypeErrors # OPTIONS_GHC -Wno - unticked - promoted - constructors # module Data.Swagger.Internal.ParamSchema where import Control.Lens import Data.Aeson (ToJSON (..)) import Data.Proxy import GHC.Generics import Data.Int import "unordered-containers" Data.HashSet (HashSet) import Data.Monoid import Data.Set (Set) import Data.Scientific import Data.Fixed (HasResolution(..), Fixed, Pico) import qualified Data.Text as T import qualified Data.Text.Lazy as TL import Data.Time import qualified Data.Vector as V import qualified Data.Vector.Primitive as VP import qualified Data.Vector.Storable as VS import qualified Data.Vector.Unboxed as VU import Data.Version (Version) import Numeric.Natural.Compat (Natural) import Data.Word import Data.UUID.Types (UUID) import Web.Cookie (SetCookie) import Data.Swagger.Internal import Data.Swagger.Lens import Data.Swagger.SchemaOptions import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as BSL import GHC.TypeLits (TypeError, ErrorMessage(..)) -- | Default schema for binary data (any sequence of octets). binaryParamSchema :: ParamSchema t binaryParamSchema = mempty & type_ ?~ SwaggerString & format ?~ "binary" -- | Default schema for binary data (base64 encoded). byteParamSchema :: ParamSchema t byteParamSchema = mempty & type_ ?~ SwaggerString & format ?~ "byte" -- | Default schema for password string. -- @"password"@ format is used to hint UIs the input needs to be obscured. passwordParamSchema :: ParamSchema t passwordParamSchema = mempty & type_ ?~ SwaggerString & format ?~ "password" -- | Convert a type into a plain @'ParamSchema'@. -- -- An example type and instance: -- -- @ { -\ # LANGUAGE OverloadedStrings \#- } -- allows to write ' T.Text ' literals -- import Control . Lens -- -- data Direction = Up | Down -- instance ToParamSchema Direction where toParamSchema _ = -- & type_ ?~ SwaggerString -- & enum_ ?~ [ \"Up\", \"Down\" ] -- @ -- -- Instead of manually writing your @'ToParamSchema'@ instance you can use a default generic implementation of @'toParamSchema'@. -- To do that , simply add @deriving ' Generic'@ clause to your datatype -- and declare a @'ToParamSchema'@ instance for your datatype without giving definition for @'toParamSchema'@. -- -- For instance, the previous example can be simplified into this: -- -- @ { -\ # LANGUAGE DeriveGeneric \#- } -- import ( Generic ) -- data Direction = Up | Down deriving Generic -- instance ToParamSchema Direction -- @ class ToParamSchema a where -- | Convert a type into a plain parameter schema. -- > > > encode $ toParamSchema ( Proxy : : Proxy Integer ) -- "{\"type\":\"integer\"}" toParamSchema :: Proxy a -> ParamSchema t default toParamSchema :: (Generic a, GToParamSchema (Rep a)) => Proxy a -> ParamSchema t toParamSchema = genericToParamSchema defaultSchemaOptions instance {-# OVERLAPPING #-} ToParamSchema String where toParamSchema _ = mempty & type_ ?~ SwaggerString instance ToParamSchema Bool where toParamSchema _ = mempty & type_ ?~ SwaggerBoolean instance ToParamSchema Integer where toParamSchema _ = mempty & type_ ?~ SwaggerInteger instance ToParamSchema Natural where toParamSchema _ = mempty & type_ ?~ SwaggerInteger & minimum_ ?~ 0 & exclusiveMinimum ?~ False instance ToParamSchema Int where toParamSchema = toParamSchemaBoundedIntegral instance ToParamSchema Int8 where toParamSchema = toParamSchemaBoundedIntegral instance ToParamSchema Int16 where toParamSchema = toParamSchemaBoundedIntegral instance ToParamSchema Int32 where toParamSchema proxy = toParamSchemaBoundedIntegral proxy & format ?~ "int32" instance ToParamSchema Int64 where toParamSchema proxy = toParamSchemaBoundedIntegral proxy & format ?~ "int64" instance ToParamSchema Word where toParamSchema = toParamSchemaBoundedIntegral instance ToParamSchema Word8 where toParamSchema = toParamSchemaBoundedIntegral instance ToParamSchema Word16 where toParamSchema = toParamSchemaBoundedIntegral instance ToParamSchema Word32 where toParamSchema proxy = toParamSchemaBoundedIntegral proxy & format ?~ "int32" instance ToParamSchema Word64 where toParamSchema proxy = toParamSchemaBoundedIntegral proxy & format ?~ "int64" -- | Default plain schema for @'Bounded'@, @'Integral'@ types. -- -- >>> encode $ toParamSchemaBoundedIntegral (Proxy :: Proxy Int8) -- "{\"maximum\":127,\"minimum\":-128,\"type\":\"integer\"}" toParamSchemaBoundedIntegral :: forall a t. (Bounded a, Integral a) => Proxy a -> ParamSchema t toParamSchemaBoundedIntegral _ = mempty & type_ ?~ SwaggerInteger & minimum_ ?~ fromInteger (toInteger (minBound :: a)) & maximum_ ?~ fromInteger (toInteger (maxBound :: a)) instance ToParamSchema Char where toParamSchema _ = mempty & type_ ?~ SwaggerString & maxLength ?~ 1 & minLength ?~ 1 instance ToParamSchema Scientific where toParamSchema _ = mempty & type_ ?~ SwaggerNumber instance HasResolution a => ToParamSchema (Fixed a) where toParamSchema _ = mempty & type_ ?~ SwaggerNumber & multipleOf ?~ (recip . fromInteger $ resolution (Proxy :: Proxy a)) instance ToParamSchema Double where toParamSchema _ = mempty & type_ ?~ SwaggerNumber & format ?~ "double" instance ToParamSchema Float where toParamSchema _ = mempty & type_ ?~ SwaggerNumber & format ?~ "float" timeParamSchema :: String -> ParamSchema t timeParamSchema fmt = mempty & type_ ?~ SwaggerString & format ?~ T.pack fmt | Format @"date"@ corresponds to @yyyy - mm - dd@ format . instance ToParamSchema Day where toParamSchema _ = timeParamSchema "date" -- | > > > toParamSchema ( Proxy : : ) ^. format Just " hh : : ss " instance ToParamSchema TimeOfDay where toParamSchema _ = timeParamSchema "hh:MM:ss" -- | > > > toParamSchema ( Proxy : : ) ^. format -- Just "yyyy-mm-ddThh:MM:ss" instance ToParamSchema LocalTime where toParamSchema _ = timeParamSchema "yyyy-mm-ddThh:MM:ss" -- | > > > toParamSchema ( Proxy : : Proxy ) ^. format -- Just "yyyy-mm-ddThh:MM:ss+hhMM" instance ToParamSchema ZonedTime where toParamSchema _ = timeParamSchema "yyyy-mm-ddThh:MM:ss+hhMM" -- | > > > toParamSchema ( Proxy : : Proxy UTCTime ) ^. format -- Just "yyyy-mm-ddThh:MM:ssZ" instance ToParamSchema UTCTime where toParamSchema _ = timeParamSchema "yyyy-mm-ddThh:MM:ssZ" instance ToParamSchema NominalDiffTime where toParamSchema _ = toParamSchema (Proxy :: Proxy Pico) instance ToParamSchema T.Text where toParamSchema _ = toParamSchema (Proxy :: Proxy String) instance ToParamSchema TL.Text where toParamSchema _ = toParamSchema (Proxy :: Proxy String) instance ToParamSchema Version where toParamSchema _ = mempty & type_ ?~ SwaggerString & pattern ?~ "^\\d+(\\.\\d+)*$" instance ToParamSchema SetCookie where toParamSchema _ = mempty & type_ ?~ SwaggerString type family ToParamSchemaByteStringError bs where ToParamSchemaByteStringError bs = TypeError ( 'Text "Impossible to have an instance " :<>: ShowType (ToParamSchema bs) :<>: Text "." :$$: 'Text "Please, use a newtype wrapper around " :<>: ShowType bs :<>: Text " instead." :$$: 'Text "Consider using byteParamSchema or binaryParamSchema templates." ) instance ToParamSchemaByteStringError BS.ByteString => ToParamSchema BS.ByteString where toParamSchema = error "impossible" instance ToParamSchemaByteStringError BSL.ByteString => ToParamSchema BSL.ByteString where toParamSchema = error "impossible" instance ToParamSchema All where toParamSchema _ = toParamSchema (Proxy :: Proxy Bool) instance ToParamSchema Any where toParamSchema _ = toParamSchema (Proxy :: Proxy Bool) instance ToParamSchema a => ToParamSchema (Sum a) where toParamSchema _ = toParamSchema (Proxy :: Proxy a) instance ToParamSchema a => ToParamSchema (Product a) where toParamSchema _ = toParamSchema (Proxy :: Proxy a) instance ToParamSchema a => ToParamSchema (First a) where toParamSchema _ = toParamSchema (Proxy :: Proxy a) instance ToParamSchema a => ToParamSchema (Last a) where toParamSchema _ = toParamSchema (Proxy :: Proxy a) instance ToParamSchema a => ToParamSchema (Dual a) where toParamSchema _ = toParamSchema (Proxy :: Proxy a) instance ToParamSchema a => ToParamSchema (Identity a) where toParamSchema _ = toParamSchema (Proxy :: Proxy a) instance ToParamSchema a => ToParamSchema [a] where toParamSchema _ = mempty & type_ ?~ SwaggerArray & items ?~ SwaggerItemsPrimitive Nothing (toParamSchema (Proxy :: Proxy a)) instance ToParamSchema a => ToParamSchema (V.Vector a) where toParamSchema _ = toParamSchema (Proxy :: Proxy [a]) instance ToParamSchema a => ToParamSchema (VP.Vector a) where toParamSchema _ = toParamSchema (Proxy :: Proxy [a]) instance ToParamSchema a => ToParamSchema (VS.Vector a) where toParamSchema _ = toParamSchema (Proxy :: Proxy [a]) instance ToParamSchema a => ToParamSchema (VU.Vector a) where toParamSchema _ = toParamSchema (Proxy :: Proxy [a]) instance ToParamSchema a => ToParamSchema (Set a) where toParamSchema _ = toParamSchema (Proxy :: Proxy [a]) & uniqueItems ?~ True instance ToParamSchema a => ToParamSchema (HashSet a) where toParamSchema _ = toParamSchema (Proxy :: Proxy (Set a)) -- | > > > encode $ toParamSchema ( Proxy : : Proxy ( ) ) -- "{\"enum\":[\"_\"],\"type\":\"string\"}" instance ToParamSchema () where toParamSchema _ = mempty & type_ ?~ SwaggerString & enum_ ?~ ["_"] instance ToParamSchema UUID where toParamSchema _ = mempty & type_ ?~ SwaggerString & format ?~ "uuid" | A configurable generic @'ParamSchema'@ creator . -- -- >>> :set -XDeriveGeneric > > > data Color = Red | Blue deriving Generic > > > encode $ genericToParamSchema defaultSchemaOptions ( Proxy : : Proxy Color ) -- "{\"enum\":[\"Red\",\"Blue\"],\"type\":\"string\"}" genericToParamSchema :: forall a t. (Generic a, GToParamSchema (Rep a)) => SchemaOptions -> Proxy a -> ParamSchema t genericToParamSchema opts _ = gtoParamSchema opts (Proxy :: Proxy (Rep a)) mempty class GToParamSchema (f :: * -> *) where gtoParamSchema :: SchemaOptions -> Proxy f -> ParamSchema t -> ParamSchema t instance GToParamSchema f => GToParamSchema (D1 d f) where gtoParamSchema opts _ = gtoParamSchema opts (Proxy :: Proxy f) instance Constructor c => GToParamSchema (C1 c U1) where gtoParamSchema = genumParamSchema instance GToParamSchema f => GToParamSchema (C1 c (S1 s f)) where gtoParamSchema opts _ = gtoParamSchema opts (Proxy :: Proxy f) instance ToParamSchema c => GToParamSchema (K1 i c) where gtoParamSchema _ _ _ = toParamSchema (Proxy :: Proxy c) instance (GEnumParamSchema f, GEnumParamSchema g) => GToParamSchema (f :+: g) where gtoParamSchema opts _ = genumParamSchema opts (Proxy :: Proxy (f :+: g)) class GEnumParamSchema (f :: * -> *) where genumParamSchema :: SchemaOptions -> Proxy f -> ParamSchema t -> ParamSchema t instance (GEnumParamSchema f, GEnumParamSchema g) => GEnumParamSchema (f :+: g) where genumParamSchema opts _ = genumParamSchema opts (Proxy :: Proxy f) . genumParamSchema opts (Proxy :: Proxy g) instance Constructor c => GEnumParamSchema (C1 c U1) where genumParamSchema opts _ s = s & type_ ?~ SwaggerString & enum_ %~ addEnumValue tag where tag = toJSON (constructorTagModifier opts (conName (Proxy3 :: Proxy3 c f p))) addEnumValue x Nothing = Just [x] addEnumValue x (Just xs) = Just (x:xs) data Proxy3 a b c = Proxy3 -- $setup > > > import Data . Aeson ( encode )
null
https://raw.githubusercontent.com/GetShopTV/swagger2/9846955d72e7242f3c1fa982911972cd9e4eb720/src/Data/Swagger/Internal/ParamSchema.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE PackageImports # # LANGUAGE TypeSynonymInstances # # OPTIONS_GHC -Wno-redundant-constraints # | Default schema for binary data (any sequence of octets). | Default schema for binary data (base64 encoded). | Default schema for password string. @"password"@ format is used to hint UIs the input needs to be obscured. | Convert a type into a plain @'ParamSchema'@. An example type and instance: @ allows to write ' T.Text ' literals data Direction = Up | Down & type_ ?~ SwaggerString & enum_ ?~ [ \"Up\", \"Down\" ] @ Instead of manually writing your @'ToParamSchema'@ instance you can and declare a @'ToParamSchema'@ instance for your datatype without For instance, the previous example can be simplified into this: @ @ | Convert a type into a plain parameter schema. "{\"type\":\"integer\"}" # OVERLAPPING # | Default plain schema for @'Bounded'@, @'Integral'@ types. >>> encode $ toParamSchemaBoundedIntegral (Proxy :: Proxy Int8) "{\"maximum\":127,\"minimum\":-128,\"type\":\"integer\"}" | | Just "yyyy-mm-ddThh:MM:ss" | Just "yyyy-mm-ddThh:MM:ss+hhMM" | Just "yyyy-mm-ddThh:MM:ssZ" | "{\"enum\":[\"_\"],\"type\":\"string\"}" >>> :set -XDeriveGeneric "{\"enum\":[\"Red\",\"Blue\"],\"type\":\"string\"}" $setup
# LANGUAGE DataKinds # # LANGUAGE DefaultSignatures # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE KindSignatures # # LANGUAGE PolyKinds # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE UndecidableInstances # Generic a is redundant in ToParamSchema a default imple For TypeErrors # OPTIONS_GHC -Wno - unticked - promoted - constructors # module Data.Swagger.Internal.ParamSchema where import Control.Lens import Data.Aeson (ToJSON (..)) import Data.Proxy import GHC.Generics import Data.Int import "unordered-containers" Data.HashSet (HashSet) import Data.Monoid import Data.Set (Set) import Data.Scientific import Data.Fixed (HasResolution(..), Fixed, Pico) import qualified Data.Text as T import qualified Data.Text.Lazy as TL import Data.Time import qualified Data.Vector as V import qualified Data.Vector.Primitive as VP import qualified Data.Vector.Storable as VS import qualified Data.Vector.Unboxed as VU import Data.Version (Version) import Numeric.Natural.Compat (Natural) import Data.Word import Data.UUID.Types (UUID) import Web.Cookie (SetCookie) import Data.Swagger.Internal import Data.Swagger.Lens import Data.Swagger.SchemaOptions import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as BSL import GHC.TypeLits (TypeError, ErrorMessage(..)) binaryParamSchema :: ParamSchema t binaryParamSchema = mempty & type_ ?~ SwaggerString & format ?~ "binary" byteParamSchema :: ParamSchema t byteParamSchema = mempty & type_ ?~ SwaggerString & format ?~ "byte" passwordParamSchema :: ParamSchema t passwordParamSchema = mempty & type_ ?~ SwaggerString & format ?~ "password" import Control . Lens instance ToParamSchema Direction where toParamSchema _ = use a default generic implementation of @'toParamSchema'@. To do that , simply add @deriving ' Generic'@ clause to your datatype giving definition for @'toParamSchema'@. { -\ # LANGUAGE DeriveGeneric \#- } import ( Generic ) data Direction = Up | Down deriving Generic instance ToParamSchema Direction class ToParamSchema a where > > > encode $ toParamSchema ( Proxy : : Proxy Integer ) toParamSchema :: Proxy a -> ParamSchema t default toParamSchema :: (Generic a, GToParamSchema (Rep a)) => Proxy a -> ParamSchema t toParamSchema = genericToParamSchema defaultSchemaOptions toParamSchema _ = mempty & type_ ?~ SwaggerString instance ToParamSchema Bool where toParamSchema _ = mempty & type_ ?~ SwaggerBoolean instance ToParamSchema Integer where toParamSchema _ = mempty & type_ ?~ SwaggerInteger instance ToParamSchema Natural where toParamSchema _ = mempty & type_ ?~ SwaggerInteger & minimum_ ?~ 0 & exclusiveMinimum ?~ False instance ToParamSchema Int where toParamSchema = toParamSchemaBoundedIntegral instance ToParamSchema Int8 where toParamSchema = toParamSchemaBoundedIntegral instance ToParamSchema Int16 where toParamSchema = toParamSchemaBoundedIntegral instance ToParamSchema Int32 where toParamSchema proxy = toParamSchemaBoundedIntegral proxy & format ?~ "int32" instance ToParamSchema Int64 where toParamSchema proxy = toParamSchemaBoundedIntegral proxy & format ?~ "int64" instance ToParamSchema Word where toParamSchema = toParamSchemaBoundedIntegral instance ToParamSchema Word8 where toParamSchema = toParamSchemaBoundedIntegral instance ToParamSchema Word16 where toParamSchema = toParamSchemaBoundedIntegral instance ToParamSchema Word32 where toParamSchema proxy = toParamSchemaBoundedIntegral proxy & format ?~ "int32" instance ToParamSchema Word64 where toParamSchema proxy = toParamSchemaBoundedIntegral proxy & format ?~ "int64" toParamSchemaBoundedIntegral :: forall a t. (Bounded a, Integral a) => Proxy a -> ParamSchema t toParamSchemaBoundedIntegral _ = mempty & type_ ?~ SwaggerInteger & minimum_ ?~ fromInteger (toInteger (minBound :: a)) & maximum_ ?~ fromInteger (toInteger (maxBound :: a)) instance ToParamSchema Char where toParamSchema _ = mempty & type_ ?~ SwaggerString & maxLength ?~ 1 & minLength ?~ 1 instance ToParamSchema Scientific where toParamSchema _ = mempty & type_ ?~ SwaggerNumber instance HasResolution a => ToParamSchema (Fixed a) where toParamSchema _ = mempty & type_ ?~ SwaggerNumber & multipleOf ?~ (recip . fromInteger $ resolution (Proxy :: Proxy a)) instance ToParamSchema Double where toParamSchema _ = mempty & type_ ?~ SwaggerNumber & format ?~ "double" instance ToParamSchema Float where toParamSchema _ = mempty & type_ ?~ SwaggerNumber & format ?~ "float" timeParamSchema :: String -> ParamSchema t timeParamSchema fmt = mempty & type_ ?~ SwaggerString & format ?~ T.pack fmt | Format @"date"@ corresponds to @yyyy - mm - dd@ format . instance ToParamSchema Day where toParamSchema _ = timeParamSchema "date" > > > toParamSchema ( Proxy : : ) ^. format Just " hh : : ss " instance ToParamSchema TimeOfDay where toParamSchema _ = timeParamSchema "hh:MM:ss" > > > toParamSchema ( Proxy : : ) ^. format instance ToParamSchema LocalTime where toParamSchema _ = timeParamSchema "yyyy-mm-ddThh:MM:ss" > > > toParamSchema ( Proxy : : Proxy ) ^. format instance ToParamSchema ZonedTime where toParamSchema _ = timeParamSchema "yyyy-mm-ddThh:MM:ss+hhMM" > > > toParamSchema ( Proxy : : Proxy UTCTime ) ^. format instance ToParamSchema UTCTime where toParamSchema _ = timeParamSchema "yyyy-mm-ddThh:MM:ssZ" instance ToParamSchema NominalDiffTime where toParamSchema _ = toParamSchema (Proxy :: Proxy Pico) instance ToParamSchema T.Text where toParamSchema _ = toParamSchema (Proxy :: Proxy String) instance ToParamSchema TL.Text where toParamSchema _ = toParamSchema (Proxy :: Proxy String) instance ToParamSchema Version where toParamSchema _ = mempty & type_ ?~ SwaggerString & pattern ?~ "^\\d+(\\.\\d+)*$" instance ToParamSchema SetCookie where toParamSchema _ = mempty & type_ ?~ SwaggerString type family ToParamSchemaByteStringError bs where ToParamSchemaByteStringError bs = TypeError ( 'Text "Impossible to have an instance " :<>: ShowType (ToParamSchema bs) :<>: Text "." :$$: 'Text "Please, use a newtype wrapper around " :<>: ShowType bs :<>: Text " instead." :$$: 'Text "Consider using byteParamSchema or binaryParamSchema templates." ) instance ToParamSchemaByteStringError BS.ByteString => ToParamSchema BS.ByteString where toParamSchema = error "impossible" instance ToParamSchemaByteStringError BSL.ByteString => ToParamSchema BSL.ByteString where toParamSchema = error "impossible" instance ToParamSchema All where toParamSchema _ = toParamSchema (Proxy :: Proxy Bool) instance ToParamSchema Any where toParamSchema _ = toParamSchema (Proxy :: Proxy Bool) instance ToParamSchema a => ToParamSchema (Sum a) where toParamSchema _ = toParamSchema (Proxy :: Proxy a) instance ToParamSchema a => ToParamSchema (Product a) where toParamSchema _ = toParamSchema (Proxy :: Proxy a) instance ToParamSchema a => ToParamSchema (First a) where toParamSchema _ = toParamSchema (Proxy :: Proxy a) instance ToParamSchema a => ToParamSchema (Last a) where toParamSchema _ = toParamSchema (Proxy :: Proxy a) instance ToParamSchema a => ToParamSchema (Dual a) where toParamSchema _ = toParamSchema (Proxy :: Proxy a) instance ToParamSchema a => ToParamSchema (Identity a) where toParamSchema _ = toParamSchema (Proxy :: Proxy a) instance ToParamSchema a => ToParamSchema [a] where toParamSchema _ = mempty & type_ ?~ SwaggerArray & items ?~ SwaggerItemsPrimitive Nothing (toParamSchema (Proxy :: Proxy a)) instance ToParamSchema a => ToParamSchema (V.Vector a) where toParamSchema _ = toParamSchema (Proxy :: Proxy [a]) instance ToParamSchema a => ToParamSchema (VP.Vector a) where toParamSchema _ = toParamSchema (Proxy :: Proxy [a]) instance ToParamSchema a => ToParamSchema (VS.Vector a) where toParamSchema _ = toParamSchema (Proxy :: Proxy [a]) instance ToParamSchema a => ToParamSchema (VU.Vector a) where toParamSchema _ = toParamSchema (Proxy :: Proxy [a]) instance ToParamSchema a => ToParamSchema (Set a) where toParamSchema _ = toParamSchema (Proxy :: Proxy [a]) & uniqueItems ?~ True instance ToParamSchema a => ToParamSchema (HashSet a) where toParamSchema _ = toParamSchema (Proxy :: Proxy (Set a)) > > > encode $ toParamSchema ( Proxy : : Proxy ( ) ) instance ToParamSchema () where toParamSchema _ = mempty & type_ ?~ SwaggerString & enum_ ?~ ["_"] instance ToParamSchema UUID where toParamSchema _ = mempty & type_ ?~ SwaggerString & format ?~ "uuid" | A configurable generic @'ParamSchema'@ creator . > > > data Color = Red | Blue deriving Generic > > > encode $ genericToParamSchema defaultSchemaOptions ( Proxy : : Proxy Color ) genericToParamSchema :: forall a t. (Generic a, GToParamSchema (Rep a)) => SchemaOptions -> Proxy a -> ParamSchema t genericToParamSchema opts _ = gtoParamSchema opts (Proxy :: Proxy (Rep a)) mempty class GToParamSchema (f :: * -> *) where gtoParamSchema :: SchemaOptions -> Proxy f -> ParamSchema t -> ParamSchema t instance GToParamSchema f => GToParamSchema (D1 d f) where gtoParamSchema opts _ = gtoParamSchema opts (Proxy :: Proxy f) instance Constructor c => GToParamSchema (C1 c U1) where gtoParamSchema = genumParamSchema instance GToParamSchema f => GToParamSchema (C1 c (S1 s f)) where gtoParamSchema opts _ = gtoParamSchema opts (Proxy :: Proxy f) instance ToParamSchema c => GToParamSchema (K1 i c) where gtoParamSchema _ _ _ = toParamSchema (Proxy :: Proxy c) instance (GEnumParamSchema f, GEnumParamSchema g) => GToParamSchema (f :+: g) where gtoParamSchema opts _ = genumParamSchema opts (Proxy :: Proxy (f :+: g)) class GEnumParamSchema (f :: * -> *) where genumParamSchema :: SchemaOptions -> Proxy f -> ParamSchema t -> ParamSchema t instance (GEnumParamSchema f, GEnumParamSchema g) => GEnumParamSchema (f :+: g) where genumParamSchema opts _ = genumParamSchema opts (Proxy :: Proxy f) . genumParamSchema opts (Proxy :: Proxy g) instance Constructor c => GEnumParamSchema (C1 c U1) where genumParamSchema opts _ s = s & type_ ?~ SwaggerString & enum_ %~ addEnumValue tag where tag = toJSON (constructorTagModifier opts (conName (Proxy3 :: Proxy3 c f p))) addEnumValue x Nothing = Just [x] addEnumValue x (Just xs) = Just (x:xs) data Proxy3 a b c = Proxy3 > > > import Data . Aeson ( encode )
2f246d6332b10d01198e2613c2fe669b3d21981393b15b5a9c71f2bd109b8005
falgon/htcc
Scope.hs
| Module : Htcc . . ConstructionData . Scope Description : The Data type of scope and its utilities used in parsing Copyright : ( c ) roki , 2019 License : MIT Maintainer : Stability : experimental Portability : POSIX The Data type of variables and its utilities used in parsing Module : Htcc.Parser.ConstructionData.Scope Description : The Data type of scope and its utilities used in parsing Copyright : (c) roki, 2019 License : MIT Maintainer : Stability : experimental Portability : POSIX The Data type of variables and its utilities used in parsing -} # LANGUAGE DeriveGeneric # module Htcc.Parser.ConstructionData.Scope ( -- * The types Scoped (..), LookupVarResult (..), -- * Operations for scope addLVar, addGVar, addGVarWith, addLiteral, addTag, addTypedef, addFunction, addEnumerator, succNest, fallBack, lookupLVar, lookupGVar, lookupVar, lookupTag, lookupTypedef, lookupFunction, lookupEnumerator, initScope, resetLocal ) where import Control.DeepSeq (NFData (..)) import Data.Bits (Bits (..)) import qualified Data.Text as T import Data.Tuple.Extra (second) import GHC.Generics (Generic (..), Generic1 (..)) import Numeric.Natural import qualified Htcc.CRules.Types as CT import Htcc.Parser.AST.Core (ATree (..)) import qualified Htcc.Parser.ConstructionData.Scope.Enumerator as SE import qualified Htcc.Parser.ConstructionData.Scope.Function as PF import qualified Htcc.Parser.ConstructionData.Scope.ManagedScope as SM import qualified Htcc.Parser.ConstructionData.Scope.Tag as PS import qualified Htcc.Parser.ConstructionData.Scope.Typedef as PT import qualified Htcc.Parser.ConstructionData.Scope.Var as PV import qualified Htcc.Tokenizer.Token as HT -- | The data type of a struct tag data Scoped i = Scoped -- ^ The constructor of a struct tag { curNestDepth :: !Natural, -- ^ The nest depth of the parsing process vars :: PV.Vars i, -- ^ scoped all identifiers of variables (local variables, global variables and literals) visible during processing structs :: PS.Tags i, -- ^ scoped all struct tags typedefs :: PT.Typedefs i, -- ^ scoped all typedefs functions :: PF.Functions i, -- ^ scoped all identifires of functions enumerators :: SE.Enumerators i -- ^ scoped all identifiers of enumerators } deriving (Show, Generic, Generic1) instance NFData i => NFData (Scoped i) -- | A type that represents the result of a variable search data LookupVarResult i = FoundGVar (PV.GVar i) -- ^ A type constructor indicating that a global variable has been found | FoundLVar (PV.LVar i) -- ^ A type constructor indicating that a local variable has been found | FoundEnum (SE.Enumerator i) -- ^ A type constructor indicating that a enumerator has been found | NotFound -- ^ A type constructor indicating that it was not found deriving (Show, Eq) # INLINE applyVars # applyVars :: Scoped i -> (a, PV.Vars i) -> (a, Scoped i) applyVars sc = second (\x -> sc { vars = x }) # INLINE addVar # addVar :: (Integral i, Bits i) => (CT.StorageClass i -> HT.TokenLC i -> PV.Vars i -> Either (T.Text, HT.TokenLC i) (ATree i, PV.Vars i)) -> CT.StorageClass i -> HT.TokenLC i -> Scoped i -> Either (SM.ASTError i) (ATree i, Scoped i) addVar f ty tkn sc = applyVars sc <$> f ty tkn (vars sc) -- | `addLVar` has a scoped type argument and is the same function as `PV.addLVar` internally. # INLINE addLVar # addLVar :: (Integral i, Bits i) => CT.StorageClass i -> HT.TokenLC i -> Scoped i -> Either (SM.ASTError i) (ATree i, Scoped i) addLVar ty tkn scp = addVar (PV.addLVar $ curNestDepth scp) ty tkn scp | ` addGVar ` has a scoped type argument and is the same function as ` PV.addGVar ` internally . # INLINE addGVar # addGVar :: (Integral i, Bits i) => CT.StorageClass i -> HT.TokenLC i -> Scoped i -> Either (SM.ASTError i) (ATree i, Scoped i) addGVar = addVar PV.addGVar -- | `addGVarWith` has a scoped type argument and is the same function as `PV.addLiteral` internally. # INLINE addGVarWith # addGVarWith :: (Integral i, Bits i) => CT.StorageClass i -> HT.TokenLC i -> PV.GVarInitWith i -> Scoped i -> Either (SM.ASTError i) (ATree i, Scoped i) addGVarWith ty tkn iw sc = applyVars sc <$> PV.addGVarWith ty tkn iw (vars sc) -- | `addLiteral` has a scoped type argument and is the same function as `PV.addLiteral` internally. {-# INLINE addLiteral #-} addLiteral :: (Integral i, Bits i) => CT.StorageClass i -> HT.TokenLC i -> Scoped i -> Either (SM.ASTError i) (ATree i, Scoped i) addLiteral = addVar PV.addLiteral -- | `succNest` has a scoped type argument and is the same function as `PV.succNest` internally. # INLINE succNest # succNest :: Scoped i -> Scoped i succNest sc = sc { curNestDepth = succ $ curNestDepth sc } -- | `fallBack` has a scoped type argument and is the same function as `PV.fallBack` internally. {-# INLINE fallBack #-} fallBack :: Scoped i -> Scoped i -> Scoped i fallBack pre post = pre { vars = PV.fallBack (vars pre) (vars post), structs = SM.fallBack (structs pre) (structs post), typedefs = SM.fallBack (typedefs pre) (typedefs post), functions = SM.fallBack (functions pre) (functions post), enumerators = SM.fallBack (enumerators pre) (enumerators post) } {-# INLINE lookupVar' #-} lookupVar' :: (T.Text -> PV.Vars a -> b) -> T.Text -> Scoped a -> b lookupVar' f s sc = f s $ vars sc | ` lookupLVar ` has a scoped type argument and is the same function as ` PV.lookupLVar ` internally . # INLINE lookupLVar # lookupLVar :: T.Text -> Scoped i -> Maybe (PV.LVar i) lookupLVar = lookupVar' PV.lookupLVar -- | `lookupGVar` has a scoped type argument and is the same function as `PV.lookupGVar` internally. # INLINE lookupGVar # lookupGVar :: T.Text -> Scoped i -> Maybe (PV.GVar i) lookupGVar = lookupVar' PV.lookupGVar -- | `lookupVar` has a scoped type argument and is the same function as `PV.lookupVar` internally. # INLINE lookupVar # lookupVar :: T.Text -> Scoped i -> LookupVarResult i lookupVar ident scp = case lookupLVar ident scp of Just local -> FoundLVar local _ -> case lookupEnumerator ident scp of Just enum -> FoundEnum enum _ -> maybe NotFound FoundGVar $ lookupGVar ident scp | ` lookupTag ` has a scoped type argument and is the same function as ` PS.lookupTag ` internally . # INLINE lookupTag # lookupTag :: T.Text -> Scoped i -> Maybe (PS.Tag i) lookupTag t sc = SM.lookup t $ structs sc -- | `lookupTypedef` has a scoped type argument and is the same function as `PT.lookupTypedef` internally. # INLINE lookupTypedef # lookupTypedef :: T.Text -> Scoped i -> Maybe (PT.Typedef i) lookupTypedef t sc = SM.lookup t $ typedefs sc -- | `lookupFunction` has a scoped type argument and is the same function as `PF.lookupFunction` internally. # INLINE lookupFunction # lookupFunction :: T.Text -> Scoped i -> Maybe (PF.Function i) lookupFunction t sc = SM.lookup t $ functions sc {-# INLINE lookupEnumerator #-} -- | `lookupEnumerator` has a scoped type argument and is the same function as `PF.lookupFunction` internally. lookupEnumerator :: T.Text -> Scoped i -> Maybe (SE.Enumerator i) lookupEnumerator t sc = SM.lookup t $ enumerators sc -- | `addTag` has a scoped type argument and is the same function as `PS.add` internally. # INLINE addTag # addTag :: Num i => CT.StorageClass i -> HT.TokenLC i -> Scoped i -> Either (SM.ASTError i) (Scoped i) addTag ty tkn sc = (\x -> sc { structs = x }) <$> PS.add (curNestDepth sc) ty tkn (structs sc) -- | `addTypedef` has a scoped type argument and is the same function as `PT.add` internally. # INLINE addTypedef # addTypedef :: (Eq i, Num i) => CT.StorageClass i -> HT.TokenLC i -> Scoped i -> Either (SM.ASTError i) (Scoped i) addTypedef ty tkn sc = (\x -> sc { typedefs = x }) <$> PT.add (curNestDepth sc) ty tkn (typedefs sc) -- | `addFunction` has a scoped type argument and is the same function as `PT.add` internally. # INLINE addFunction # addFunction :: Num i => Bool -> CT.StorageClass i -> HT.TokenLC i -> Scoped i -> Either (SM.ASTError i) (Scoped i) addFunction fd ty tkn sc = (\x -> sc { functions = x }) <$> PF.add fd ty tkn (functions sc) | ` addEnumerator ` has a scoped type argument and is the same function as ` SE.add ` internally . # INLINE addEnumerator # addEnumerator :: Num i => CT.StorageClass i -> HT.TokenLC i -> i -> Scoped i -> Either (SM.ASTError i) (Scoped i) addEnumerator ty tkn val sc = (\x -> sc { enumerators = x }) <$> SE.add ty tkn val (enumerators sc) # INLINE initScope # -- | Helper function representing an empty scoped data initScope :: Scoped i initScope = Scoped 0 PV.initVars SM.initial SM.initial SM.initial SM.initial # INLINE resetLocal # -- | `resetLocal` has a scoped type argument and is the same function as `PV.resetLocal` internally. resetLocal :: Scoped i -> Scoped i resetLocal sc = sc { vars = PV.resetLocal (vars sc) }
null
https://raw.githubusercontent.com/falgon/htcc/3cef6fc362b00d4bc0ae261cba567bfd9c69b3c5/src/Htcc/Parser/ConstructionData/Scope.hs
haskell
* The types * Operations for scope | The data type of a struct tag ^ The constructor of a struct tag ^ The nest depth of the parsing process ^ scoped all identifiers of variables (local variables, global variables and literals) visible during processing ^ scoped all struct tags ^ scoped all typedefs ^ scoped all identifires of functions ^ scoped all identifiers of enumerators | A type that represents the result of a variable search ^ A type constructor indicating that a global variable has been found ^ A type constructor indicating that a local variable has been found ^ A type constructor indicating that a enumerator has been found ^ A type constructor indicating that it was not found | `addLVar` has a scoped type argument and is the same function as `PV.addLVar` internally. | `addGVarWith` has a scoped type argument and is the same function as `PV.addLiteral` internally. | `addLiteral` has a scoped type argument and is the same function as `PV.addLiteral` internally. # INLINE addLiteral # | `succNest` has a scoped type argument and is the same function as `PV.succNest` internally. | `fallBack` has a scoped type argument and is the same function as `PV.fallBack` internally. # INLINE fallBack # # INLINE lookupVar' # | `lookupGVar` has a scoped type argument and is the same function as `PV.lookupGVar` internally. | `lookupVar` has a scoped type argument and is the same function as `PV.lookupVar` internally. | `lookupTypedef` has a scoped type argument and is the same function as `PT.lookupTypedef` internally. | `lookupFunction` has a scoped type argument and is the same function as `PF.lookupFunction` internally. # INLINE lookupEnumerator # | `lookupEnumerator` has a scoped type argument and is the same function as `PF.lookupFunction` internally. | `addTag` has a scoped type argument and is the same function as `PS.add` internally. | `addTypedef` has a scoped type argument and is the same function as `PT.add` internally. | `addFunction` has a scoped type argument and is the same function as `PT.add` internally. | Helper function representing an empty scoped data | `resetLocal` has a scoped type argument and is the same function as `PV.resetLocal` internally.
| Module : Htcc . . ConstructionData . Scope Description : The Data type of scope and its utilities used in parsing Copyright : ( c ) roki , 2019 License : MIT Maintainer : Stability : experimental Portability : POSIX The Data type of variables and its utilities used in parsing Module : Htcc.Parser.ConstructionData.Scope Description : The Data type of scope and its utilities used in parsing Copyright : (c) roki, 2019 License : MIT Maintainer : Stability : experimental Portability : POSIX The Data type of variables and its utilities used in parsing -} # LANGUAGE DeriveGeneric # module Htcc.Parser.ConstructionData.Scope ( Scoped (..), LookupVarResult (..), addLVar, addGVar, addGVarWith, addLiteral, addTag, addTypedef, addFunction, addEnumerator, succNest, fallBack, lookupLVar, lookupGVar, lookupVar, lookupTag, lookupTypedef, lookupFunction, lookupEnumerator, initScope, resetLocal ) where import Control.DeepSeq (NFData (..)) import Data.Bits (Bits (..)) import qualified Data.Text as T import Data.Tuple.Extra (second) import GHC.Generics (Generic (..), Generic1 (..)) import Numeric.Natural import qualified Htcc.CRules.Types as CT import Htcc.Parser.AST.Core (ATree (..)) import qualified Htcc.Parser.ConstructionData.Scope.Enumerator as SE import qualified Htcc.Parser.ConstructionData.Scope.Function as PF import qualified Htcc.Parser.ConstructionData.Scope.ManagedScope as SM import qualified Htcc.Parser.ConstructionData.Scope.Tag as PS import qualified Htcc.Parser.ConstructionData.Scope.Typedef as PT import qualified Htcc.Parser.ConstructionData.Scope.Var as PV import qualified Htcc.Tokenizer.Token as HT { } deriving (Show, Generic, Generic1) instance NFData i => NFData (Scoped i) deriving (Show, Eq) # INLINE applyVars # applyVars :: Scoped i -> (a, PV.Vars i) -> (a, Scoped i) applyVars sc = second (\x -> sc { vars = x }) # INLINE addVar # addVar :: (Integral i, Bits i) => (CT.StorageClass i -> HT.TokenLC i -> PV.Vars i -> Either (T.Text, HT.TokenLC i) (ATree i, PV.Vars i)) -> CT.StorageClass i -> HT.TokenLC i -> Scoped i -> Either (SM.ASTError i) (ATree i, Scoped i) addVar f ty tkn sc = applyVars sc <$> f ty tkn (vars sc) # INLINE addLVar # addLVar :: (Integral i, Bits i) => CT.StorageClass i -> HT.TokenLC i -> Scoped i -> Either (SM.ASTError i) (ATree i, Scoped i) addLVar ty tkn scp = addVar (PV.addLVar $ curNestDepth scp) ty tkn scp | ` addGVar ` has a scoped type argument and is the same function as ` PV.addGVar ` internally . # INLINE addGVar # addGVar :: (Integral i, Bits i) => CT.StorageClass i -> HT.TokenLC i -> Scoped i -> Either (SM.ASTError i) (ATree i, Scoped i) addGVar = addVar PV.addGVar # INLINE addGVarWith # addGVarWith :: (Integral i, Bits i) => CT.StorageClass i -> HT.TokenLC i -> PV.GVarInitWith i -> Scoped i -> Either (SM.ASTError i) (ATree i, Scoped i) addGVarWith ty tkn iw sc = applyVars sc <$> PV.addGVarWith ty tkn iw (vars sc) addLiteral :: (Integral i, Bits i) => CT.StorageClass i -> HT.TokenLC i -> Scoped i -> Either (SM.ASTError i) (ATree i, Scoped i) addLiteral = addVar PV.addLiteral # INLINE succNest # succNest :: Scoped i -> Scoped i succNest sc = sc { curNestDepth = succ $ curNestDepth sc } fallBack :: Scoped i -> Scoped i -> Scoped i fallBack pre post = pre { vars = PV.fallBack (vars pre) (vars post), structs = SM.fallBack (structs pre) (structs post), typedefs = SM.fallBack (typedefs pre) (typedefs post), functions = SM.fallBack (functions pre) (functions post), enumerators = SM.fallBack (enumerators pre) (enumerators post) } lookupVar' :: (T.Text -> PV.Vars a -> b) -> T.Text -> Scoped a -> b lookupVar' f s sc = f s $ vars sc | ` lookupLVar ` has a scoped type argument and is the same function as ` PV.lookupLVar ` internally . # INLINE lookupLVar # lookupLVar :: T.Text -> Scoped i -> Maybe (PV.LVar i) lookupLVar = lookupVar' PV.lookupLVar # INLINE lookupGVar # lookupGVar :: T.Text -> Scoped i -> Maybe (PV.GVar i) lookupGVar = lookupVar' PV.lookupGVar # INLINE lookupVar # lookupVar :: T.Text -> Scoped i -> LookupVarResult i lookupVar ident scp = case lookupLVar ident scp of Just local -> FoundLVar local _ -> case lookupEnumerator ident scp of Just enum -> FoundEnum enum _ -> maybe NotFound FoundGVar $ lookupGVar ident scp | ` lookupTag ` has a scoped type argument and is the same function as ` PS.lookupTag ` internally . # INLINE lookupTag # lookupTag :: T.Text -> Scoped i -> Maybe (PS.Tag i) lookupTag t sc = SM.lookup t $ structs sc # INLINE lookupTypedef # lookupTypedef :: T.Text -> Scoped i -> Maybe (PT.Typedef i) lookupTypedef t sc = SM.lookup t $ typedefs sc # INLINE lookupFunction # lookupFunction :: T.Text -> Scoped i -> Maybe (PF.Function i) lookupFunction t sc = SM.lookup t $ functions sc lookupEnumerator :: T.Text -> Scoped i -> Maybe (SE.Enumerator i) lookupEnumerator t sc = SM.lookup t $ enumerators sc # INLINE addTag # addTag :: Num i => CT.StorageClass i -> HT.TokenLC i -> Scoped i -> Either (SM.ASTError i) (Scoped i) addTag ty tkn sc = (\x -> sc { structs = x }) <$> PS.add (curNestDepth sc) ty tkn (structs sc) # INLINE addTypedef # addTypedef :: (Eq i, Num i) => CT.StorageClass i -> HT.TokenLC i -> Scoped i -> Either (SM.ASTError i) (Scoped i) addTypedef ty tkn sc = (\x -> sc { typedefs = x }) <$> PT.add (curNestDepth sc) ty tkn (typedefs sc) # INLINE addFunction # addFunction :: Num i => Bool -> CT.StorageClass i -> HT.TokenLC i -> Scoped i -> Either (SM.ASTError i) (Scoped i) addFunction fd ty tkn sc = (\x -> sc { functions = x }) <$> PF.add fd ty tkn (functions sc) | ` addEnumerator ` has a scoped type argument and is the same function as ` SE.add ` internally . # INLINE addEnumerator # addEnumerator :: Num i => CT.StorageClass i -> HT.TokenLC i -> i -> Scoped i -> Either (SM.ASTError i) (Scoped i) addEnumerator ty tkn val sc = (\x -> sc { enumerators = x }) <$> SE.add ty tkn val (enumerators sc) # INLINE initScope # initScope :: Scoped i initScope = Scoped 0 PV.initVars SM.initial SM.initial SM.initial SM.initial # INLINE resetLocal # resetLocal :: Scoped i -> Scoped i resetLocal sc = sc { vars = PV.resetLocal (vars sc) }
a55edb97f11c69f4fb79048204b73ac9c0273070582cb3ddc198eab811657c87
expipiplus1/spir-v
Extra.hs
module Data.Maybe.Extra ( module Data.Maybe , rightToMaybe ) where import Data.Maybe rightToMaybe :: Either t a -> Maybe a rightToMaybe (Right x) = Just x rightToMaybe (Left _) = Nothing
null
https://raw.githubusercontent.com/expipiplus1/spir-v/5692404f43a63fb8feb0cfaff3bfb3eedada6890/generate/src/Data/Maybe/Extra.hs
haskell
module Data.Maybe.Extra ( module Data.Maybe , rightToMaybe ) where import Data.Maybe rightToMaybe :: Either t a -> Maybe a rightToMaybe (Right x) = Just x rightToMaybe (Left _) = Nothing
db3bf3000d94131d181b15a63558270b6534fb31ee09ce43faaa228302b45e58
basho/riak_kv
riak_kv_fold_buffer.erl
%% ------------------------------------------------------------------- %% %% riak_kv_fold_buffer: Provide operations for creating and using %% size-limited buffers for use in folds.n %% Copyright ( c ) 2007 - 2011 Basho Technologies , Inc. All Rights Reserved . %% This file is provided to you under the Apache License , %% Version 2.0 (the "License"); you may not use this file except in compliance with the License . You may obtain %% a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY %% KIND, either express or implied. See the License for the %% specific language governing permissions and limitations %% under the License. %% %% ------------------------------------------------------------------- %% @doc Provide operations for creating and using %% size-limited buffers for use in folds. -module(riak_kv_fold_buffer). %% Public API -export([new/2, add/2, flush/1, size/1]). -export_type([buffer/0]). -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). -endif. -record(buffer, {acc=[] :: [any()], buffer_fun :: function(), max_size :: pos_integer(), size=0 :: non_neg_integer()}). -type buffer() :: #buffer{}. %% =================================================================== %% Public API %% =================================================================== %% @doc Returns a new buffer with the specified %% maximum size and buffer function. -spec new(pos_integer(), fun(([any()]) -> any())) -> buffer(). new(MaxSize, Fun) -> #buffer{buffer_fun=Fun, max_size=MaxSize-1}. %% @doc Add an item to the buffer. If the %% size of the buffer is equal to the %% maximum size of this buffer then %% the buffer function is called on %% the accumlated buffer items and %% then the buffer is emptied. -spec add(any(), buffer()) -> buffer(). add(Item, #buffer{acc=Acc, buffer_fun=Fun, max_size=MaxSize, size=MaxSize}=Buffer) -> Fun([Item | Acc]), Buffer#buffer{acc=[], size=0}; add(Item, #buffer{acc=Acc, size=Size}=Buffer) -> Buffer#buffer{acc=[Item | Acc], size=Size+1}. %% @doc Call the buffer function on the %% remaining items and then reset the buffer. -spec flush(buffer()) -> buffer(). flush(#buffer{acc=Acc, buffer_fun=Fun}=Buffer) -> Fun(Acc), Buffer#buffer{acc=[], size=0}. %% @doc Returns the size of the buffer. -spec size(buffer()) -> non_neg_integer(). size(#buffer{size=Size}) -> Size. %% =================================================================== EUnit tests %% =================================================================== -ifdef(TEST). fold_buffer_test_() -> Fun = fun(_) -> true end, Buffer = new(5, Fun), Buffer1 = add(1, Buffer), Buffer2 = add(2, Buffer1), Buffer3 = add(3, Buffer2), Buffer4 = add(4, Buffer3), Buffer5 = add(5, Buffer4), {spawn, [ ?_assertEqual(#buffer{acc=[1], buffer_fun=Fun, max_size=4, size=1}, Buffer1), ?_assertEqual(#buffer{acc=[2,1], buffer_fun=Fun, max_size=4, size=2}, Buffer2), ?_assertEqual(#buffer{acc=[3,2,1], buffer_fun=Fun, max_size=4, size=3}, Buffer3), ?_assertEqual(#buffer{acc=[4,3,2,1], buffer_fun=Fun, max_size=4, size=4}, Buffer4), ?_assertEqual(#buffer{acc=[], buffer_fun=Fun, max_size=4, size=0}, Buffer5), ?_assertEqual(Buffer5#buffer{acc=[], size=0}, flush(Buffer5)), ?_assertEqual(0, ?MODULE:size(Buffer)), ?_assertEqual(1, ?MODULE:size(Buffer1)), ?_assertEqual(2, ?MODULE:size(Buffer2)), ?_assertEqual(3, ?MODULE:size(Buffer3)), ?_assertEqual(4, ?MODULE:size(Buffer4)), ?_assertEqual(0, ?MODULE:size(Buffer5)) ]}. -endif.
null
https://raw.githubusercontent.com/basho/riak_kv/aeef1591704d32230b773d952a2f1543cbfa1889/src/riak_kv_fold_buffer.erl
erlang
------------------------------------------------------------------- riak_kv_fold_buffer: Provide operations for creating and using size-limited buffers for use in folds.n Version 2.0 (the "License"); you may not use this file a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ------------------------------------------------------------------- @doc Provide operations for creating and using size-limited buffers for use in folds. Public API =================================================================== Public API =================================================================== @doc Returns a new buffer with the specified maximum size and buffer function. @doc Add an item to the buffer. If the size of the buffer is equal to the maximum size of this buffer then the buffer function is called on the accumlated buffer items and then the buffer is emptied. @doc Call the buffer function on the remaining items and then reset the buffer. @doc Returns the size of the buffer. =================================================================== ===================================================================
Copyright ( c ) 2007 - 2011 Basho Technologies , Inc. All Rights Reserved . This file is provided to you under the Apache License , except in compliance with the License . You may obtain software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY -module(riak_kv_fold_buffer). -export([new/2, add/2, flush/1, size/1]). -export_type([buffer/0]). -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). -endif. -record(buffer, {acc=[] :: [any()], buffer_fun :: function(), max_size :: pos_integer(), size=0 :: non_neg_integer()}). -type buffer() :: #buffer{}. -spec new(pos_integer(), fun(([any()]) -> any())) -> buffer(). new(MaxSize, Fun) -> #buffer{buffer_fun=Fun, max_size=MaxSize-1}. -spec add(any(), buffer()) -> buffer(). add(Item, #buffer{acc=Acc, buffer_fun=Fun, max_size=MaxSize, size=MaxSize}=Buffer) -> Fun([Item | Acc]), Buffer#buffer{acc=[], size=0}; add(Item, #buffer{acc=Acc, size=Size}=Buffer) -> Buffer#buffer{acc=[Item | Acc], size=Size+1}. -spec flush(buffer()) -> buffer(). flush(#buffer{acc=Acc, buffer_fun=Fun}=Buffer) -> Fun(Acc), Buffer#buffer{acc=[], size=0}. -spec size(buffer()) -> non_neg_integer(). size(#buffer{size=Size}) -> Size. EUnit tests -ifdef(TEST). fold_buffer_test_() -> Fun = fun(_) -> true end, Buffer = new(5, Fun), Buffer1 = add(1, Buffer), Buffer2 = add(2, Buffer1), Buffer3 = add(3, Buffer2), Buffer4 = add(4, Buffer3), Buffer5 = add(5, Buffer4), {spawn, [ ?_assertEqual(#buffer{acc=[1], buffer_fun=Fun, max_size=4, size=1}, Buffer1), ?_assertEqual(#buffer{acc=[2,1], buffer_fun=Fun, max_size=4, size=2}, Buffer2), ?_assertEqual(#buffer{acc=[3,2,1], buffer_fun=Fun, max_size=4, size=3}, Buffer3), ?_assertEqual(#buffer{acc=[4,3,2,1], buffer_fun=Fun, max_size=4, size=4}, Buffer4), ?_assertEqual(#buffer{acc=[], buffer_fun=Fun, max_size=4, size=0}, Buffer5), ?_assertEqual(Buffer5#buffer{acc=[], size=0}, flush(Buffer5)), ?_assertEqual(0, ?MODULE:size(Buffer)), ?_assertEqual(1, ?MODULE:size(Buffer1)), ?_assertEqual(2, ?MODULE:size(Buffer2)), ?_assertEqual(3, ?MODULE:size(Buffer3)), ?_assertEqual(4, ?MODULE:size(Buffer4)), ?_assertEqual(0, ?MODULE:size(Buffer5)) ]}. -endif.
f3a56fdc40137a2431a15914dfb8e7f2232b52601fceb14f7fe355dab231d731
clojerl/clojerl
clojerl.ArityError.erl
-module('clojerl.ArityError'). -include("clojerl.hrl"). -behavior('clojerl.IEquiv'). -behavior('clojerl.IError'). -behavior('clojerl.IHash'). -behavior('clojerl.IStringable'). -export([?CONSTRUCTOR/2]). -export([equiv/2]). -export([ message/1 , message/2 ]). -export([hash/1]). -export([str/1]). -export_type([type/0]). -type type() :: #{ ?TYPE => ?M , actual => arity() , message => binary() , name => binary() }. -spec ?CONSTRUCTOR(arity(), binary()) -> type(). ?CONSTRUCTOR(Arity, Name) when is_integer(Arity), is_binary(Name) -> ArityBin = integer_to_binary(Arity), Message = <<"Wrong number of args (", ArityBin/binary, ") ", "passed to: ", Name/binary>>, #{ ?TYPE => ?M , actual => Arity , message => Message , name => Name }. %%------------------------------------------------------------------------------ Protocols %%------------------------------------------------------------------------------ %% clojerl.IEquiv equiv(#{?TYPE := ?M} = X, #{?TYPE := ?M} = X) -> true; equiv(_, _) -> false. %% clojerl.IError message(#{?TYPE := ?M, message := Message}) -> Message. message(#{?TYPE := ?M} = Error, Msg) -> Error#{message := Msg}. clojerl . IHash hash(#{?TYPE := ?M} = Error) -> erlang:phash2(Error). %% clojerl.IStringable str(#{?TYPE := ?M} = Error) -> clj_utils:error_str(?M, message(Error)).
null
https://raw.githubusercontent.com/clojerl/clojerl/506000465581d6349659898dd5025fa259d5cf28/src/erl/lang/errors/clojerl.ArityError.erl
erlang
------------------------------------------------------------------------------ ------------------------------------------------------------------------------ clojerl.IEquiv clojerl.IError clojerl.IStringable
-module('clojerl.ArityError'). -include("clojerl.hrl"). -behavior('clojerl.IEquiv'). -behavior('clojerl.IError'). -behavior('clojerl.IHash'). -behavior('clojerl.IStringable'). -export([?CONSTRUCTOR/2]). -export([equiv/2]). -export([ message/1 , message/2 ]). -export([hash/1]). -export([str/1]). -export_type([type/0]). -type type() :: #{ ?TYPE => ?M , actual => arity() , message => binary() , name => binary() }. -spec ?CONSTRUCTOR(arity(), binary()) -> type(). ?CONSTRUCTOR(Arity, Name) when is_integer(Arity), is_binary(Name) -> ArityBin = integer_to_binary(Arity), Message = <<"Wrong number of args (", ArityBin/binary, ") ", "passed to: ", Name/binary>>, #{ ?TYPE => ?M , actual => Arity , message => Message , name => Name }. Protocols equiv(#{?TYPE := ?M} = X, #{?TYPE := ?M} = X) -> true; equiv(_, _) -> false. message(#{?TYPE := ?M, message := Message}) -> Message. message(#{?TYPE := ?M} = Error, Msg) -> Error#{message := Msg}. clojerl . IHash hash(#{?TYPE := ?M} = Error) -> erlang:phash2(Error). str(#{?TYPE := ?M} = Error) -> clj_utils:error_str(?M, message(Error)).
32ca730d2e6f9c9a39b01301cd879840b87e176fef502478876f50fdaf822892
vyos/vyconf
vyconf_types.ml
[@@@ocaml.warning "-27-30-39"] type request_config_format = | Curly | Json type request_output_format = | Out_plain | Out_json type request_setup_session = { client_application : string option; on_behalf_of : int32 option; } type request_set = { path : string list; ephemeral : bool option; } type request_delete = { path : string list; } type request_rename = { edit_level : string list; from : string; to_ : string; } type request_copy = { edit_level : string list; from : string; to_ : string; } type request_comment = { path : string list; comment : string; } type request_commit = { confirm : bool option; confirm_timeout : int32 option; comment : string option; } type request_rollback = { revision : int32; } type request_load = { location : string; format : request_config_format option; } type request_merge = { location : string; format : request_config_format option; } type request_save = { location : string; format : request_config_format option; } type request_show_config = { path : string list; format : request_config_format option; } type request_exists = { path : string list; } type request_get_value = { path : string list; output_format : request_output_format option; } type request_get_values = { path : string list; output_format : request_output_format option; } type request_list_children = { path : string list; output_format : request_output_format option; } type request_run_op_mode = { path : string list; output_format : request_output_format option; } type request_enter_configuration_mode = { exclusive : bool; override_exclusive : bool; } type request = | Status | Setup_session of request_setup_session | Set of request_set | Delete of request_delete | Rename of request_rename | Copy of request_copy | Comment of request_comment | Commit of request_commit | Rollback of request_rollback | Merge of request_merge | Save of request_save | Show_config of request_show_config | Exists of request_exists | Get_value of request_get_value | Get_values of request_get_values | List_children of request_list_children | Run_op_mode of request_run_op_mode | Confirm | Configure of request_enter_configuration_mode | Exit_configure | Teardown of string type request_envelope = { token : string option; request : request; } type status = | Success | Fail | Invalid_path | Invalid_value | Commit_in_progress | Configuration_locked | Internal_error | Permission_denied | Path_already_exists type response = { status : status; output : string option; error : string option; warning : string option; } let rec default_request_config_format () = (Curly:request_config_format) let rec default_request_output_format () = (Out_plain:request_output_format) let rec default_request_setup_session ?client_application:((client_application:string option) = None) ?on_behalf_of:((on_behalf_of:int32 option) = None) () : request_setup_session = { client_application; on_behalf_of; } let rec default_request_set ?path:((path:string list) = []) ?ephemeral:((ephemeral:bool option) = None) () : request_set = { path; ephemeral; } let rec default_request_delete ?path:((path:string list) = []) () : request_delete = { path; } let rec default_request_rename ?edit_level:((edit_level:string list) = []) ?from:((from:string) = "") ?to_:((to_:string) = "") () : request_rename = { edit_level; from; to_; } let rec default_request_copy ?edit_level:((edit_level:string list) = []) ?from:((from:string) = "") ?to_:((to_:string) = "") () : request_copy = { edit_level; from; to_; } let rec default_request_comment ?path:((path:string list) = []) ?comment:((comment:string) = "") () : request_comment = { path; comment; } let rec default_request_commit ?confirm:((confirm:bool option) = None) ?confirm_timeout:((confirm_timeout:int32 option) = None) ?comment:((comment:string option) = None) () : request_commit = { confirm; confirm_timeout; comment; } let rec default_request_rollback ?revision:((revision:int32) = 0l) () : request_rollback = { revision; } let rec default_request_load ?location:((location:string) = "") ?format:((format:request_config_format option) = None) () : request_load = { location; format; } let rec default_request_merge ?location:((location:string) = "") ?format:((format:request_config_format option) = None) () : request_merge = { location; format; } let rec default_request_save ?location:((location:string) = "") ?format:((format:request_config_format option) = None) () : request_save = { location; format; } let rec default_request_show_config ?path:((path:string list) = []) ?format:((format:request_config_format option) = None) () : request_show_config = { path; format; } let rec default_request_exists ?path:((path:string list) = []) () : request_exists = { path; } let rec default_request_get_value ?path:((path:string list) = []) ?output_format:((output_format:request_output_format option) = None) () : request_get_value = { path; output_format; } let rec default_request_get_values ?path:((path:string list) = []) ?output_format:((output_format:request_output_format option) = None) () : request_get_values = { path; output_format; } let rec default_request_list_children ?path:((path:string list) = []) ?output_format:((output_format:request_output_format option) = None) () : request_list_children = { path; output_format; } let rec default_request_run_op_mode ?path:((path:string list) = []) ?output_format:((output_format:request_output_format option) = None) () : request_run_op_mode = { path; output_format; } let rec default_request_enter_configuration_mode ?exclusive:((exclusive:bool) = false) ?override_exclusive:((override_exclusive:bool) = false) () : request_enter_configuration_mode = { exclusive; override_exclusive; } let rec default_request (): request = Status let rec default_request_envelope ?token:((token:string option) = None) ?request:((request:request) = default_request ()) () : request_envelope = { token; request; } let rec default_status () = (Success:status) let rec default_response ?status:((status:status) = default_status ()) ?output:((output:string option) = None) ?error:((error:string option) = None) ?warning:((warning:string option) = None) () : response = { status; output; error; warning; }
null
https://raw.githubusercontent.com/vyos/vyconf/dd9271b4304c6b1a5a2576821d1b2b8fd3aa6bf5/src/vyconf_types.ml
ocaml
[@@@ocaml.warning "-27-30-39"] type request_config_format = | Curly | Json type request_output_format = | Out_plain | Out_json type request_setup_session = { client_application : string option; on_behalf_of : int32 option; } type request_set = { path : string list; ephemeral : bool option; } type request_delete = { path : string list; } type request_rename = { edit_level : string list; from : string; to_ : string; } type request_copy = { edit_level : string list; from : string; to_ : string; } type request_comment = { path : string list; comment : string; } type request_commit = { confirm : bool option; confirm_timeout : int32 option; comment : string option; } type request_rollback = { revision : int32; } type request_load = { location : string; format : request_config_format option; } type request_merge = { location : string; format : request_config_format option; } type request_save = { location : string; format : request_config_format option; } type request_show_config = { path : string list; format : request_config_format option; } type request_exists = { path : string list; } type request_get_value = { path : string list; output_format : request_output_format option; } type request_get_values = { path : string list; output_format : request_output_format option; } type request_list_children = { path : string list; output_format : request_output_format option; } type request_run_op_mode = { path : string list; output_format : request_output_format option; } type request_enter_configuration_mode = { exclusive : bool; override_exclusive : bool; } type request = | Status | Setup_session of request_setup_session | Set of request_set | Delete of request_delete | Rename of request_rename | Copy of request_copy | Comment of request_comment | Commit of request_commit | Rollback of request_rollback | Merge of request_merge | Save of request_save | Show_config of request_show_config | Exists of request_exists | Get_value of request_get_value | Get_values of request_get_values | List_children of request_list_children | Run_op_mode of request_run_op_mode | Confirm | Configure of request_enter_configuration_mode | Exit_configure | Teardown of string type request_envelope = { token : string option; request : request; } type status = | Success | Fail | Invalid_path | Invalid_value | Commit_in_progress | Configuration_locked | Internal_error | Permission_denied | Path_already_exists type response = { status : status; output : string option; error : string option; warning : string option; } let rec default_request_config_format () = (Curly:request_config_format) let rec default_request_output_format () = (Out_plain:request_output_format) let rec default_request_setup_session ?client_application:((client_application:string option) = None) ?on_behalf_of:((on_behalf_of:int32 option) = None) () : request_setup_session = { client_application; on_behalf_of; } let rec default_request_set ?path:((path:string list) = []) ?ephemeral:((ephemeral:bool option) = None) () : request_set = { path; ephemeral; } let rec default_request_delete ?path:((path:string list) = []) () : request_delete = { path; } let rec default_request_rename ?edit_level:((edit_level:string list) = []) ?from:((from:string) = "") ?to_:((to_:string) = "") () : request_rename = { edit_level; from; to_; } let rec default_request_copy ?edit_level:((edit_level:string list) = []) ?from:((from:string) = "") ?to_:((to_:string) = "") () : request_copy = { edit_level; from; to_; } let rec default_request_comment ?path:((path:string list) = []) ?comment:((comment:string) = "") () : request_comment = { path; comment; } let rec default_request_commit ?confirm:((confirm:bool option) = None) ?confirm_timeout:((confirm_timeout:int32 option) = None) ?comment:((comment:string option) = None) () : request_commit = { confirm; confirm_timeout; comment; } let rec default_request_rollback ?revision:((revision:int32) = 0l) () : request_rollback = { revision; } let rec default_request_load ?location:((location:string) = "") ?format:((format:request_config_format option) = None) () : request_load = { location; format; } let rec default_request_merge ?location:((location:string) = "") ?format:((format:request_config_format option) = None) () : request_merge = { location; format; } let rec default_request_save ?location:((location:string) = "") ?format:((format:request_config_format option) = None) () : request_save = { location; format; } let rec default_request_show_config ?path:((path:string list) = []) ?format:((format:request_config_format option) = None) () : request_show_config = { path; format; } let rec default_request_exists ?path:((path:string list) = []) () : request_exists = { path; } let rec default_request_get_value ?path:((path:string list) = []) ?output_format:((output_format:request_output_format option) = None) () : request_get_value = { path; output_format; } let rec default_request_get_values ?path:((path:string list) = []) ?output_format:((output_format:request_output_format option) = None) () : request_get_values = { path; output_format; } let rec default_request_list_children ?path:((path:string list) = []) ?output_format:((output_format:request_output_format option) = None) () : request_list_children = { path; output_format; } let rec default_request_run_op_mode ?path:((path:string list) = []) ?output_format:((output_format:request_output_format option) = None) () : request_run_op_mode = { path; output_format; } let rec default_request_enter_configuration_mode ?exclusive:((exclusive:bool) = false) ?override_exclusive:((override_exclusive:bool) = false) () : request_enter_configuration_mode = { exclusive; override_exclusive; } let rec default_request (): request = Status let rec default_request_envelope ?token:((token:string option) = None) ?request:((request:request) = default_request ()) () : request_envelope = { token; request; } let rec default_status () = (Success:status) let rec default_response ?status:((status:status) = default_status ()) ?output:((output:string option) = None) ?error:((error:string option) = None) ?warning:((warning:string option) = None) () : response = { status; output; error; warning; }
cedf5cd1c6785d535b3695f3b53eb3b1a2ba7b4b789bd186cf2fd5913d3c4dc4
gren-lang/compiler
Declaration.hs
{-# LANGUAGE OverloadedStrings #-} -- Temporary while implementing gren format # OPTIONS_GHC -Wno - error = unused - do - bind # # OPTIONS_GHC -Wno - error = unused - local - binds # # OPTIONS_GHC -Wno - error = unused - matches # module Parse.Declaration ( Decl (..), declaration, infix_, ) where import AST.Source qualified as Src import AST.SourceComments qualified as SC import AST.Utils.Binop qualified as Binop import Data.List qualified as List import Data.List.NonEmpty (NonEmpty (..)) import Data.List.NonEmpty qualified as NonEmpty import Data.Name qualified as Name import Parse.Expression qualified as Expr import Parse.Keyword qualified as Keyword import Parse.Number qualified as Number import Parse.Pattern qualified as Pattern import Parse.Primitives hiding (State) import Parse.Primitives qualified as P import Parse.Space qualified as Space import Parse.Symbol qualified as Symbol import Parse.Type qualified as Type import Parse.Variable qualified as Var import Reporting.Annotation qualified as A import Reporting.Error.Syntax qualified as E -- DECLARATION data Decl = Value (Maybe Src.DocComment) (A.Located Src.Value) | Union (Maybe Src.DocComment) (A.Located Src.Union) | Alias (Maybe Src.DocComment) (A.Located Src.Alias) | Port (Maybe Src.DocComment) Src.Port | TopLevelComments (NonEmpty Src.Comment) declaration :: Space.Parser E.Decl (Decl, [Src.Comment]) declaration = do maybeDocs <- chompDocComment start <- getPosition oneOf E.DeclStart [ typeDecl maybeDocs start, portDecl maybeDocs, valueDecl maybeDocs start ] DOC COMMENT chompDocComment :: Parser E.Decl (Maybe Src.DocComment) chompDocComment = oneOfWithFallback [ do docComment <- Space.docComment E.DeclStart E.DeclSpace Space.chomp E.DeclSpace Space.checkFreshLine E.DeclFreshLineAfterDocComment return (Just docComment) ] Nothing DEFINITION and ANNOTATION valueDecl :: Maybe Src.DocComment -> A.Position -> Space.Parser E.Decl (Decl, [Src.Comment]) valueDecl maybeDocs start = do name <- Var.lower E.DeclStart end <- getPosition specialize (E.DeclDef name) $ do commentsAfterName <- Space.chompAndCheckIndent E.DeclDefSpace E.DeclDefIndentEquals oneOf E.DeclDefEquals [ do word1 0x3A {-:-} E.DeclDefEquals let commentsBeforeColon = commentsAfterName commentsAfterColon <- Space.chompAndCheckIndent E.DeclDefSpace E.DeclDefIndentType ((tipe, commentsAfterTipe), _) <- specialize E.DeclDefType Type.expression Space.checkFreshLine E.DeclDefNameRepeat defName <- chompMatchingName name commentsAfterMatchingName <- Space.chompAndCheckIndent E.DeclDefSpace E.DeclDefIndentEquals let tipeComments = SC.ValueTypeComments commentsBeforeColon commentsAfterColon commentsAfterTipe chompDefArgsAndBody maybeDocs start defName (Just (tipe, tipeComments)) [] commentsAfterMatchingName, chompDefArgsAndBody maybeDocs start (A.at start end name) Nothing [] commentsAfterName ] chompDefArgsAndBody :: Maybe Src.DocComment -> A.Position -> A.Located Name.Name -> Maybe (Src.Type, SC.ValueTypeComments) -> [([Src.Comment], Src.Pattern)] -> [Src.Comment] -> Space.Parser E.DeclDef (Decl, [Src.Comment]) chompDefArgsAndBody maybeDocs start name tipe revArgs commentsBefore = oneOf E.DeclDefEquals [ do arg <- specialize E.DeclDefArg Pattern.term commentsAfterArg <- Space.chompAndCheckIndent E.DeclDefSpace E.DeclDefIndentEquals chompDefArgsAndBody maybeDocs start name tipe ((commentsBefore, arg) : revArgs) commentsAfterArg, do word1 0x3D {-=-} E.DeclDefEquals commentsAfterEquals <- Space.chompAndCheckIndent E.DeclDefSpace E.DeclDefIndentBody ((body, commentsAfter), end) <- specialize E.DeclDefBody Expr.expression let (commentsAfterBody, commentsAfterDef) = List.span (A.isIndentedMoreThan 1) commentsAfter let comments = SC.ValueComments commentsBefore commentsAfterEquals commentsAfterBody let value = Src.Value name (reverse revArgs) body tipe comments let avalue = A.at start end value return ((Value maybeDocs avalue, commentsAfterDef), end) ] chompMatchingName :: Name.Name -> Parser E.DeclDef (A.Located Name.Name) chompMatchingName expectedName = let (P.Parser parserL) = Var.lower E.DeclDefNameRepeat in P.Parser $ \state@(P.State _ _ _ _ sr sc) cok eok cerr eerr -> let cokL name newState@(P.State _ _ _ _ er ec) = if expectedName == name then cok (A.At (A.Region (A.Position sr sc) (A.Position er ec)) name) newState else cerr sr sc (E.DeclDefNameMatch name) eokL name newState@(P.State _ _ _ _ er ec) = if expectedName == name then eok (A.At (A.Region (A.Position sr sc) (A.Position er ec)) name) newState else eerr sr sc (E.DeclDefNameMatch name) in parserL state cokL eokL cerr eerr -- TYPE DECLARATIONS typeDecl :: Maybe Src.DocComment -> A.Position -> Space.Parser E.Decl (Decl, [Src.Comment]) typeDecl maybeDocs start = inContext E.DeclType (Keyword.type_ E.DeclStart) $ do commentsAfterTypeKeyword <- Space.chompAndCheckIndent E.DT_Space E.DT_IndentName oneOf E.DT_Name [ inContext E.DT_Alias (Keyword.alias_ E.DT_Name) $ do TODO : use commentsAfterTypeKeyword Space.chompAndCheckIndent E.AliasSpace E.AliasIndentEquals (name, args) <- chompAliasNameToEquals ((tipe, commentsAfterTipe), end) <- specialize E.AliasBody Type.expression let alias = A.at start end (Src.Alias name args tipe) return ((Alias maybeDocs alias, commentsAfterTipe), end), specialize E.DT_Union $ do (name, args, commentsAfterArgs, commentsAfterEquals) <- chompCustomNameToEquals ((firstName, firstArgs, commentsAfterFirst), firstEnd) <- Type.variant let firstVariant = (commentsAfterEquals, firstName, firstArgs, commentsAfterFirst) ((variants, commentsAfter), end) <- chompVariants (NonEmpty.singleton firstVariant) firstEnd let comments = SC.UnionComments commentsAfterTypeKeyword commentsAfterArgs let union = A.at start end (Src.Union name args variants comments) return ((Union maybeDocs union, commentsAfter), end) ] -- TYPE ALIASES chompAliasNameToEquals :: Parser E.TypeAlias (A.Located Name.Name, [A.Located Name.Name]) chompAliasNameToEquals = do name <- addLocation (Var.upper E.AliasName) Space.chompAndCheckIndent E.AliasSpace E.AliasIndentEquals chompAliasNameToEqualsHelp name [] chompAliasNameToEqualsHelp :: A.Located Name.Name -> [A.Located Name.Name] -> Parser E.TypeAlias (A.Located Name.Name, [A.Located Name.Name]) chompAliasNameToEqualsHelp name args = oneOf E.AliasEquals [ do arg <- addLocation (Var.lower E.AliasEquals) Space.chompAndCheckIndent E.AliasSpace E.AliasIndentEquals chompAliasNameToEqualsHelp name (arg : args), do word1 0x3D {-=-} E.AliasEquals Space.chompAndCheckIndent E.AliasSpace E.AliasIndentBody return (name, reverse args) ] -- CUSTOM TYPES chompCustomNameToEquals :: Parser E.CustomType (A.Located Name.Name, [([Src.Comment], A.Located Name.Name)], [Src.Comment], [Src.Comment]) chompCustomNameToEquals = do name <- addLocation (Var.upper E.CT_Name) commentsAfterName <- Space.chompAndCheckIndent E.CT_Space E.CT_IndentEquals chompCustomNameToEqualsHelp name commentsAfterName [] chompCustomNameToEqualsHelp :: A.Located Name.Name -> [Src.Comment] -> [([Src.Comment], A.Located Name.Name)] -> Parser E.CustomType (A.Located Name.Name, [([Src.Comment], A.Located Name.Name)], [Src.Comment], [Src.Comment]) chompCustomNameToEqualsHelp name commentsAfterPrev args = oneOf E.CT_Equals [ do arg <- addLocation (Var.lower E.CT_Equals) commentsAfterArg <- Space.chompAndCheckIndent E.CT_Space E.CT_IndentEquals chompCustomNameToEqualsHelp name commentsAfterArg ((commentsAfterPrev, arg) : args), do word1 0x3D {-=-} E.CT_Equals commentsAfter <- Space.chompAndCheckIndent E.CT_Space E.CT_IndentAfterEquals return (name, reverse args, commentsAfterPrev, commentsAfter) ] chompVariants :: NonEmpty (Src.UnionVariant) -> A.Position -> Space.Parser E.CustomType ([Src.UnionVariant], [Src.Comment]) chompVariants variants@((lastCommentsBefore, lastName, lastArgs, lastCommentsAfter) :| rest) end = oneOfWithFallback [ do Space.checkIndent end E.CT_IndentBar word1 0x7C E.CT_Bar commentsAfterBar <- Space.chompAndCheckIndent E.CT_Space E.CT_IndentAfterBar ((name, args, commentsAfter), newEnd) <- Type.variant let variant = (commentsAfterBar, name, args, commentsAfter) chompVariants (NonEmpty.cons variant variants) newEnd ] ( let (commentsAfterLastVariant, commentsAfter) = List.span (A.isIndentedMoreThan 1) lastCommentsAfter in ((reverse ((lastCommentsBefore, lastName, lastArgs, commentsAfterLastVariant) : rest), commentsAfter), end) ) -- PORT portDecl :: Maybe Src.DocComment -> Space.Parser E.Decl (Decl, [Src.Comment]) portDecl maybeDocs = inContext E.Port (Keyword.port_ E.DeclStart) $ do Space.chompAndCheckIndent E.PortSpace E.PortIndentName name <- addLocation (Var.lower E.PortName) Space.chompAndCheckIndent E.PortSpace E.PortIndentColon word1 0x3A {-:-} E.PortColon Space.chompAndCheckIndent E.PortSpace E.PortIndentType ((tipe, commentsAfterTipe), end) <- specialize E.PortType Type.expression return ( (Port maybeDocs (Src.Port name tipe), commentsAfterTipe), end ) INFIX -- INVARIANT: always chomps to a freshline -- infix_ :: Parser E.Module (A.Located Src.Infix, [Src.Comment]) infix_ = let err = E.Infix _err = \_ -> E.Infix in do start <- getPosition Keyword.infix_ err Space.chompAndCheckIndent _err err associativity <- oneOf err [ Keyword.left_ err >> return Binop.Left, Keyword.right_ err >> return Binop.Right, Keyword.non_ err >> return Binop.Non ] Space.chompAndCheckIndent _err err precedence <- Number.precedence err Space.chompAndCheckIndent _err err word1 0x28 {-(-} err op <- Symbol.operator err _err word1 0x29 {-)-} err Space.chompAndCheckIndent _err err word1 0x3D {-=-} err Space.chompAndCheckIndent _err err name <- Var.lower err end <- getPosition commentsAfter <- Space.chomp _err Space.checkFreshLine err return (A.at start end (Src.Infix op associativity precedence name), commentsAfter)
null
https://raw.githubusercontent.com/gren-lang/compiler/c3a39dc7177934704ba2c1942580f1f8169954a9/compiler/src/Parse/Declaration.hs
haskell
# LANGUAGE OverloadedStrings # Temporary while implementing gren format DECLARATION : = TYPE DECLARATIONS TYPE ALIASES = CUSTOM TYPES = PORT : INVARIANT: always chomps to a freshline ( ) =
# OPTIONS_GHC -Wno - error = unused - do - bind # # OPTIONS_GHC -Wno - error = unused - local - binds # # OPTIONS_GHC -Wno - error = unused - matches # module Parse.Declaration ( Decl (..), declaration, infix_, ) where import AST.Source qualified as Src import AST.SourceComments qualified as SC import AST.Utils.Binop qualified as Binop import Data.List qualified as List import Data.List.NonEmpty (NonEmpty (..)) import Data.List.NonEmpty qualified as NonEmpty import Data.Name qualified as Name import Parse.Expression qualified as Expr import Parse.Keyword qualified as Keyword import Parse.Number qualified as Number import Parse.Pattern qualified as Pattern import Parse.Primitives hiding (State) import Parse.Primitives qualified as P import Parse.Space qualified as Space import Parse.Symbol qualified as Symbol import Parse.Type qualified as Type import Parse.Variable qualified as Var import Reporting.Annotation qualified as A import Reporting.Error.Syntax qualified as E data Decl = Value (Maybe Src.DocComment) (A.Located Src.Value) | Union (Maybe Src.DocComment) (A.Located Src.Union) | Alias (Maybe Src.DocComment) (A.Located Src.Alias) | Port (Maybe Src.DocComment) Src.Port | TopLevelComments (NonEmpty Src.Comment) declaration :: Space.Parser E.Decl (Decl, [Src.Comment]) declaration = do maybeDocs <- chompDocComment start <- getPosition oneOf E.DeclStart [ typeDecl maybeDocs start, portDecl maybeDocs, valueDecl maybeDocs start ] DOC COMMENT chompDocComment :: Parser E.Decl (Maybe Src.DocComment) chompDocComment = oneOfWithFallback [ do docComment <- Space.docComment E.DeclStart E.DeclSpace Space.chomp E.DeclSpace Space.checkFreshLine E.DeclFreshLineAfterDocComment return (Just docComment) ] Nothing DEFINITION and ANNOTATION valueDecl :: Maybe Src.DocComment -> A.Position -> Space.Parser E.Decl (Decl, [Src.Comment]) valueDecl maybeDocs start = do name <- Var.lower E.DeclStart end <- getPosition specialize (E.DeclDef name) $ do commentsAfterName <- Space.chompAndCheckIndent E.DeclDefSpace E.DeclDefIndentEquals oneOf E.DeclDefEquals [ do let commentsBeforeColon = commentsAfterName commentsAfterColon <- Space.chompAndCheckIndent E.DeclDefSpace E.DeclDefIndentType ((tipe, commentsAfterTipe), _) <- specialize E.DeclDefType Type.expression Space.checkFreshLine E.DeclDefNameRepeat defName <- chompMatchingName name commentsAfterMatchingName <- Space.chompAndCheckIndent E.DeclDefSpace E.DeclDefIndentEquals let tipeComments = SC.ValueTypeComments commentsBeforeColon commentsAfterColon commentsAfterTipe chompDefArgsAndBody maybeDocs start defName (Just (tipe, tipeComments)) [] commentsAfterMatchingName, chompDefArgsAndBody maybeDocs start (A.at start end name) Nothing [] commentsAfterName ] chompDefArgsAndBody :: Maybe Src.DocComment -> A.Position -> A.Located Name.Name -> Maybe (Src.Type, SC.ValueTypeComments) -> [([Src.Comment], Src.Pattern)] -> [Src.Comment] -> Space.Parser E.DeclDef (Decl, [Src.Comment]) chompDefArgsAndBody maybeDocs start name tipe revArgs commentsBefore = oneOf E.DeclDefEquals [ do arg <- specialize E.DeclDefArg Pattern.term commentsAfterArg <- Space.chompAndCheckIndent E.DeclDefSpace E.DeclDefIndentEquals chompDefArgsAndBody maybeDocs start name tipe ((commentsBefore, arg) : revArgs) commentsAfterArg, do commentsAfterEquals <- Space.chompAndCheckIndent E.DeclDefSpace E.DeclDefIndentBody ((body, commentsAfter), end) <- specialize E.DeclDefBody Expr.expression let (commentsAfterBody, commentsAfterDef) = List.span (A.isIndentedMoreThan 1) commentsAfter let comments = SC.ValueComments commentsBefore commentsAfterEquals commentsAfterBody let value = Src.Value name (reverse revArgs) body tipe comments let avalue = A.at start end value return ((Value maybeDocs avalue, commentsAfterDef), end) ] chompMatchingName :: Name.Name -> Parser E.DeclDef (A.Located Name.Name) chompMatchingName expectedName = let (P.Parser parserL) = Var.lower E.DeclDefNameRepeat in P.Parser $ \state@(P.State _ _ _ _ sr sc) cok eok cerr eerr -> let cokL name newState@(P.State _ _ _ _ er ec) = if expectedName == name then cok (A.At (A.Region (A.Position sr sc) (A.Position er ec)) name) newState else cerr sr sc (E.DeclDefNameMatch name) eokL name newState@(P.State _ _ _ _ er ec) = if expectedName == name then eok (A.At (A.Region (A.Position sr sc) (A.Position er ec)) name) newState else eerr sr sc (E.DeclDefNameMatch name) in parserL state cokL eokL cerr eerr typeDecl :: Maybe Src.DocComment -> A.Position -> Space.Parser E.Decl (Decl, [Src.Comment]) typeDecl maybeDocs start = inContext E.DeclType (Keyword.type_ E.DeclStart) $ do commentsAfterTypeKeyword <- Space.chompAndCheckIndent E.DT_Space E.DT_IndentName oneOf E.DT_Name [ inContext E.DT_Alias (Keyword.alias_ E.DT_Name) $ do TODO : use commentsAfterTypeKeyword Space.chompAndCheckIndent E.AliasSpace E.AliasIndentEquals (name, args) <- chompAliasNameToEquals ((tipe, commentsAfterTipe), end) <- specialize E.AliasBody Type.expression let alias = A.at start end (Src.Alias name args tipe) return ((Alias maybeDocs alias, commentsAfterTipe), end), specialize E.DT_Union $ do (name, args, commentsAfterArgs, commentsAfterEquals) <- chompCustomNameToEquals ((firstName, firstArgs, commentsAfterFirst), firstEnd) <- Type.variant let firstVariant = (commentsAfterEquals, firstName, firstArgs, commentsAfterFirst) ((variants, commentsAfter), end) <- chompVariants (NonEmpty.singleton firstVariant) firstEnd let comments = SC.UnionComments commentsAfterTypeKeyword commentsAfterArgs let union = A.at start end (Src.Union name args variants comments) return ((Union maybeDocs union, commentsAfter), end) ] chompAliasNameToEquals :: Parser E.TypeAlias (A.Located Name.Name, [A.Located Name.Name]) chompAliasNameToEquals = do name <- addLocation (Var.upper E.AliasName) Space.chompAndCheckIndent E.AliasSpace E.AliasIndentEquals chompAliasNameToEqualsHelp name [] chompAliasNameToEqualsHelp :: A.Located Name.Name -> [A.Located Name.Name] -> Parser E.TypeAlias (A.Located Name.Name, [A.Located Name.Name]) chompAliasNameToEqualsHelp name args = oneOf E.AliasEquals [ do arg <- addLocation (Var.lower E.AliasEquals) Space.chompAndCheckIndent E.AliasSpace E.AliasIndentEquals chompAliasNameToEqualsHelp name (arg : args), do Space.chompAndCheckIndent E.AliasSpace E.AliasIndentBody return (name, reverse args) ] chompCustomNameToEquals :: Parser E.CustomType (A.Located Name.Name, [([Src.Comment], A.Located Name.Name)], [Src.Comment], [Src.Comment]) chompCustomNameToEquals = do name <- addLocation (Var.upper E.CT_Name) commentsAfterName <- Space.chompAndCheckIndent E.CT_Space E.CT_IndentEquals chompCustomNameToEqualsHelp name commentsAfterName [] chompCustomNameToEqualsHelp :: A.Located Name.Name -> [Src.Comment] -> [([Src.Comment], A.Located Name.Name)] -> Parser E.CustomType (A.Located Name.Name, [([Src.Comment], A.Located Name.Name)], [Src.Comment], [Src.Comment]) chompCustomNameToEqualsHelp name commentsAfterPrev args = oneOf E.CT_Equals [ do arg <- addLocation (Var.lower E.CT_Equals) commentsAfterArg <- Space.chompAndCheckIndent E.CT_Space E.CT_IndentEquals chompCustomNameToEqualsHelp name commentsAfterArg ((commentsAfterPrev, arg) : args), do commentsAfter <- Space.chompAndCheckIndent E.CT_Space E.CT_IndentAfterEquals return (name, reverse args, commentsAfterPrev, commentsAfter) ] chompVariants :: NonEmpty (Src.UnionVariant) -> A.Position -> Space.Parser E.CustomType ([Src.UnionVariant], [Src.Comment]) chompVariants variants@((lastCommentsBefore, lastName, lastArgs, lastCommentsAfter) :| rest) end = oneOfWithFallback [ do Space.checkIndent end E.CT_IndentBar word1 0x7C E.CT_Bar commentsAfterBar <- Space.chompAndCheckIndent E.CT_Space E.CT_IndentAfterBar ((name, args, commentsAfter), newEnd) <- Type.variant let variant = (commentsAfterBar, name, args, commentsAfter) chompVariants (NonEmpty.cons variant variants) newEnd ] ( let (commentsAfterLastVariant, commentsAfter) = List.span (A.isIndentedMoreThan 1) lastCommentsAfter in ((reverse ((lastCommentsBefore, lastName, lastArgs, commentsAfterLastVariant) : rest), commentsAfter), end) ) portDecl :: Maybe Src.DocComment -> Space.Parser E.Decl (Decl, [Src.Comment]) portDecl maybeDocs = inContext E.Port (Keyword.port_ E.DeclStart) $ do Space.chompAndCheckIndent E.PortSpace E.PortIndentName name <- addLocation (Var.lower E.PortName) Space.chompAndCheckIndent E.PortSpace E.PortIndentColon Space.chompAndCheckIndent E.PortSpace E.PortIndentType ((tipe, commentsAfterTipe), end) <- specialize E.PortType Type.expression return ( (Port maybeDocs (Src.Port name tipe), commentsAfterTipe), end ) INFIX infix_ :: Parser E.Module (A.Located Src.Infix, [Src.Comment]) infix_ = let err = E.Infix _err = \_ -> E.Infix in do start <- getPosition Keyword.infix_ err Space.chompAndCheckIndent _err err associativity <- oneOf err [ Keyword.left_ err >> return Binop.Left, Keyword.right_ err >> return Binop.Right, Keyword.non_ err >> return Binop.Non ] Space.chompAndCheckIndent _err err precedence <- Number.precedence err Space.chompAndCheckIndent _err err op <- Symbol.operator err _err Space.chompAndCheckIndent _err err Space.chompAndCheckIndent _err err name <- Var.lower err end <- getPosition commentsAfter <- Space.chomp _err Space.checkFreshLine err return (A.at start end (Src.Infix op associativity precedence name), commentsAfter)
b7ff7a2800bc5e39da05338aa2d409e55a6b4ed141852478b7c826c0548d8235
anton-k/processing-for-haskell
Star.hs
-- original code: Star -- -- The star() function created for this example is capable of drawing -- a wide range of different forms. Try placing different numbers into -- the star() function calls within draw() to explore. import Graphics.Proc main = runProc $ def { procSetup = setup, procDraw = draw } width = 640 height = 360 setup = do smooth size (P2 width height) draw() = do background (grey 102) fill (grey 250) Triangle Icosahedron Heptagon the function ` local ` is equivalent of pair of pushMatrix and popMatrix . -- We specify the scope of local transformation with indentation. drawPoly center speed radius npoints = local $ do translate center n <- frameCount rotate (float n * speed); poly (P2 0 0) radius npoints poly center radius npoints = polygon $ fmap (onCircle radius center) [0, 1/npoints .. 1] star center radius npoints = undefined -- not convex polygons are not implemented yet (todo)
null
https://raw.githubusercontent.com/anton-k/processing-for-haskell/7f99414f3c266135b6a2848978fcb572fd7b67b1/examples/Form/Star.hs
haskell
original code: The star() function created for this example is capable of drawing a wide range of different forms. Try placing different numbers into the star() function calls within draw() to explore. We specify the scope of local transformation with indentation. not convex polygons are not implemented yet (todo)
Star import Graphics.Proc main = runProc $ def { procSetup = setup, procDraw = draw } width = 640 height = 360 setup = do smooth size (P2 width height) draw() = do background (grey 102) fill (grey 250) Triangle Icosahedron Heptagon the function ` local ` is equivalent of pair of pushMatrix and popMatrix . drawPoly center speed radius npoints = local $ do translate center n <- frameCount rotate (float n * speed); poly (P2 0 0) radius npoints poly center radius npoints = polygon $ fmap (onCircle radius center) [0, 1/npoints .. 1] star center radius npoints = undefined
207f7798aa0856e179651764ddf34e8fae7c1d9b1aff95291ae68f7114bb9a0d
static-clouds/hlisp
Parse.hs
module HLisp.Parse where import Text.Parsec hiding (letter) import Text.Parsec.Char (alphaNum) import HLisp.Tokenize hiding (Parser) data VariableValue = I Int | S String | B Bool deriving (Eq, Show) type Pos = (SourcePos, SourcePos) data Exp = Identifier (Maybe Pos) String | SExp (Maybe Pos) [Exp] | Literal (Maybe Pos) VariableValue deriving Show data TopLevelExp = Blank | Directive | TopLevelExp Exp deriving Show type Parser = Parsec String () getSourcePos :: Monad m => ParsecT s u m SourcePos getSourcePos = fmap statePos getParserState sexpBody :: Parser [Exp] sexpBody = do option [] $ many whitespace sepBy expression $ many whitespace sexp :: Parser Exp sexp = do string "(" sexpStartPos <- getSourcePos sexpBodyObj <- sexpBody string ")" sexpEndPos <- getSourcePos return $ SExp (Just (sexpStartPos, sexpEndPos)) sexpBodyObj int :: Parser Int int = read <$> many1 digit bool :: Parser Bool bool = True <$ string "true" <|> False <$ string "false" literal :: Parser Exp literal = do startPos <- getSourcePos value <- I <$> int <|> B <$> bool -- <|> S <$> string' endPos <- getSourcePos return $ Literal (Just (startPos, endPos)) value directive :: Parser TopLevelExp directive = do string "#lang racket" return Directive identifierExp :: Parser Exp identifierExp = do startPos <- getSourcePos (TIdentifier value) <- identifier endPos <- getSourcePos return $ Identifier (Just (startPos, endPos)) value expression :: Parser Exp expression = identifierExp <|> sexp <|> literal blank :: Parser TopLevelExp blank = do string "" return Blank expressions :: Parser [TopLevelExp] expressions = do sepBy topLevelExpression whitespace where topLevelExpression = choice [directive, TopLevelExp <$> expression, blank]
null
https://raw.githubusercontent.com/static-clouds/hlisp/66c30a35c13b896488c59da83bb90b81b3c12b7b/src/HLisp/Parse.hs
haskell
<|> S <$> string'
module HLisp.Parse where import Text.Parsec hiding (letter) import Text.Parsec.Char (alphaNum) import HLisp.Tokenize hiding (Parser) data VariableValue = I Int | S String | B Bool deriving (Eq, Show) type Pos = (SourcePos, SourcePos) data Exp = Identifier (Maybe Pos) String | SExp (Maybe Pos) [Exp] | Literal (Maybe Pos) VariableValue deriving Show data TopLevelExp = Blank | Directive | TopLevelExp Exp deriving Show type Parser = Parsec String () getSourcePos :: Monad m => ParsecT s u m SourcePos getSourcePos = fmap statePos getParserState sexpBody :: Parser [Exp] sexpBody = do option [] $ many whitespace sepBy expression $ many whitespace sexp :: Parser Exp sexp = do string "(" sexpStartPos <- getSourcePos sexpBodyObj <- sexpBody string ")" sexpEndPos <- getSourcePos return $ SExp (Just (sexpStartPos, sexpEndPos)) sexpBodyObj int :: Parser Int int = read <$> many1 digit bool :: Parser Bool bool = True <$ string "true" <|> False <$ string "false" literal :: Parser Exp literal = do startPos <- getSourcePos endPos <- getSourcePos return $ Literal (Just (startPos, endPos)) value directive :: Parser TopLevelExp directive = do string "#lang racket" return Directive identifierExp :: Parser Exp identifierExp = do startPos <- getSourcePos (TIdentifier value) <- identifier endPos <- getSourcePos return $ Identifier (Just (startPos, endPos)) value expression :: Parser Exp expression = identifierExp <|> sexp <|> literal blank :: Parser TopLevelExp blank = do string "" return Blank expressions :: Parser [TopLevelExp] expressions = do sepBy topLevelExpression whitespace where topLevelExpression = choice [directive, TopLevelExp <$> expression, blank]
08054ce9db1fc27f9d7e60550e4597afe999ece55509d68b6cc8d47da249231e
exercism/babashka
nucleotide_count.clj
(ns nucleotide-count) (def ^{:private :const} dna-nucleotides #{\A \C \G \T}) (def ^{:private :const} base-count (zipmap dna-nucleotides (repeat 0))) (defn nucleotide-counts "generate a map of counts per nucleotide in strand" [strand] (into base-count (frequencies strand))) (defn count-of-nucleotide-in-strand "count occurrences of nucleotide in strand" [nucleotide strand] (or ((nucleotide-counts strand) nucleotide) (throw (Exception. (str "invalid nucleotide '" nucleotide "'")))))
null
https://raw.githubusercontent.com/exercism/babashka/707356c52e08490e66cb1b2e63e4f4439d91cf08/exercises/practice/nucleotide-count/src/nucleotide_count.clj
clojure
(ns nucleotide-count) (def ^{:private :const} dna-nucleotides #{\A \C \G \T}) (def ^{:private :const} base-count (zipmap dna-nucleotides (repeat 0))) (defn nucleotide-counts "generate a map of counts per nucleotide in strand" [strand] (into base-count (frequencies strand))) (defn count-of-nucleotide-in-strand "count occurrences of nucleotide in strand" [nucleotide strand] (or ((nucleotide-counts strand) nucleotide) (throw (Exception. (str "invalid nucleotide '" nucleotide "'")))))
2d0d760c362a0deb123d382dcda80ae97a73b2dc0c203773674949316c0b6048
MinaProtocol/mina
sok_message.ml
open Core_kernel open Mina_base_util open Mina_base_import module Wire_types = Mina_wire_types.Mina_base.Sok_message module Make_sig (A : Wire_types.Types.S) = struct module type S = Sok_message_intf.Full with type Digest.t = A.Digest.V1.t end module Make_str (A : Wire_types.Concrete) = struct [%%versioned module Stable = struct module V1 = struct type t = { fee : Currency.Fee.Stable.V1.t ; prover : Public_key.Compressed.Stable.V1.t } [@@deriving sexp, yojson, equal, compare] let to_latest = Fn.id end end] let create ~fee ~prover = Stable.Latest.{ fee; prover } module Digest = struct let length_in_bytes = Blake2.digest_size_in_bytes [%%versioned_binable module Stable = struct module V1 = struct type t = string [@@deriving sexp, hash, compare, equal, yojson] let to_latest = Fn.id include Binable.Of_binable_without_uuid (Core_kernel.String.Stable.V1) (struct type nonrec t = t let to_binable = Fn.id let of_binable s = assert (String.length s = length_in_bytes) ; s end) open Snark_params.Tick let to_input t = Random_oracle.Input.Chunked.packeds (Array.of_list_map Fold_lib.Fold.(to_list (string_bits t)) ~f:(fun b -> (field_of_bool b, 1)) ) let typ = Typ.array ~length:Blake2.digest_size_in_bits Boolean.typ |> Typ.transport ~there:Blake2.string_to_bits ~back:Blake2.bits_to_string end end] module Checked = struct open Snark_params.Tick type t = Boolean.var array let to_input (t : t) = Random_oracle.Input.Chunked.packeds (Array.map t ~f:(fun b -> ((b :> Field.Var.t), 1))) end [%%define_locally Stable.Latest.(to_input, typ)] let default = String.init length_in_bytes ~f:(fun _ -> '\000') end let digest t = Blake2.to_raw_string (Blake2.digest_string (Binable.to_string (module Stable.Latest) t)) end include Wire_types.Make (Make_sig) (Make_str)
null
https://raw.githubusercontent.com/MinaProtocol/mina/7a380064e215dc6aa152b76a7c3254949e383b1f/src/lib/mina_base/sok_message.ml
ocaml
open Core_kernel open Mina_base_util open Mina_base_import module Wire_types = Mina_wire_types.Mina_base.Sok_message module Make_sig (A : Wire_types.Types.S) = struct module type S = Sok_message_intf.Full with type Digest.t = A.Digest.V1.t end module Make_str (A : Wire_types.Concrete) = struct [%%versioned module Stable = struct module V1 = struct type t = { fee : Currency.Fee.Stable.V1.t ; prover : Public_key.Compressed.Stable.V1.t } [@@deriving sexp, yojson, equal, compare] let to_latest = Fn.id end end] let create ~fee ~prover = Stable.Latest.{ fee; prover } module Digest = struct let length_in_bytes = Blake2.digest_size_in_bytes [%%versioned_binable module Stable = struct module V1 = struct type t = string [@@deriving sexp, hash, compare, equal, yojson] let to_latest = Fn.id include Binable.Of_binable_without_uuid (Core_kernel.String.Stable.V1) (struct type nonrec t = t let to_binable = Fn.id let of_binable s = assert (String.length s = length_in_bytes) ; s end) open Snark_params.Tick let to_input t = Random_oracle.Input.Chunked.packeds (Array.of_list_map Fold_lib.Fold.(to_list (string_bits t)) ~f:(fun b -> (field_of_bool b, 1)) ) let typ = Typ.array ~length:Blake2.digest_size_in_bits Boolean.typ |> Typ.transport ~there:Blake2.string_to_bits ~back:Blake2.bits_to_string end end] module Checked = struct open Snark_params.Tick type t = Boolean.var array let to_input (t : t) = Random_oracle.Input.Chunked.packeds (Array.map t ~f:(fun b -> ((b :> Field.Var.t), 1))) end [%%define_locally Stable.Latest.(to_input, typ)] let default = String.init length_in_bytes ~f:(fun _ -> '\000') end let digest t = Blake2.to_raw_string (Blake2.digest_string (Binable.to_string (module Stable.Latest) t)) end include Wire_types.Make (Make_sig) (Make_str)
c8a950efa06da07a28c3258e8198ac7e211b551b2f57624a7beac4220bdcf25f
forward/incanter-BLAS
distributions.clj
;;; distributions.clj -- A common distribution protocol with several implmentations. by May 10 , 2010 Changes added by Jun 24 , 2010 Copyright ( c ) , 2010 . All rights reserved . 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.htincanter.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. CHANGE LOG (ns #^{:doc "Probability functions (pdf, cdf, draw, etc.) for common distributions, and for collections, sets, and maps." :author "Mark M. Fredrickson and William Leung"} incanter.distributions (:import java.util.Random (cern.jet.random.tdouble Beta Binomial ChiSquare DoubleUniform Exponential Gamma NegativeBinomial Normal Poisson StudentT) (cern.jet.stat.tdouble Probability) (cern.jet.random.tdouble.engine DoubleMersenneTwister)) (:use [clojure.set :only (intersection difference)] [clojure.math.combinatorics :only (combinations)] [incanter.core :only (gamma pow regularized-beta)])) ;; NOTE: as of this writing, (doc pdf/cdf/...) do not show the doc strings. ;; including them for when this bug is fixed. (defprotocol Distribution " The distribution protocol defines operations on probability distributions. Distributions may be univariate (defined over scalars) or multivariate (defined over vectors). Distributions may be discrete or continuous. For a list of types that implement the protocol run (extenders Distribution). Implementations are provided for the various Clojure collection datatypes. See the example below for using the distribution methods on these types. See also: pdf, cdf, draw, support References: Examples: (support [1 3 4 2 1 3 4 2]) ; returns the set #{1 2 3 4} (draw [1 3 4 2 1 3 4 2]) ; returns a value from #{1 2 3 4} returns the value 1/3 returns the value 3/4 " (pdf [d v] " A function of the incanter.distribution.Distribution protocol. Returns the value of the probability density/mass function for the distribution d at support v. See also: Distribution, cdf, draw, support References: Examples: (pdf [2 1 2] 1) ; returns the value 1/3\n") (cdf [d v] " A function of the incanter.distribution.Distribution protocol. Returns the value of the cumulative density function for the distribution d at support v. See also: Distribution, pdf, draw, support References: Examples: returns the value 3/4 \n " ) (draw [d] " A function of the incanter.distribution.Distribution protocol. Returns a randomly drawn value from the support of distribution d. See also: Distribution, pdf, cdf, support Examples: (draw [1 3 4 2 1 3 4 2]) ; returns a value from #{1 2 3 4}\n") (support [d] " **** EXPERIMENTAL **** A function of the incanter.distribution.Distribution protocol. Returns the support of the probability distribution d. For discrete distributions, the support is a set (i.e. #{1 2 3}). For continuous distributions, the support is a 2 element vector describing the range. For example, the uniform distribution over the unit interval would return the vector [0 1]. This function is marked as experimental to note that the output format might need to adapt to more complex support structures. For example, what would best describe a mixture of continuous distributions? See also: Distribution, pdf, draw, support References: Examples: returns the value 3/4 \n " ) (mean [d] "mean") (variance [d] "variance") ) Notes : other possible methods include moment generating function , transformations / change of vars (defn- tabulate "Private tabulation function that works on any data type, not just numerical" [v] (let [f (frequencies v) total (reduce + (vals f))] (into {} (map (fn [[k v]] [k (/ v total)]) f)))) (defn- simple-cdf "Compute the CDF at a value by getting the support and adding up the values until you get to v (inclusive)" [d v] (reduce + (map #(pdf d %) (filter #(>= v %) (support d))))) ;; Extending all sequence types to be distributions (extend-type clojure.lang.Sequential Distribution (pdf [d v] (get (tabulate d) v 0)) TODO check comparable elements (draw [d] (nth d (rand-int (count d)))) ; (draw [d n] (repeatedly n #(draw d))) (support [d] (set d)) (mean [d] (if (or (empty? d) (not (every? #(isa? (class %) java.lang.Number) d))) nil (/ (reduce + d) (count d)))) (variance [d] (if (or (empty? d) (not (every? #(isa? (class %) java.lang.Number) d))) nil (let [mu (mean d)] (/ (reduce + (map #(* (- % mu) (- % mu)) d)) (count d))))) ) Sets ( e.g. # { 1 2 3 } ) are not seqs , so they need their own implementation (extend-type clojure.lang.APersistentSet Distribution (pdf [d v] (if (get d v) (/ 1 (count d)) 0)) (cdf [d v] (if-not (isa? (class d) clojure.lang.PersistentTreeSet) nil (cdf (vec d) v))) (draw [d] (nth (support d) (rand-int (count d)))) (support [d] d) (mean [d] (if (or (empty? d) (not (every? #(isa? (class %) java.lang.Number) d))) nil (/ (reduce + d) (count d)))) (variance [d] (if (or (empty? d) (not (every? #(isa? (class %) java.lang.Number) d))) nil (let [mu (mean d)] (/ (reduce + (map #(* (- % mu) (- % mu)) d)) (count d))))) ) (defn- take-to-first "Returns a lazy sequence of successive items from coll up to and including the point at which it (pred item) returns true. pred must be free of side-effects. src: -archive.com//msg25706.html" [pred coll] (lazy-seq (when-let [s (seq coll)] (if-not (pred (first s)) (cons (first s) (take-to-first pred (rest s))) (list (first s)))))) (defn roulette-wheel "Perform a roulette wheel selection given a list of frequencies" [freqs] (let [nfreqs (count freqs) tot (reduce + freqs)] (if (= tot 0) nil (let [dist (map #(/ % tot) freqs) rval (double (rand))] (loop [acc 0, i 0] (let [lb acc, ub (+ acc (nth dist i))] (cond (>= (+ i 1) nfreqs) i (and (>= rval lb) (< rval ub)) i :else (recur ub (+ i 1))))))))) ;; map extension takes values as frequencies (extend-type clojure.lang.APersistentMap Distribution (pdf [d v] (if-not (contains? d v) 0 (/ (get d v) (reduce + (vals d))))) (cdf [d v] (if-not (isa? (class d) clojure.lang.PersistentTreeMap) ; isa? stronger than instance? nil (let [nd (count (support d)) compd (.comparator d) fkey (first (keys d))] (cond (= nd 0) 0 (= nd 1) (if (= -1 (.compare compd v fkey)) 0 1) :else (let [upto (take-to-first #(= (key %) v) d)] (if-not (contains? d v) (if (= -1 (.compare compd v fkey)) 0 1) (/ (reduce + (vals upto)) (reduce + (vals d))))))))) (draw [d] (nth (keys d) (roulette-wheel (vals d)))) (support [d] (keys d)) (mean [d] (if (empty? d) nil (let [vs (vals d)] (if-not (every? #(isa? (class %) java.lang.Number) vs) nil (/ (reduce + vs) (count d)))))) (variance [d] (if (empty? d) nil (let [vs (vals d)] (if-not (every? #(isa? (class %) java.lang.Number) vs) nil (let [mu (mean d)] (/ (reduce + (map #(* (- (val %) mu) (- (val %) mu)) d)) (count d))))))) ) defrecord expands to have a ( contains ? ... ) ( or .contains method ) that causes ; a reflection warning. Note much to do about that for now. Perhaps it will be ; fixed in clojure.core later. (defrecord UniformInt [start end] Distribution (pdf [d v] (/ 1 (- end start))) (cdf [d v] (* v (pdf d v))) (draw [d] ; for simplicity, cast to BigInt to use the random bitstream a better implementation would handle different types differently (let [r (bigint (- end start)) TODO replace with reused , threadsafe random rejection sampler , P(accept ) > .5 , so do n't fret (if (< candidate end) candidate (recur (f)))))) (support [d] (range start end)) (mean [d] (/ (reduce + (support d)) (- end start))) (variance [d] (let [vals (support d) mu (mean vals)] (/ (reduce + (map #(* (- % mu) (- % mu)) vals)) (- end start)))) ) (defn integer-distribution " Create a uniform distribution over a set of integers over the (start, end] interval. An alternative method of creating a distribution would be to just use a sequence of integers (e.g. (draw (range 100000))). For large sequences, like the one in the example, using a sequence will be require realizing the entire sequence before a draw can be taken. This less efficient than computing random draws based on the end points of the distribution. Arguments: start The lowest end of the interval, such that (>= (draw d) start) is always true. (Default 0) end The value at the upper end of the interval, such that (> end (draw d)) is always true. Note the strict inequality. (Default 1) See also: pdf, cdf, draw, support References: (discrete) Examples: returns 1/10 for any value (draw (integer-distribution -5 5)) (draw (integer-distribution (bit-shift-left 2 1000))) ; probably a very large value " ([] (integer-distribution 0 1)) ([end] (integer-distribution 0 end)) ([start end] {:pre [(> end start)]} (UniformInt. start end))) ;;;; Combination Sampling: Draws from the nCk possible combinations ;;;; (defn- nCk [n k] (cond (or (< n 0) (< k 0) (< n k)) 0 (or (= k 0) (= n k)) 1 :else (/ (reduce * 1 (range (inc (- n k)) (inc n))) (reduce * 1 (range 1 (inc k)))))) (defn- decode-combinadic "Decodes a 0 to nCk - 1 integer into its combinadic form, a set of k-tuple of indices, where each index i is 0 < i < n - 1" [n k c] {:pre [(<= 0 c) (> (nCk n k) c)] } (loop [candidate (dec n) ks (range k 0 -1) remaining c tuple '()] (if (empty? ks) tuple ;; <- return value of function (let [k (first ks) v (first (filter #(>= remaining (nCk % k)) (range candidate (- k 2) -1)))] (assert (not (nil? v))) (recur v (rest ks) (- remaining (nCk v k)) (conj tuple v)))))) (defn- res-sampler "Get a sample from the nCk possible combinations. Uses a reservoir sample from Chapter 4 of Tille, Y. (2006). Sampling Algorithms. Springer, New York." [n k] (let [res (transient (into [] (range 0 k)))] (doall (map (fn [i] (if (< (/ k i) (rand)) (assoc! res (rand-int k) i))) (range k n))) (persistent! res))) defrecord expands to have a ( contains ? ... ) ( or .contains method ) that causes ; a reflection warning. Note much to do about that for now. Perhaps it will be ; fixed in clojure.core later. (defrecord Combination [n k u] Distribution (pdf [d v] (/ 1 (nCk n k))) (cdf [d v] nil) ; TODO: this requires encoding combinations (draw [d] (res-sampler n k)) (support [d] (map #(decode-combinadic n k %) (range 0 (nCk n k)))) (mean [d] nil) (variance [d] nil) ) (defn combination-distribution " Create a distribution of all the k-sized combinations of n integers. Can be considered a multivariate distribution over k-dimensions, where each dimension is a discrete random variable on the (0, n] range (though these variables are decidedly non-independent). A draw from this distribution can also be considered a sample without replacement from any finite set, where the values in the returned vector represent the indices of the items in the set. Arguments: n The number of possible items from which to select. k The size of a sample (without replacement) to draw. See also: test-statistic-distribution, integer-distribution, pdf, cdf, draw, support References: Examples: " [n k] {:pre [(>= n k) (and (<= 0 n) (<= 0 k))] } (Combination. n k (integer-distribution 0 (nCk n k)))) (def ^:dynamic *test-statistic-iterations* 1000) (def ^:dynamic *test-statistic-map* pmap) (defn test-statistic-distribution " Create a distribution of the test-statistic over the possible random samples of treatment units from the possible units. There are two methods for generating the distribution. The first method is enumerating all possible randomizations and performing the test statistic on each. This gives the exact distribution, but is only feasible for small problems. The second method uses a combination-distribution to sample for the space of possible treatment assignments and applies the test statistic the sampled randomizations. While the resulting distribution is not exact, it is tractable for larger problems. The algorithm automatically chooses between the two methods by computing the number of possible randomizations and comparing it to *test-statistic-iterations*. If the exact distribution requires fewer than *test-statistic-iterations* the enumeration method is used. Otherwise, it draws *test-statistic-iterations* total samples for the simulated method. By default, the algorithm uses parallel computation. This is controlled by the function *test-statistic-map*, which is bound to pmap by default. Bind it to map to use a single thread for computation. Arguments: test-statistic A function that takes two vectors and summarizes the difference between them n The number of total units in the pool k The number of treatment units per sample See also: combination-distribution, pdf, cdf, draw, support References: Examples: " [test-statistic n k] ; for now returns entire set of computed values, should summarize via frequencies (*test-statistic-map* test-statistic ; *t-s-m* is bound to pmap by default (let [cd (combination-distribution n k)] (if (> (nCk n k) *test-statistic-iterations*) ; simulated method (repeatedly *test-statistic-iterations* #(draw cd)) ; exact method (combinations (range 0 n) k))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; NORMAL DISTRIBUTION ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def inf+ Double/POSITIVE_INFINITY) (def inf- Double/NEGATIVE_INFINITY) ; NOTE: the pdf and cdf functions require a reflection call. They could be made ; to note reflect by type hinting the d argument: ; (fn [#^cern.jet.randome.tdouble.Normal d v] (.pdf d v)) ; for now, I'm skipping this optimization so that more distributions can be boostrapped ; quickly using the extenders map. This can be easily pulled out for each distribution ; later, and appropriate type hints inserted. (def colt-extenders {:pdf (fn [d v] (.pdf d v)) :cdf (fn [d v] (.cdf d v)) :draw (fn [#^cern.jet.random.tdouble.AbstractDoubleDistribution d] (.nextDouble d)) :support (fn [d] [inf-, inf+]) :mean (fn [d] nil) :variance (fn [d] nil)}) (defrecord Normal-rec [mean sd] Distribution (pdf [d v] (.pdf (Normal. mean sd (DoubleMersenneTwister.)) v)) (cdf [d v] (.cdf (Normal. mean sd (DoubleMersenneTwister.)) v)) (draw [d] (cern.jet.random.tdouble.Normal/staticNextDouble mean sd)) (support [d] [inf-, inf+]) (mean [d] mean) (variance [d] (* sd sd)) ) ; bootstrap by extending the colt object to implement this protocol future versions could implement a Box - Muller transform in clojure for ( draw ) ; I think clojure.contrib.probabilities would have an example implementation. ; I'm interested to know how pdf/cdf are implemented in colt... ;(extend cern.jet.random.tdouble.Normal Distribution colt-extenders) (defn normal-distribution " Returns a Normal distribution that implements the incanter.distributions.Distribution protocol. Arguments: mean The mean of the distribution. One of two parameters that summarize the Normal distribution (default 0). sd The standard deviation of the distribution. The second parameter that describes the Normal (default 1). See also: Distribution, pdf, cdf, draw, support References: Example: (pdf (normal-distribution -2 (sqrt 0.5)) 1.96) " ([] (normal-distribution 0 1)) ([mean sd] (Normal-rec. mean sd))) distributions created using code and default values from -core/src/incanter/stats.clj ;(extend cern.jet.random.tdouble.Beta Distribution colt-extenders) (defrecord Beta-rec [alpha beta] Distribution (pdf [d v] (.pdf (Beta. alpha beta (DoubleMersenneTwister.)) v)) (cdf [d v] (.cdf (Beta. alpha beta (DoubleMersenneTwister.)) v)) (draw [d] (cern.jet.random.tdouble.Beta/staticNextDouble alpha beta)) (support [d] [0,1]) (mean [d] (/ alpha (+ alpha beta))) (variance [d] (/ (* alpha beta) (* (+ alpha beta) (+ alpha beta) (+ alpha beta 1))))) (defn beta-distribution "Returns a Beta distribution that implements the incanter.distributions.Distribution protocol. Arguments: alpha (default 1) beta (default 1) See also: Distribution, pdf, cdf, draw, support References: Example: (pdf (beta-distribution 1 2) 0.5)" ([] (beta-distribution 1 1)) ([alpha beta] (Beta-rec. alpha beta))) ;(extend cern.jet.random.tdouble.Binomial Distribution colt-extenders) (defrecord Binomial-rec [n p] Distribution (pdf [d v] (.pdf (Binomial. n p (DoubleMersenneTwister.)) v)) (cdf [d v] (.cdf (Binomial. n p (DoubleMersenneTwister.)) v)) (draw [d] (cern.jet.random.tdouble.Binomial/staticNextInt n p)) (support [d] (range (+ n 1))) (mean [d] (* n p)) (variance [d] (* n p (- 1 p)))) (defn binomial-distribution "Returns a Binomial distribution that implements the incanter.distributions.Distribution protocol. Arguments: size (default 1) prob (default 1/2) See also: Distribution, pdf, cdf, draw, support References: Example: (pdf (binomial-distribution 20 1/4) 10)" ([] (binomial-distribution 1 1/2)) ([n p] (Binomial-rec. n p))) ( extend cern.jet.random.tdouble . ChiSquare Distribution colt - extenders ) (defrecord ChiSquare-rec [df] Distribution (pdf [d v] (.pdf (ChiSquare. df (DoubleMersenneTwister.)) v)) (cdf [d v] (.cdf (ChiSquare. df (DoubleMersenneTwister.)) v)) (draw [d] (cern.jet.random.tdouble.ChiSquare/staticNextDouble df)) (support [d] [0,inf+]) (mean [d] df) (variance [d] (* 2 df))) (defn chisq-distribution "Returns a Chi-square distribution that implements the incanter.distributions.Distribution protocol. Arguments: df (default 1) See also: Distribution, pdf, cdf, draw, support References: Example: (pdf (chisq-distribution 2) 5.0)" ([] (chisq-distribution 1)) ([df] (ChiSquare-rec. df))) ;(extend cern.jet.random.tdouble.Exponential Distribution colt-extenders) (defrecord Exponential-rec [rate] Distribution (pdf [d v] (.pdf (Exponential. rate (DoubleMersenneTwister.)) v)) (cdf [d v] (.cdf (Exponential. rate (DoubleMersenneTwister.)) v)) (draw [d] (cern.jet.random.tdouble.Exponential/staticNextDouble rate)) (support [d] [0,inf+]) (mean [d] (/ 1 rate)) (variance [d] (/ 1 (* rate rate)))) (defn exponential-distribution "Returns a Exponential distribution that implements the incanter.distributions.Distribution protocol. Arguments: rate (default 1) See also: Distribution, pdf, cdf, draw, support References: Example: (pdf (exponential-distribution 1/2) 2.0)" ([] (exponential-distribution 1)) ([rate] (Exponential-rec. rate))) (defrecord F [df1 df2] Distribution (pdf [d v] (* (/ (gamma (/ (+ df1 df2) 2)) (* (gamma (/ df1 2)) (gamma (/ df2 2)))) (pow (/ df1 df2) (/ df1 2)) (pow v (- (/ df1 2) 1)) (pow (+ 1 (* (/ df1 df2) v)) (- 0 (/ (+ df1 df2) 2))))) TODO decide on : lower - tail (/ (* df1 v) (+ df2 (* df1 v))) (/ df1 2) (/ df2 2))) TODO (support [d] [0,inf+]) (mean [d] (if (> df2 2) (/ df2 (- df2 2)) nil)) (variance [d] (if (> df2 4) (/ (* 2 df2 df2 (+ df1 df2 -2)) (* df1 (- df2 2) (- df2 2) (- df2 4))))) ) (defn f-distribution "Returns a F-distribution that implements the incanter.distributions.Distribution protocol. Arguments: df1 (default 1) df2 (default 1) See also: Distribution, pdf, cdf, draw, support References: -Distribution.html Example: (pdf (f-distribution 5 2) 1.0)" ([] (f-distribution 1 1)) ([df1 df2] (F. df1 df2))) using defrecord since cdf was not matching up in unittest without switching " : lower - tail " Distribution (pdf [d v] (.pdf (Gamma. shape rate (DoubleMersenneTwister.)) v)) TODO decide on : lower - tail (draw [d] (cern.jet.random.tdouble.Gamma/staticNextDouble shape rate)) (support [d] [0,inf+]) (mean [d] (* shape rate)) (variance [d] (* shape rate rate)) ) ( extend cern.jet.random.tdouble . Gamma Distribution colt - extenders ) (defn gamma-distribution "Returns a Gamma distribution that implements the incanter.distributions.Distribution protocol. Arguments: shape (default 1) rate (default 1) See also: Distribution, pdf, cdf, draw, support References: Example: (pdf (gamma-distribution 1 2) 10)" ([] (gamma-distribution 1 1)) ([shape rate] (Gamma-rec. shape rate))) ( extend cern.jet.random.tdouble . NegativeBinomial Distribution colt - extenders ) (defrecord NegativeBinomial-rec [size prob] Distribution (pdf [d v] (.pdf (NegativeBinomial. size prob (DoubleMersenneTwister.)) v)) (cdf [d v] (.cdf (NegativeBinomial. size prob (DoubleMersenneTwister.)) v)) (draw [d] (cern.jet.random.tdouble.NegativeBinomial/staticNextInt size prob)) (support [d] [0,inf+]) (mean [d] (/ (* size prob) (- 1 prob))) (variance [d] (/ (* size prob) (* (- 1 prob) (- 1 prob))))) (defn neg-binomial-distribution "Returns a Negative binomial distribution that implements the incanter.distributions.Distribution protocol. Arguments: size (default 10) prob (default 1/2) See also: Distribution, pdf, cdf, draw, support References: Example: (pdf (neg-binomial-distribution 20 1/2) 10)" ([] (neg-binomial-distribution 10 1/2)) ([size prob] (NegativeBinomial-rec. size prob))) ;(extend cern.jet.random.tdouble.Poisson Distribution colt-extenders) (defrecord Poisson-rec [lambda] Distribution (pdf [d v] (.pdf (Poisson. lambda (DoubleMersenneTwister.)) v)) (cdf [d v] (.cdf (Poisson. lambda (DoubleMersenneTwister.)) v)) (draw [d] (cern.jet.random.tdouble.Poisson/staticNextInt lambda)) (support [d] [0,inf+]) (mean [d] lambda) (variance [d] lambda)) (defn poisson-distribution "Returns a Poisson distribution that implements the incanter.distributions.Distribution protocol. Arguments: lambda (default 1) See also: Distribution, pdf, cdf, draw, support References: Example: (pdf (poisson-distribution 10) 5)" ([] (poisson-distribution 1)) ([lambda] (Poisson-rec. lambda))) ;(extend cern.jet.random.tdouble.StudentT Distribution colt-extenders) (defrecord StudentT-rec [df] Distribution (pdf [d v] (.pdf (StudentT. df (DoubleMersenneTwister.)) v)) (cdf [d v] (.cdf (StudentT. df (DoubleMersenneTwister.)) v)) (draw [d] (cern.jet.random.tdouble.StudentT/staticNextDouble df)) (support [d] [inf-,inf+]) (mean [d] (if (> df 1) 0 nil)) (variance [d] (cond (> df 2) (/ df (- df 2)) (and (> df 1) (<= df 2)) inf+ :else nil))) (defn t-distribution "Returns a Student-t distribution that implements the incanter.distributions.Distribution protocol. Arguments: df (default 1) See also: Distribution, pdf, cdf, draw, support References: -t_distribution Example: (pdf (t-distribution 10) 1.2)" ([] (t-distribution 1)) ([df] (StudentT-rec. df))) ( extend cern.jet.random.tdouble . colt - extenders ) (defrecord DoubleUniform-rec [min max] Distribution (pdf [d v] (.pdf (DoubleUniform. min max (DoubleMersenneTwister.)) v)) (cdf [d v] (.cdf (DoubleUniform. min max (DoubleMersenneTwister.)) v)) (draw [d] (cern.jet.random.tdouble.DoubleUniform/staticNextDouble)) (support [d] [min,max]) (mean [d] (/ (+ min max) 2)) (variance [d] (/ (* (- max min) (- max min)) 12))) (defn uniform-distribution "Returns a Uniform distribution that implements the incanter.distributions.Distribution protocol. Arguments: min (default 0) max (default 1) See also: Distribution, pdf, cdf, draw, support References: Example: (pdf (uniform-distribution 1.0 10.0) 5)" since " 0 1 " not implicitly promoted , otheriwse no matching ctor ... ([min max] (DoubleUniform-rec. min max)))
null
https://raw.githubusercontent.com/forward/incanter-BLAS/da48558cc9d8296b775d8e88de532a4897ee966e/src/main/clojure/incanter/distributions.clj
clojure
distributions.clj -- A common distribution protocol with several implmentations. Public License 1.0 (-1.0.php) which can be found in the file epl-v10.htincanter.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. NOTE: as of this writing, (doc pdf/cdf/...) do not show the doc strings. including them for when this bug is fixed. returns the set #{1 2 3 4} returns a value from #{1 2 3 4} returns the value 1/3\n") returns a value from #{1 2 3 4}\n") Extending all sequence types to be distributions (draw [d n] (repeatedly n #(draw d))) map extension takes values as frequencies isa? stronger than instance? a reflection warning. Note much to do about that for now. Perhaps it will be fixed in clojure.core later. for simplicity, cast to BigInt to use the random bitstream a better implementation would handle different types differently probably a very large value Combination Sampling: Draws from the nCk possible combinations ;;;; <- return value of function a reflection warning. Note much to do about that for now. Perhaps it will be fixed in clojure.core later. TODO: this requires encoding combinations for now returns entire set of computed values, should summarize via frequencies *t-s-m* is bound to pmap by default simulated method exact method NORMAL DISTRIBUTION NOTE: the pdf and cdf functions require a reflection call. They could be made to note reflect by type hinting the d argument: (fn [#^cern.jet.randome.tdouble.Normal d v] (.pdf d v)) for now, I'm skipping this optimization so that more distributions can be boostrapped quickly using the extenders map. This can be easily pulled out for each distribution later, and appropriate type hints inserted. bootstrap by extending the colt object to implement this protocol I think clojure.contrib.probabilities would have an example implementation. I'm interested to know how pdf/cdf are implemented in colt... (extend cern.jet.random.tdouble.Normal Distribution colt-extenders) (extend cern.jet.random.tdouble.Beta Distribution colt-extenders) (extend cern.jet.random.tdouble.Binomial Distribution colt-extenders) (extend cern.jet.random.tdouble.Exponential Distribution colt-extenders) (extend cern.jet.random.tdouble.Poisson Distribution colt-extenders) (extend cern.jet.random.tdouble.StudentT Distribution colt-extenders)
by May 10 , 2010 Changes added by Jun 24 , 2010 Copyright ( c ) , 2010 . All rights reserved . The use and distribution terms for this software are covered by the Eclipse CHANGE LOG (ns #^{:doc "Probability functions (pdf, cdf, draw, etc.) for common distributions, and for collections, sets, and maps." :author "Mark M. Fredrickson and William Leung"} incanter.distributions (:import java.util.Random (cern.jet.random.tdouble Beta Binomial ChiSquare DoubleUniform Exponential Gamma NegativeBinomial Normal Poisson StudentT) (cern.jet.stat.tdouble Probability) (cern.jet.random.tdouble.engine DoubleMersenneTwister)) (:use [clojure.set :only (intersection difference)] [clojure.math.combinatorics :only (combinations)] [incanter.core :only (gamma pow regularized-beta)])) (defprotocol Distribution " The distribution protocol defines operations on probability distributions. Distributions may be univariate (defined over scalars) or multivariate (defined over vectors). Distributions may be discrete or continuous. For a list of types that implement the protocol run (extenders Distribution). Implementations are provided for the various Clojure collection datatypes. See the example below for using the distribution methods on these types. See also: pdf, cdf, draw, support References: Examples: returns the value 1/3 returns the value 3/4 " (pdf [d v] " A function of the incanter.distribution.Distribution protocol. Returns the value of the probability density/mass function for the distribution d at support v. See also: Distribution, cdf, draw, support References: Examples: (cdf [d v] " A function of the incanter.distribution.Distribution protocol. Returns the value of the cumulative density function for the distribution d at support v. See also: Distribution, pdf, draw, support References: Examples: returns the value 3/4 \n " ) (draw [d] " A function of the incanter.distribution.Distribution protocol. Returns a randomly drawn value from the support of distribution d. See also: Distribution, pdf, cdf, support Examples: (support [d] " **** EXPERIMENTAL **** A function of the incanter.distribution.Distribution protocol. Returns the support of the probability distribution d. For discrete distributions, the support is a set (i.e. #{1 2 3}). For continuous distributions, the support is a 2 element vector describing the range. For example, the uniform distribution over the unit interval would return the vector [0 1]. This function is marked as experimental to note that the output format might need to adapt to more complex support structures. For example, what would best describe a mixture of continuous distributions? See also: Distribution, pdf, draw, support References: Examples: returns the value 3/4 \n " ) (mean [d] "mean") (variance [d] "variance") ) Notes : other possible methods include moment generating function , transformations / change of vars (defn- tabulate "Private tabulation function that works on any data type, not just numerical" [v] (let [f (frequencies v) total (reduce + (vals f))] (into {} (map (fn [[k v]] [k (/ v total)]) f)))) (defn- simple-cdf "Compute the CDF at a value by getting the support and adding up the values until you get to v (inclusive)" [d v] (reduce + (map #(pdf d %) (filter #(>= v %) (support d))))) (extend-type clojure.lang.Sequential Distribution (pdf [d v] (get (tabulate d) v 0)) TODO check comparable elements (draw [d] (nth d (rand-int (count d)))) (support [d] (set d)) (mean [d] (if (or (empty? d) (not (every? #(isa? (class %) java.lang.Number) d))) nil (/ (reduce + d) (count d)))) (variance [d] (if (or (empty? d) (not (every? #(isa? (class %) java.lang.Number) d))) nil (let [mu (mean d)] (/ (reduce + (map #(* (- % mu) (- % mu)) d)) (count d))))) ) Sets ( e.g. # { 1 2 3 } ) are not seqs , so they need their own implementation (extend-type clojure.lang.APersistentSet Distribution (pdf [d v] (if (get d v) (/ 1 (count d)) 0)) (cdf [d v] (if-not (isa? (class d) clojure.lang.PersistentTreeSet) nil (cdf (vec d) v))) (draw [d] (nth (support d) (rand-int (count d)))) (support [d] d) (mean [d] (if (or (empty? d) (not (every? #(isa? (class %) java.lang.Number) d))) nil (/ (reduce + d) (count d)))) (variance [d] (if (or (empty? d) (not (every? #(isa? (class %) java.lang.Number) d))) nil (let [mu (mean d)] (/ (reduce + (map #(* (- % mu) (- % mu)) d)) (count d))))) ) (defn- take-to-first "Returns a lazy sequence of successive items from coll up to and including the point at which it (pred item) returns true. pred must be free of side-effects. src: -archive.com//msg25706.html" [pred coll] (lazy-seq (when-let [s (seq coll)] (if-not (pred (first s)) (cons (first s) (take-to-first pred (rest s))) (list (first s)))))) (defn roulette-wheel "Perform a roulette wheel selection given a list of frequencies" [freqs] (let [nfreqs (count freqs) tot (reduce + freqs)] (if (= tot 0) nil (let [dist (map #(/ % tot) freqs) rval (double (rand))] (loop [acc 0, i 0] (let [lb acc, ub (+ acc (nth dist i))] (cond (>= (+ i 1) nfreqs) i (and (>= rval lb) (< rval ub)) i :else (recur ub (+ i 1))))))))) (extend-type clojure.lang.APersistentMap Distribution (pdf [d v] (if-not (contains? d v) 0 (/ (get d v) (reduce + (vals d))))) nil (let [nd (count (support d)) compd (.comparator d) fkey (first (keys d))] (cond (= nd 0) 0 (= nd 1) (if (= -1 (.compare compd v fkey)) 0 1) :else (let [upto (take-to-first #(= (key %) v) d)] (if-not (contains? d v) (if (= -1 (.compare compd v fkey)) 0 1) (/ (reduce + (vals upto)) (reduce + (vals d))))))))) (draw [d] (nth (keys d) (roulette-wheel (vals d)))) (support [d] (keys d)) (mean [d] (if (empty? d) nil (let [vs (vals d)] (if-not (every? #(isa? (class %) java.lang.Number) vs) nil (/ (reduce + vs) (count d)))))) (variance [d] (if (empty? d) nil (let [vs (vals d)] (if-not (every? #(isa? (class %) java.lang.Number) vs) nil (let [mu (mean d)] (/ (reduce + (map #(* (- (val %) mu) (- (val %) mu)) d)) (count d))))))) ) defrecord expands to have a ( contains ? ... ) ( or .contains method ) that causes (defrecord UniformInt [start end] Distribution (pdf [d v] (/ 1 (- end start))) (cdf [d v] (* v (pdf d v))) (let [r (bigint (- end start)) TODO replace with reused , threadsafe random rejection sampler , P(accept ) > .5 , so do n't fret (if (< candidate end) candidate (recur (f)))))) (support [d] (range start end)) (mean [d] (/ (reduce + (support d)) (- end start))) (variance [d] (let [vals (support d) mu (mean vals)] (/ (reduce + (map #(* (- % mu) (- % mu)) vals)) (- end start)))) ) (defn integer-distribution " Create a uniform distribution over a set of integers over the (start, end] interval. An alternative method of creating a distribution would be to just use a sequence of integers (e.g. (draw (range 100000))). For large sequences, like the one in the example, using a sequence will be require realizing the entire sequence before a draw can be taken. This less efficient than computing random draws based on the end points of the distribution. Arguments: start The lowest end of the interval, such that (>= (draw d) start) is always true. (Default 0) end The value at the upper end of the interval, such that (> end (draw d)) is always true. Note the strict inequality. (Default 1) See also: pdf, cdf, draw, support References: (discrete) Examples: returns 1/10 for any value (draw (integer-distribution -5 5)) " ([] (integer-distribution 0 1)) ([end] (integer-distribution 0 end)) ([start end] {:pre [(> end start)]} (UniformInt. start end))) (defn- nCk [n k] (cond (or (< n 0) (< k 0) (< n k)) 0 (or (= k 0) (= n k)) 1 :else (/ (reduce * 1 (range (inc (- n k)) (inc n))) (reduce * 1 (range 1 (inc k)))))) (defn- decode-combinadic "Decodes a 0 to nCk - 1 integer into its combinadic form, a set of k-tuple of indices, where each index i is 0 < i < n - 1" [n k c] {:pre [(<= 0 c) (> (nCk n k) c)] } (loop [candidate (dec n) ks (range k 0 -1) remaining c tuple '()] (let [k (first ks) v (first (filter #(>= remaining (nCk % k)) (range candidate (- k 2) -1)))] (assert (not (nil? v))) (recur v (rest ks) (- remaining (nCk v k)) (conj tuple v)))))) (defn- res-sampler "Get a sample from the nCk possible combinations. Uses a reservoir sample from Chapter 4 of Tille, Y. (2006). Sampling Algorithms. Springer, New York." [n k] (let [res (transient (into [] (range 0 k)))] (doall (map (fn [i] (if (< (/ k i) (rand)) (assoc! res (rand-int k) i))) (range k n))) (persistent! res))) defrecord expands to have a ( contains ? ... ) ( or .contains method ) that causes (defrecord Combination [n k u] Distribution (pdf [d v] (/ 1 (nCk n k))) (draw [d] (res-sampler n k)) (support [d] (map #(decode-combinadic n k %) (range 0 (nCk n k)))) (mean [d] nil) (variance [d] nil) ) (defn combination-distribution " Create a distribution of all the k-sized combinations of n integers. Can be considered a multivariate distribution over k-dimensions, where each dimension is a discrete random variable on the (0, n] range (though these variables are decidedly non-independent). A draw from this distribution can also be considered a sample without replacement from any finite set, where the values in the returned vector represent the indices of the items in the set. Arguments: n The number of possible items from which to select. k The size of a sample (without replacement) to draw. See also: test-statistic-distribution, integer-distribution, pdf, cdf, draw, support References: Examples: " [n k] {:pre [(>= n k) (and (<= 0 n) (<= 0 k))] } (Combination. n k (integer-distribution 0 (nCk n k)))) (def ^:dynamic *test-statistic-iterations* 1000) (def ^:dynamic *test-statistic-map* pmap) (defn test-statistic-distribution " Create a distribution of the test-statistic over the possible random samples of treatment units from the possible units. There are two methods for generating the distribution. The first method is enumerating all possible randomizations and performing the test statistic on each. This gives the exact distribution, but is only feasible for small problems. The second method uses a combination-distribution to sample for the space of possible treatment assignments and applies the test statistic the sampled randomizations. While the resulting distribution is not exact, it is tractable for larger problems. The algorithm automatically chooses between the two methods by computing the number of possible randomizations and comparing it to *test-statistic-iterations*. If the exact distribution requires fewer than *test-statistic-iterations* the enumeration method is used. Otherwise, it draws *test-statistic-iterations* total samples for the simulated method. By default, the algorithm uses parallel computation. This is controlled by the function *test-statistic-map*, which is bound to pmap by default. Bind it to map to use a single thread for computation. Arguments: test-statistic A function that takes two vectors and summarizes the difference between them n The number of total units in the pool k The number of treatment units per sample See also: combination-distribution, pdf, cdf, draw, support References: Examples: " [test-statistic n k] (let [cd (combination-distribution n k)] (if (> (nCk n k) *test-statistic-iterations*) (repeatedly *test-statistic-iterations* #(draw cd)) (combinations (range 0 n) k))))) (def inf+ Double/POSITIVE_INFINITY) (def inf- Double/NEGATIVE_INFINITY) (def colt-extenders {:pdf (fn [d v] (.pdf d v)) :cdf (fn [d v] (.cdf d v)) :draw (fn [#^cern.jet.random.tdouble.AbstractDoubleDistribution d] (.nextDouble d)) :support (fn [d] [inf-, inf+]) :mean (fn [d] nil) :variance (fn [d] nil)}) (defrecord Normal-rec [mean sd] Distribution (pdf [d v] (.pdf (Normal. mean sd (DoubleMersenneTwister.)) v)) (cdf [d v] (.cdf (Normal. mean sd (DoubleMersenneTwister.)) v)) (draw [d] (cern.jet.random.tdouble.Normal/staticNextDouble mean sd)) (support [d] [inf-, inf+]) (mean [d] mean) (variance [d] (* sd sd)) ) future versions could implement a Box - Muller transform in clojure for ( draw ) (defn normal-distribution " Returns a Normal distribution that implements the incanter.distributions.Distribution protocol. Arguments: mean The mean of the distribution. One of two parameters that summarize the Normal distribution (default 0). sd The standard deviation of the distribution. The second parameter that describes the Normal (default 1). See also: Distribution, pdf, cdf, draw, support References: Example: (pdf (normal-distribution -2 (sqrt 0.5)) 1.96) " ([] (normal-distribution 0 1)) ([mean sd] (Normal-rec. mean sd))) distributions created using code and default values from -core/src/incanter/stats.clj (defrecord Beta-rec [alpha beta] Distribution (pdf [d v] (.pdf (Beta. alpha beta (DoubleMersenneTwister.)) v)) (cdf [d v] (.cdf (Beta. alpha beta (DoubleMersenneTwister.)) v)) (draw [d] (cern.jet.random.tdouble.Beta/staticNextDouble alpha beta)) (support [d] [0,1]) (mean [d] (/ alpha (+ alpha beta))) (variance [d] (/ (* alpha beta) (* (+ alpha beta) (+ alpha beta) (+ alpha beta 1))))) (defn beta-distribution "Returns a Beta distribution that implements the incanter.distributions.Distribution protocol. Arguments: alpha (default 1) beta (default 1) See also: Distribution, pdf, cdf, draw, support References: Example: (pdf (beta-distribution 1 2) 0.5)" ([] (beta-distribution 1 1)) ([alpha beta] (Beta-rec. alpha beta))) (defrecord Binomial-rec [n p] Distribution (pdf [d v] (.pdf (Binomial. n p (DoubleMersenneTwister.)) v)) (cdf [d v] (.cdf (Binomial. n p (DoubleMersenneTwister.)) v)) (draw [d] (cern.jet.random.tdouble.Binomial/staticNextInt n p)) (support [d] (range (+ n 1))) (mean [d] (* n p)) (variance [d] (* n p (- 1 p)))) (defn binomial-distribution "Returns a Binomial distribution that implements the incanter.distributions.Distribution protocol. Arguments: size (default 1) prob (default 1/2) See also: Distribution, pdf, cdf, draw, support References: Example: (pdf (binomial-distribution 20 1/4) 10)" ([] (binomial-distribution 1 1/2)) ([n p] (Binomial-rec. n p))) ( extend cern.jet.random.tdouble . ChiSquare Distribution colt - extenders ) (defrecord ChiSquare-rec [df] Distribution (pdf [d v] (.pdf (ChiSquare. df (DoubleMersenneTwister.)) v)) (cdf [d v] (.cdf (ChiSquare. df (DoubleMersenneTwister.)) v)) (draw [d] (cern.jet.random.tdouble.ChiSquare/staticNextDouble df)) (support [d] [0,inf+]) (mean [d] df) (variance [d] (* 2 df))) (defn chisq-distribution "Returns a Chi-square distribution that implements the incanter.distributions.Distribution protocol. Arguments: df (default 1) See also: Distribution, pdf, cdf, draw, support References: Example: (pdf (chisq-distribution 2) 5.0)" ([] (chisq-distribution 1)) ([df] (ChiSquare-rec. df))) (defrecord Exponential-rec [rate] Distribution (pdf [d v] (.pdf (Exponential. rate (DoubleMersenneTwister.)) v)) (cdf [d v] (.cdf (Exponential. rate (DoubleMersenneTwister.)) v)) (draw [d] (cern.jet.random.tdouble.Exponential/staticNextDouble rate)) (support [d] [0,inf+]) (mean [d] (/ 1 rate)) (variance [d] (/ 1 (* rate rate)))) (defn exponential-distribution "Returns a Exponential distribution that implements the incanter.distributions.Distribution protocol. Arguments: rate (default 1) See also: Distribution, pdf, cdf, draw, support References: Example: (pdf (exponential-distribution 1/2) 2.0)" ([] (exponential-distribution 1)) ([rate] (Exponential-rec. rate))) (defrecord F [df1 df2] Distribution (pdf [d v] (* (/ (gamma (/ (+ df1 df2) 2)) (* (gamma (/ df1 2)) (gamma (/ df2 2)))) (pow (/ df1 df2) (/ df1 2)) (pow v (- (/ df1 2) 1)) (pow (+ 1 (* (/ df1 df2) v)) (- 0 (/ (+ df1 df2) 2))))) TODO decide on : lower - tail (/ (* df1 v) (+ df2 (* df1 v))) (/ df1 2) (/ df2 2))) TODO (support [d] [0,inf+]) (mean [d] (if (> df2 2) (/ df2 (- df2 2)) nil)) (variance [d] (if (> df2 4) (/ (* 2 df2 df2 (+ df1 df2 -2)) (* df1 (- df2 2) (- df2 2) (- df2 4))))) ) (defn f-distribution "Returns a F-distribution that implements the incanter.distributions.Distribution protocol. Arguments: df1 (default 1) df2 (default 1) See also: Distribution, pdf, cdf, draw, support References: -Distribution.html Example: (pdf (f-distribution 5 2) 1.0)" ([] (f-distribution 1 1)) ([df1 df2] (F. df1 df2))) using defrecord since cdf was not matching up in unittest without switching " : lower - tail " Distribution (pdf [d v] (.pdf (Gamma. shape rate (DoubleMersenneTwister.)) v)) TODO decide on : lower - tail (draw [d] (cern.jet.random.tdouble.Gamma/staticNextDouble shape rate)) (support [d] [0,inf+]) (mean [d] (* shape rate)) (variance [d] (* shape rate rate)) ) ( extend cern.jet.random.tdouble . Gamma Distribution colt - extenders ) (defn gamma-distribution "Returns a Gamma distribution that implements the incanter.distributions.Distribution protocol. Arguments: shape (default 1) rate (default 1) See also: Distribution, pdf, cdf, draw, support References: Example: (pdf (gamma-distribution 1 2) 10)" ([] (gamma-distribution 1 1)) ([shape rate] (Gamma-rec. shape rate))) ( extend cern.jet.random.tdouble . NegativeBinomial Distribution colt - extenders ) (defrecord NegativeBinomial-rec [size prob] Distribution (pdf [d v] (.pdf (NegativeBinomial. size prob (DoubleMersenneTwister.)) v)) (cdf [d v] (.cdf (NegativeBinomial. size prob (DoubleMersenneTwister.)) v)) (draw [d] (cern.jet.random.tdouble.NegativeBinomial/staticNextInt size prob)) (support [d] [0,inf+]) (mean [d] (/ (* size prob) (- 1 prob))) (variance [d] (/ (* size prob) (* (- 1 prob) (- 1 prob))))) (defn neg-binomial-distribution "Returns a Negative binomial distribution that implements the incanter.distributions.Distribution protocol. Arguments: size (default 10) prob (default 1/2) See also: Distribution, pdf, cdf, draw, support References: Example: (pdf (neg-binomial-distribution 20 1/2) 10)" ([] (neg-binomial-distribution 10 1/2)) ([size prob] (NegativeBinomial-rec. size prob))) (defrecord Poisson-rec [lambda] Distribution (pdf [d v] (.pdf (Poisson. lambda (DoubleMersenneTwister.)) v)) (cdf [d v] (.cdf (Poisson. lambda (DoubleMersenneTwister.)) v)) (draw [d] (cern.jet.random.tdouble.Poisson/staticNextInt lambda)) (support [d] [0,inf+]) (mean [d] lambda) (variance [d] lambda)) (defn poisson-distribution "Returns a Poisson distribution that implements the incanter.distributions.Distribution protocol. Arguments: lambda (default 1) See also: Distribution, pdf, cdf, draw, support References: Example: (pdf (poisson-distribution 10) 5)" ([] (poisson-distribution 1)) ([lambda] (Poisson-rec. lambda))) (defrecord StudentT-rec [df] Distribution (pdf [d v] (.pdf (StudentT. df (DoubleMersenneTwister.)) v)) (cdf [d v] (.cdf (StudentT. df (DoubleMersenneTwister.)) v)) (draw [d] (cern.jet.random.tdouble.StudentT/staticNextDouble df)) (support [d] [inf-,inf+]) (mean [d] (if (> df 1) 0 nil)) (variance [d] (cond (> df 2) (/ df (- df 2)) (and (> df 1) (<= df 2)) inf+ :else nil))) (defn t-distribution "Returns a Student-t distribution that implements the incanter.distributions.Distribution protocol. Arguments: df (default 1) See also: Distribution, pdf, cdf, draw, support References: -t_distribution Example: (pdf (t-distribution 10) 1.2)" ([] (t-distribution 1)) ([df] (StudentT-rec. df))) ( extend cern.jet.random.tdouble . colt - extenders ) (defrecord DoubleUniform-rec [min max] Distribution (pdf [d v] (.pdf (DoubleUniform. min max (DoubleMersenneTwister.)) v)) (cdf [d v] (.cdf (DoubleUniform. min max (DoubleMersenneTwister.)) v)) (draw [d] (cern.jet.random.tdouble.DoubleUniform/staticNextDouble)) (support [d] [min,max]) (mean [d] (/ (+ min max) 2)) (variance [d] (/ (* (- max min) (- max min)) 12))) (defn uniform-distribution "Returns a Uniform distribution that implements the incanter.distributions.Distribution protocol. Arguments: min (default 0) max (default 1) See also: Distribution, pdf, cdf, draw, support References: Example: (pdf (uniform-distribution 1.0 10.0) 5)" since " 0 1 " not implicitly promoted , otheriwse no matching ctor ... ([min max] (DoubleUniform-rec. min max)))
9dbc3f1a0c22e1ea69c6f23de884e0dd0bcff87e9b1d5dff3211f12359f8adf1
mbj/mhs
HUnit.hs
module Test.HUnit where import Data.Bounded.Prelude import Test.Tasty.HUnit import qualified Data.List as List shouldFailWith :: forall e. Exception e => String -> Assertion -> Assertion shouldFailWith msg assertion = do eResult <- try @e assertion case eResult of Right _ -> assertFailure "Error should have failed" Left (show -> err) -> unless (msg `List.isInfixOf` err) . assertFailure $ "Failed! expected error message: " <> err <> " but got " <> msg
null
https://raw.githubusercontent.com/mbj/mhs/3c0fe9e28c24ba633ed51ccbeeb154d6f2f82292/bounded/test/Test/HUnit.hs
haskell
module Test.HUnit where import Data.Bounded.Prelude import Test.Tasty.HUnit import qualified Data.List as List shouldFailWith :: forall e. Exception e => String -> Assertion -> Assertion shouldFailWith msg assertion = do eResult <- try @e assertion case eResult of Right _ -> assertFailure "Error should have failed" Left (show -> err) -> unless (msg `List.isInfixOf` err) . assertFailure $ "Failed! expected error message: " <> err <> " but got " <> msg
2fbb44bd9965a018a2b0cf445b2a8ffad5d41f4d22be034d0e69d78448a1e4bd
clj-holmes/clj-holmes
json.clj
(ns clj-holmes.specs.json (:require [clojure.spec.alpha :as s] [clojure.string :as str])) (s/def ::non-blank-string (s/and string? (complement str/blank?))) (s/def ::row pos-int?) (s/def ::col pos-int?) (s/def ::end-row pos-int?) (s/def ::end-col pos-int?) (s/def ::parent (s/nilable qualified-keyword?)) (s/def ::code any?) (s/def ::finding (s/keys :opt-un [::row ::col ::end-row ::end-col] :req-un [::parent ::code])) (s/def ::findings (s/coll-of ::finding)) (s/def ::filename ::non-blank-string) (s/def ::name ::non-blank-string) (s/def ::message ::non-blank-string) (s/def ::result (s/keys :req-un [::findings ::filename ::name ::message])) (s/def ::results (s/coll-of ::result))
null
https://raw.githubusercontent.com/clj-holmes/clj-holmes/f06ed9d0623db4512c8fb6b8d7781229355f77ee/src/clj_holmes/specs/json.clj
clojure
(ns clj-holmes.specs.json (:require [clojure.spec.alpha :as s] [clojure.string :as str])) (s/def ::non-blank-string (s/and string? (complement str/blank?))) (s/def ::row pos-int?) (s/def ::col pos-int?) (s/def ::end-row pos-int?) (s/def ::end-col pos-int?) (s/def ::parent (s/nilable qualified-keyword?)) (s/def ::code any?) (s/def ::finding (s/keys :opt-un [::row ::col ::end-row ::end-col] :req-un [::parent ::code])) (s/def ::findings (s/coll-of ::finding)) (s/def ::filename ::non-blank-string) (s/def ::name ::non-blank-string) (s/def ::message ::non-blank-string) (s/def ::result (s/keys :req-un [::findings ::filename ::name ::message])) (s/def ::results (s/coll-of ::result))
f6eade126670000b7eb835231cdf80c71a80fe0bbacf7890889dd75d7545b937
RefactoringTools/HaRe
Signature3.hs
module LiftToTopLevel.Signature3 where {- Lifting baz to the top level should bring in xx and a as parameters, and update the signature to include these -} foo a = baz where baz :: Int baz = xx 1 a xx :: Int -> Int -> Int xx p1 p2 = p1 + p2
null
https://raw.githubusercontent.com/RefactoringTools/HaRe/ef5dee64c38fb104e6e5676095946279fbce381c/test/testdata/LiftToToplevel/Signature3.hs
haskell
Lifting baz to the top level should bring in xx and a as parameters, and update the signature to include these
module LiftToTopLevel.Signature3 where foo a = baz where baz :: Int baz = xx 1 a xx :: Int -> Int -> Int xx p1 p2 = p1 + p2
15bcbfea973c8d07f7a3f2c0e60525d98e57c5e02cc535721bdce5df3bdafbcf
binsec/binsec
armToDba.enabled.ml
(**************************************************************************) This file is part of BINSEC . (* *) Copyright ( C ) 2016 - 2022 CEA ( Commissariat à l'énergie atomique et aux énergies (* alternatives) *) (* *) (* you can redistribute it and/or modify it under the terms of the GNU *) Lesser General Public License as published by the Free Software Foundation , version 2.1 . (* *) (* It is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* GNU Lesser General Public License for more details. *) (* *) See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . (* *) (**************************************************************************) module Statistics = struct open! Basic_types type opcode_tbl = (Instruction.Generic.t, unit) Hashtbl.t type t = { decoded : opcode_tbl; mutable n_instr : int; parse_failed : int ref; invalid_size : int ref; other_errors : unit String.Htbl.t; not_implemented : unit String.Htbl.t; } let empty = { decoded = Hashtbl.create 17; n_instr = 0; parse_failed = ref 0; invalid_size = ref 0; other_errors = String.Htbl.create 7; not_implemented = String.Htbl.create 7; } let add_bytes bytes h = String.Htbl.add h bytes () let size h = String.Htbl.length h let size_unique h = let s = String.Set.empty in String.Htbl.fold (fun k _ s -> String.Set.add k s) h s |> String.Set.cardinal let pp_h ppf h = Format.fprintf ppf "@[<v 0>%d (%d)@ @[<hov 0>%a@]@]" (size h) (size_unique h) (fun ppf -> String.Htbl.iter (fun k _ -> Format.fprintf ppf "%s;@ " k)) h let incr_decoded (i, _) t = t.n_instr <- t.n_instr + 1; Hashtbl.replace t.decoded i () let incr_invalid_size t = incr t.invalid_size let incr_parse_failed t = incr t.parse_failed let incr_errors opcode t = add_bytes opcode t.other_errors let incr_not_implemented opcode t = add_bytes opcode t.not_implemented let pp ppf t = Format.fprintf ppf "@[<v 0>ARM decoding statistics@ ----@ Decoded (unique): %d (%d)@ Failed \ parsing: %d@ Invalid size: %d@ Not implemented (unique): %a @ Misc \ errors (unique): %a@ @]" t.n_instr (Hashtbl.length t.decoded) !(t.parse_failed) !(t.invalid_size) pp_h t.not_implemented pp_h t.other_errors end let stats = Statistics.empty let show_stats ppf () = Statistics.pp ppf stats let find key kvs = try List.assoc key kvs with Not_found -> Arm_options.Logger.debug "Decoder message has no %s field. Aborting." key; raise Not_found Some conversion functions from parsed categorized value to the expected types in Instruction.Generic.create in Instruction.Generic.create *) let to_hex_opcode = function | Parse_helpers.Message.Value.Int h -> Z.format "%02x" h | _ -> assert false let to_mnemonic = function | Parse_helpers.Message.Value.Str s -> Mnemonic.supported s Format.pp_print_string | _ -> assert false let just_integer = function | Parse_helpers.Message.Value.Int n -> Z.to_int n | _ -> assert false let compare_labeled_instruction (caddr1, _i1) (caddr2, _i2) = Dba_types.Caddress.compare caddr1 caddr2 let to_block addr_instr_list = Blocks returned by Unisimi 's ARM decoded are not necessarily ordered . We need to do it here . The specific comparison functions explicits assumptions about what is expected ( same virtual addresses and differences of identifiers ) . We need to do it here. The specific comparison functions explicits assumptions about what is expected (same virtual addresses and differences of identifiers). *) List.sort compare_labeled_instruction addr_instr_list |> List.map snd |> Dhunk.of_list let mk_instruction (kvs, instructions) = let opcode = find "opcode" kvs |> to_hex_opcode in let mnemonic = find "mnemonic" kvs |> to_mnemonic in let size = find "size" kvs |> just_integer in let block = to_block instructions in let ginstr = Instruction.Generic.create size opcode mnemonic in (ginstr, block) Create a dummy instruction . This is used for " unfailing " mode where something is always returned , even in cases of Parser . Error . This is used for "unfailing" mode where something is always returned, even in cases of Parser.Error. *) let dummy_instruction kvs = let block = Dba.Instr.stop (Some Dba.KO) |> Dhunk.singleton in let opcode = find "opcode" kvs |> to_hex_opcode in let mnemonic = find "mnemonic" kvs |> to_mnemonic in let size = 4 in let ginstr = Instruction.Generic.create size opcode mnemonic in (ginstr, block) let empty_instruction = let block = Dba.Instr.stop (Some Dba.KO) |> Dhunk.singleton in let opcode = "" in let mnemonic = Mnemonic.unsupported () in let size = 4 in let ginstr = Instruction.Generic.create size opcode mnemonic in (ginstr, block) let dummy_parse s = let open Lexing in let lexbuf = from_string s in try let kvs = Parser.decoder_base Lexer.token lexbuf in let opcode = to_hex_opcode (find "opcode" kvs) in match dummy_instruction kvs with | i -> Statistics.incr_errors opcode stats; Error i | exception Failure _ -> Statistics.incr_not_implemented opcode stats; Error empty_instruction with | Failure _ | Parsing.Parse_error | Parser.Error -> Statistics.incr_parse_failed stats; let pos = lexeme_start_p lexbuf in Arm_options.Logger.error "@[<v 0>Probable parse error at line %d, column %d@ Lexeme was: %s@ \ Entry was: %s@ Getting basic infos only ... @]" pos.pos_lnum pos.pos_cnum (Lexing.lexeme lexbuf) s; Error empty_instruction | Not_found -> Error empty_instruction let parse_result s = Arm_options.Logger.debug ~level:1 "@[<v 0>Parsing %s@]" s; let open Lexing in let lexbuf = from_string s in try Ok (mk_instruction (Parser.decoder_msg Lexer.token lexbuf)) with _ -> dummy_parse s let decode_arm addr bytes = Arm32dba.decode ~thumb:false ~addr bytes |> parse_result let decode_from_reader_arm addr reader = if addr mod 4 <> 0 then Error empty_instruction else match Lreader.Peek.i32 reader with | exception _ -> Statistics.incr_invalid_size stats; Error empty_instruction | bytes -> decode_arm (Int32.of_int addr) bytes let merge_itblock addr itblock = let n = Array.length itblock in let sizes = Array.make (n + 1) 0 in for i = 1 to n do sizes.(i) <- sizes.(i - 1) + Dhunk.length itblock.(i - 1) done; let inner j i = i + sizes.(j) in let outer = let rec iter i map = if i = n then map else iter (i + 1) (Dba_types.Caddress.Map.add (Dba_types.Caddress.block_start_of_int (addr + (2 * i))) (Dba.Jump_target.inner sizes.(i)) map) in let map = iter 1 Dba_types.Caddress.Map.empty in fun j -> function | Dba.JInner goto -> Dba.Jump_target.inner (inner j goto) | Dba.JOuter caddr as jo -> ( try Dba_types.Caddress.Map.find caddr map with Not_found -> jo) in let open Dhunk in let j = ref 0 in init sizes.(n) (fun i -> if i >= sizes.(!j + 1) then incr j; Dba_types.Instruction.reloc ~outer:(outer !j) ~inner:(inner !j) (Utils.unsafe_get_opt (inst itblock.(!j) (i - sizes.(!j))))) let pp_opcode ppf bv = for i = 0 to (Bitvector.size_of bv / 8) - 1 do Format.fprintf ppf "%02x" (Z.to_int Bitvector.( value_of (extract bv { Interval.lo = 8 * i; hi = (8 * (i + 1)) - 1 }))) done let itstate w i = if i = 0 then 0 else w land 0xe0 lor ((w lsl (i - 1)) land 0x1f) let isitw w = let w = w land 0xffff in 0xbf00 < w && w <= 0xbfff let decode_thumb itstate addr bytes = Arm32dba.decode ~thumb:true ~itstate ~addr bytes |> parse_result let decode_from_reader_thumb addr reader = let addr = if addr mod 2 = 1 then ( Lreader.rewind reader 1; addr - 1) else addr in match Lreader.Peek.u16 reader with | exception _ -> Statistics.incr_invalid_size stats; Error empty_instruction | bytes when not @@ isitw bytes -> let bytes = try Lreader.Peek.i32 reader with _ -> Int32.of_int bytes in decode_thumb 0 (Int32.of_int addr) bytes | word -> ( (* it block *) let n = 1 + if word land 0x01 <> 0 then 4 else if word land 0x02 <> 0 then 3 else if word land 0x04 <> 0 then 2 else if word land 0x08 <> 0 then 1 else assert false in let itblock = Array.make n (fst empty_instruction) and ithunks = Array.make n (snd empty_instruction) in let rec init i offset = if i = n then offset else match try Lreader.Peek.i32 reader with _ -> Int32.of_int (Lreader.Peek.u16 reader) with | exception _ -> raise @@ Failure "" | bytes -> ( match decode_thumb (itstate word i) (Int32.of_int (addr + offset)) bytes with | Error _ -> raise @@ Failure "" | Ok (instr, dhunk) -> itblock.(i) <- instr; ithunks.(i) <- dhunk; let size = Size.Byte.to_int instr.Instruction.Generic.size in Lreader.advance reader size; init (i + 1) (offset + size)) in try let size = init 0 0 in Lreader.rewind reader size; let bytes = Lreader.Peek.read reader size in let opcode = Format.asprintf "%a" pp_opcode bytes in let mnemonic = Mnemonic.supported itblock (fun ppf it -> Array.iteri (fun i g -> if i <> 0 then Format.pp_print_string ppf "; "; Instruction.Generic.pp_mnemonic ppf g) it) in Ok ( Instruction.Generic.create size opcode mnemonic, merge_itblock addr ithunks ) with Failure _ -> Error empty_instruction) let thumb_mode = Dba.(Expr.var ~tag:Var.Tag.Flag "t" 1) let assert_mode mode dhunk = let open Dhunk in init (length dhunk + 1) (function | 0 -> Dba.Instr._assert mode 1 | i -> Dba_types.Instruction.reloc ~inner:(fun x -> x + 1) (Utils.unsafe_get_opt (inst dhunk (i - 1)))) let merge_dhunk arm thumb = let open Dhunk in let larm = length arm and lthumb = length thumb in init (1 + larm + lthumb) (function | 0 -> Dba.Instr.ite thumb_mode (Dba.Jump_target.inner (1 + larm)) 1 | i when i <= larm -> Dba_types.Instruction.reloc ~inner:(fun x -> x + 1) (Utils.unsafe_get_opt (inst arm (i - 1))) | i -> Dba_types.Instruction.reloc ~inner:(fun x -> x + larm + 1) (Utils.unsafe_get_opt (inst thumb (i - 1 - larm)))) let merge_ginstr arm thumb = let open Instruction.Generic in let size, opcode = if arm.size > thumb.size then (arm.size, arm.opcode) else (thumb.size, thumb.opcode) in let mnemonic = match (arm.mnemonic, thumb.mnemonic) with | Mnemonic.Supported s, Mnemonic.Supported s' -> Mnemonic.supported () (fun ppf _ -> Format.fprintf ppf "[arm] %s | [thumb] %s" s s') | _, _ -> assert false in create (Size.Byte.to_int size) opcode mnemonic let merge_result arm thumb = match (arm, thumb) with | Error _, Error i -> i | Error _, Ok (g, d) -> Statistics.incr_decoded (g, d) stats; (g, assert_mode thumb_mode d) | Ok (g, d), Error _ -> Statistics.incr_decoded (g, d) stats; (g, assert_mode (Dba.Expr.lognot thumb_mode) d) | Ok (g, d), Ok (g', d') -> let g, d = (merge_ginstr g g', merge_dhunk d d') in Statistics.incr_decoded (g, d) stats; (g, d) let unwrap_result = function Error i -> i | Ok x -> x let decode_from_reader addr reader = let ((Instruction.Generic.{ size; _ }, _) as r) = match Arm_options.SupportedModes.get () with | Arm_options.Both -> merge_result (decode_from_reader_arm addr reader) (decode_from_reader_thumb addr reader) | Arm_options.Arm -> decode_from_reader_arm addr reader |> unwrap_result | Arm_options.Thumb -> decode_from_reader_thumb addr reader |> unwrap_result in Lreader.advance reader (Size.Byte.to_int size); r let decode reader (addr : Virtual_address.t) = let res = decode_from_reader (addr :> int) reader in Arm_options.Logger.debug ~level:5 "@[%a@]" Dhunk.pp (snd res); Arm_options.Logger.debug ~level:3 "@[%a@]" show_stats (); res let cached_decode reader = let h = Virtual_address.Htbl.create 7 in fun (addr : Virtual_address.t) -> match Virtual_address.Htbl.find h addr with | res -> res | exception Not_found -> let res = decode reader addr in Virtual_address.Htbl.add h addr res; res ;; Disasm_core.register_decoder (Machine.armv7 Machine.LittleEndian) decode (fun x -> x)
null
https://raw.githubusercontent.com/binsec/binsec/22ee39aad58219e8837b6ba15f150ba04a498b63/src/disasm/arm/armToDba.enabled.ml
ocaml
************************************************************************ alternatives) you can redistribute it and/or modify it under the terms of the GNU It is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ************************************************************************ it block
This file is part of BINSEC . Copyright ( C ) 2016 - 2022 CEA ( Commissariat à l'énergie atomique et aux énergies Lesser General Public License as published by the Free Software Foundation , version 2.1 . See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . module Statistics = struct open! Basic_types type opcode_tbl = (Instruction.Generic.t, unit) Hashtbl.t type t = { decoded : opcode_tbl; mutable n_instr : int; parse_failed : int ref; invalid_size : int ref; other_errors : unit String.Htbl.t; not_implemented : unit String.Htbl.t; } let empty = { decoded = Hashtbl.create 17; n_instr = 0; parse_failed = ref 0; invalid_size = ref 0; other_errors = String.Htbl.create 7; not_implemented = String.Htbl.create 7; } let add_bytes bytes h = String.Htbl.add h bytes () let size h = String.Htbl.length h let size_unique h = let s = String.Set.empty in String.Htbl.fold (fun k _ s -> String.Set.add k s) h s |> String.Set.cardinal let pp_h ppf h = Format.fprintf ppf "@[<v 0>%d (%d)@ @[<hov 0>%a@]@]" (size h) (size_unique h) (fun ppf -> String.Htbl.iter (fun k _ -> Format.fprintf ppf "%s;@ " k)) h let incr_decoded (i, _) t = t.n_instr <- t.n_instr + 1; Hashtbl.replace t.decoded i () let incr_invalid_size t = incr t.invalid_size let incr_parse_failed t = incr t.parse_failed let incr_errors opcode t = add_bytes opcode t.other_errors let incr_not_implemented opcode t = add_bytes opcode t.not_implemented let pp ppf t = Format.fprintf ppf "@[<v 0>ARM decoding statistics@ ----@ Decoded (unique): %d (%d)@ Failed \ parsing: %d@ Invalid size: %d@ Not implemented (unique): %a @ Misc \ errors (unique): %a@ @]" t.n_instr (Hashtbl.length t.decoded) !(t.parse_failed) !(t.invalid_size) pp_h t.not_implemented pp_h t.other_errors end let stats = Statistics.empty let show_stats ppf () = Statistics.pp ppf stats let find key kvs = try List.assoc key kvs with Not_found -> Arm_options.Logger.debug "Decoder message has no %s field. Aborting." key; raise Not_found Some conversion functions from parsed categorized value to the expected types in Instruction.Generic.create in Instruction.Generic.create *) let to_hex_opcode = function | Parse_helpers.Message.Value.Int h -> Z.format "%02x" h | _ -> assert false let to_mnemonic = function | Parse_helpers.Message.Value.Str s -> Mnemonic.supported s Format.pp_print_string | _ -> assert false let just_integer = function | Parse_helpers.Message.Value.Int n -> Z.to_int n | _ -> assert false let compare_labeled_instruction (caddr1, _i1) (caddr2, _i2) = Dba_types.Caddress.compare caddr1 caddr2 let to_block addr_instr_list = Blocks returned by Unisimi 's ARM decoded are not necessarily ordered . We need to do it here . The specific comparison functions explicits assumptions about what is expected ( same virtual addresses and differences of identifiers ) . We need to do it here. The specific comparison functions explicits assumptions about what is expected (same virtual addresses and differences of identifiers). *) List.sort compare_labeled_instruction addr_instr_list |> List.map snd |> Dhunk.of_list let mk_instruction (kvs, instructions) = let opcode = find "opcode" kvs |> to_hex_opcode in let mnemonic = find "mnemonic" kvs |> to_mnemonic in let size = find "size" kvs |> just_integer in let block = to_block instructions in let ginstr = Instruction.Generic.create size opcode mnemonic in (ginstr, block) Create a dummy instruction . This is used for " unfailing " mode where something is always returned , even in cases of Parser . Error . This is used for "unfailing" mode where something is always returned, even in cases of Parser.Error. *) let dummy_instruction kvs = let block = Dba.Instr.stop (Some Dba.KO) |> Dhunk.singleton in let opcode = find "opcode" kvs |> to_hex_opcode in let mnemonic = find "mnemonic" kvs |> to_mnemonic in let size = 4 in let ginstr = Instruction.Generic.create size opcode mnemonic in (ginstr, block) let empty_instruction = let block = Dba.Instr.stop (Some Dba.KO) |> Dhunk.singleton in let opcode = "" in let mnemonic = Mnemonic.unsupported () in let size = 4 in let ginstr = Instruction.Generic.create size opcode mnemonic in (ginstr, block) let dummy_parse s = let open Lexing in let lexbuf = from_string s in try let kvs = Parser.decoder_base Lexer.token lexbuf in let opcode = to_hex_opcode (find "opcode" kvs) in match dummy_instruction kvs with | i -> Statistics.incr_errors opcode stats; Error i | exception Failure _ -> Statistics.incr_not_implemented opcode stats; Error empty_instruction with | Failure _ | Parsing.Parse_error | Parser.Error -> Statistics.incr_parse_failed stats; let pos = lexeme_start_p lexbuf in Arm_options.Logger.error "@[<v 0>Probable parse error at line %d, column %d@ Lexeme was: %s@ \ Entry was: %s@ Getting basic infos only ... @]" pos.pos_lnum pos.pos_cnum (Lexing.lexeme lexbuf) s; Error empty_instruction | Not_found -> Error empty_instruction let parse_result s = Arm_options.Logger.debug ~level:1 "@[<v 0>Parsing %s@]" s; let open Lexing in let lexbuf = from_string s in try Ok (mk_instruction (Parser.decoder_msg Lexer.token lexbuf)) with _ -> dummy_parse s let decode_arm addr bytes = Arm32dba.decode ~thumb:false ~addr bytes |> parse_result let decode_from_reader_arm addr reader = if addr mod 4 <> 0 then Error empty_instruction else match Lreader.Peek.i32 reader with | exception _ -> Statistics.incr_invalid_size stats; Error empty_instruction | bytes -> decode_arm (Int32.of_int addr) bytes let merge_itblock addr itblock = let n = Array.length itblock in let sizes = Array.make (n + 1) 0 in for i = 1 to n do sizes.(i) <- sizes.(i - 1) + Dhunk.length itblock.(i - 1) done; let inner j i = i + sizes.(j) in let outer = let rec iter i map = if i = n then map else iter (i + 1) (Dba_types.Caddress.Map.add (Dba_types.Caddress.block_start_of_int (addr + (2 * i))) (Dba.Jump_target.inner sizes.(i)) map) in let map = iter 1 Dba_types.Caddress.Map.empty in fun j -> function | Dba.JInner goto -> Dba.Jump_target.inner (inner j goto) | Dba.JOuter caddr as jo -> ( try Dba_types.Caddress.Map.find caddr map with Not_found -> jo) in let open Dhunk in let j = ref 0 in init sizes.(n) (fun i -> if i >= sizes.(!j + 1) then incr j; Dba_types.Instruction.reloc ~outer:(outer !j) ~inner:(inner !j) (Utils.unsafe_get_opt (inst itblock.(!j) (i - sizes.(!j))))) let pp_opcode ppf bv = for i = 0 to (Bitvector.size_of bv / 8) - 1 do Format.fprintf ppf "%02x" (Z.to_int Bitvector.( value_of (extract bv { Interval.lo = 8 * i; hi = (8 * (i + 1)) - 1 }))) done let itstate w i = if i = 0 then 0 else w land 0xe0 lor ((w lsl (i - 1)) land 0x1f) let isitw w = let w = w land 0xffff in 0xbf00 < w && w <= 0xbfff let decode_thumb itstate addr bytes = Arm32dba.decode ~thumb:true ~itstate ~addr bytes |> parse_result let decode_from_reader_thumb addr reader = let addr = if addr mod 2 = 1 then ( Lreader.rewind reader 1; addr - 1) else addr in match Lreader.Peek.u16 reader with | exception _ -> Statistics.incr_invalid_size stats; Error empty_instruction | bytes when not @@ isitw bytes -> let bytes = try Lreader.Peek.i32 reader with _ -> Int32.of_int bytes in decode_thumb 0 (Int32.of_int addr) bytes | word -> ( let n = 1 + if word land 0x01 <> 0 then 4 else if word land 0x02 <> 0 then 3 else if word land 0x04 <> 0 then 2 else if word land 0x08 <> 0 then 1 else assert false in let itblock = Array.make n (fst empty_instruction) and ithunks = Array.make n (snd empty_instruction) in let rec init i offset = if i = n then offset else match try Lreader.Peek.i32 reader with _ -> Int32.of_int (Lreader.Peek.u16 reader) with | exception _ -> raise @@ Failure "" | bytes -> ( match decode_thumb (itstate word i) (Int32.of_int (addr + offset)) bytes with | Error _ -> raise @@ Failure "" | Ok (instr, dhunk) -> itblock.(i) <- instr; ithunks.(i) <- dhunk; let size = Size.Byte.to_int instr.Instruction.Generic.size in Lreader.advance reader size; init (i + 1) (offset + size)) in try let size = init 0 0 in Lreader.rewind reader size; let bytes = Lreader.Peek.read reader size in let opcode = Format.asprintf "%a" pp_opcode bytes in let mnemonic = Mnemonic.supported itblock (fun ppf it -> Array.iteri (fun i g -> if i <> 0 then Format.pp_print_string ppf "; "; Instruction.Generic.pp_mnemonic ppf g) it) in Ok ( Instruction.Generic.create size opcode mnemonic, merge_itblock addr ithunks ) with Failure _ -> Error empty_instruction) let thumb_mode = Dba.(Expr.var ~tag:Var.Tag.Flag "t" 1) let assert_mode mode dhunk = let open Dhunk in init (length dhunk + 1) (function | 0 -> Dba.Instr._assert mode 1 | i -> Dba_types.Instruction.reloc ~inner:(fun x -> x + 1) (Utils.unsafe_get_opt (inst dhunk (i - 1)))) let merge_dhunk arm thumb = let open Dhunk in let larm = length arm and lthumb = length thumb in init (1 + larm + lthumb) (function | 0 -> Dba.Instr.ite thumb_mode (Dba.Jump_target.inner (1 + larm)) 1 | i when i <= larm -> Dba_types.Instruction.reloc ~inner:(fun x -> x + 1) (Utils.unsafe_get_opt (inst arm (i - 1))) | i -> Dba_types.Instruction.reloc ~inner:(fun x -> x + larm + 1) (Utils.unsafe_get_opt (inst thumb (i - 1 - larm)))) let merge_ginstr arm thumb = let open Instruction.Generic in let size, opcode = if arm.size > thumb.size then (arm.size, arm.opcode) else (thumb.size, thumb.opcode) in let mnemonic = match (arm.mnemonic, thumb.mnemonic) with | Mnemonic.Supported s, Mnemonic.Supported s' -> Mnemonic.supported () (fun ppf _ -> Format.fprintf ppf "[arm] %s | [thumb] %s" s s') | _, _ -> assert false in create (Size.Byte.to_int size) opcode mnemonic let merge_result arm thumb = match (arm, thumb) with | Error _, Error i -> i | Error _, Ok (g, d) -> Statistics.incr_decoded (g, d) stats; (g, assert_mode thumb_mode d) | Ok (g, d), Error _ -> Statistics.incr_decoded (g, d) stats; (g, assert_mode (Dba.Expr.lognot thumb_mode) d) | Ok (g, d), Ok (g', d') -> let g, d = (merge_ginstr g g', merge_dhunk d d') in Statistics.incr_decoded (g, d) stats; (g, d) let unwrap_result = function Error i -> i | Ok x -> x let decode_from_reader addr reader = let ((Instruction.Generic.{ size; _ }, _) as r) = match Arm_options.SupportedModes.get () with | Arm_options.Both -> merge_result (decode_from_reader_arm addr reader) (decode_from_reader_thumb addr reader) | Arm_options.Arm -> decode_from_reader_arm addr reader |> unwrap_result | Arm_options.Thumb -> decode_from_reader_thumb addr reader |> unwrap_result in Lreader.advance reader (Size.Byte.to_int size); r let decode reader (addr : Virtual_address.t) = let res = decode_from_reader (addr :> int) reader in Arm_options.Logger.debug ~level:5 "@[%a@]" Dhunk.pp (snd res); Arm_options.Logger.debug ~level:3 "@[%a@]" show_stats (); res let cached_decode reader = let h = Virtual_address.Htbl.create 7 in fun (addr : Virtual_address.t) -> match Virtual_address.Htbl.find h addr with | res -> res | exception Not_found -> let res = decode reader addr in Virtual_address.Htbl.add h addr res; res ;; Disasm_core.register_decoder (Machine.armv7 Machine.LittleEndian) decode (fun x -> x)
073f0162303597b041ca03898f20dcc654581dd1461639f70009bf71c5987ce9
archimag/cliki2
entry.lisp
;;;; entry.lisp (in-package #:cliki2) (restas:define-route entry ("") (view-article :title "index")) (restas:mount-submodule -static- (#:restas.directory-publisher) (restas.directory-publisher:*directory* (merge-pathnames "static/" *basepath*)) (restas.directory-publisher:*autoindex* t))
null
https://raw.githubusercontent.com/archimag/cliki2/f0b6910f040907c70fd842ed76472af2d645c984/src/routes/entry.lisp
lisp
entry.lisp
(in-package #:cliki2) (restas:define-route entry ("") (view-article :title "index")) (restas:mount-submodule -static- (#:restas.directory-publisher) (restas.directory-publisher:*directory* (merge-pathnames "static/" *basepath*)) (restas.directory-publisher:*autoindex* t))
bcddc6f9c6ff01d9405dba45cf51cdd21caa158559c4c88cdfc4db8b6f1cfd58
avsm/mirage-duniverse
state.ml
Defines all high - level datatypes for the TLS library . It is opaque to clients of this library , and only used from within the library . of this library, and only used from within the library. *) open Sexplib open Sexplib.Conv open Core open Nocrypto type hmac_key = Cstruct.t type 'k stream_state = { cipher : (module Cipher_stream.S with type key = 'k) ; cipher_secret : 'k ; hmac : Hash.hash ; hmac_secret : hmac_key } initialisation vector style , depending on TLS version type iv_mode = traditional CBC ( reusing last cipherblock ) | Random_iv (* TLS 1.1 and higher explicit IV (we use random) *) [@@deriving sexp] type 'k cbc_cipher = (module Cipher_block.S.CBC with type key = 'k) type 'k cbc_state = { cipher : 'k cbc_cipher ; cipher_secret : 'k ; iv_mode : iv_mode ; hmac : Hash.hash ; hmac_secret : hmac_key } type nonce = Cstruct.t type 'k aead_cipher = | CCM of (module Cipher_block.S.CCM with type key = 'k) | GCM of (module Cipher_block.S.GCM with type key = 'k) type 'k aead_state = { cipher : 'k aead_cipher ; cipher_secret : 'k ; nonce : nonce } (* state of a symmetric cipher *) type cipher_st = | Stream : 'k stream_state -> cipher_st | CBC : 'k cbc_state -> cipher_st | AEAD : 'k aead_state -> cipher_st stubs -- rethink how to play with crypto . let sexp_of_cipher_st = function | Stream _ -> Sexp.Atom "<stream-state>" | CBC _ -> Sexp.Atom "<cbc-state>" | AEAD _ -> Sexp.Atom "<aead-state>" let cipher_st_of_sexp = Conv.of_sexp_error "cipher_st_of_sexp: not implemented" (* *** *) (* context of a TLS connection (both in and out has each one of these) *) type crypto_context = { sequence : int64 ; (* sequence number *) cipher_st : cipher_st ; (* cipher state *) } [@@deriving sexp] (* the raw handshake log we need to carry around *) type hs_log = Cstruct.t list [@@deriving sexp] diffie hellman group and secret type dh_sent = Dh.group * Dh.secret [@@deriving sexp] (* a collection of client and server verify bytes for renegotiation *) type reneg_params = Cstruct.t * Cstruct.t [@@deriving sexp] type session_data = { 32 bytes random from the server hello 32 bytes random from the client hello version in client hello ( needed in RSA client key exchange ) ciphersuite : Ciphersuite.ciphersuite ; peer_certificate_chain : X509.t list ; peer_certificate : X509.t option ; trust_anchor : X509.t option ; received_certificates : X509.t list ; own_certificate : X509.t list ; own_private_key : Nocrypto.Rsa.priv option ; master_secret : master_secret ; renegotiation : reneg_params ; (* renegotiation data *) own_name : string option ; client_auth : bool ; session_id : Cstruct.t ; extended_ms : bool ; alpn_protocol : string option ; (* selected alpn protocol after handshake *) } [@@deriving sexp] (* state machine of the server *) type server_handshake_state = | AwaitClientHello (* initial state *) | AwaitClientHelloRenegotiate | AwaitClientCertificate_RSA of session_data * hs_log | AwaitClientCertificate_DHE_RSA of session_data * dh_sent * hs_log server hello done is sent , and RSA key exchange used , waiting for a client key exchange message server hello done is sent , and DHE_RSA key exchange used , waiting for client key exchange | AwaitClientCertificateVerify of session_data * crypto_context * crypto_context * hs_log | AwaitClientChangeCipherSpec of session_data * crypto_context * crypto_context * hs_log (* client key exchange received, next should be change cipher spec *) | AwaitClientChangeCipherSpecResume of session_data * crypto_context * Cstruct.t * hs_log (* resumption: next should be change cipher spec *) | AwaitClientFinished of session_data * hs_log (* change cipher spec received, next should be the finished including a hmac over all handshake packets *) | AwaitClientFinishedResume of session_data * Cstruct.t * hs_log (* change cipher spec received, next should be the finished including a hmac over all handshake packets *) | Established (* handshake successfully completed *) [@@deriving sexp] (* state machine of the client *) type client_handshake_state = | ClientInitial (* initial state *) | AwaitServerHello of client_hello * hs_log (* client hello is sent, handshake_params are half-filled *) | AwaitServerHelloRenegotiate of session_data * client_hello * hs_log (* client hello is sent, handshake_params are half-filled *) certificate expected with RSA key exchange certificate expected with DHE_RSA key exchange server key exchange expected with DHE_RSA server hello done expected , client key exchange and premastersecret are ready server hello done expected , client key exchange and premastersecret are ready | AwaitServerChangeCipherSpec of session_data * crypto_context * Cstruct.t * hs_log (* change cipher spec expected *) | AwaitServerChangeCipherSpecResume of session_data * crypto_context * crypto_context * hs_log (* change cipher spec expected *) | AwaitServerFinished of session_data * Cstruct.t * hs_log (* finished expected with a hmac over all handshake packets *) | AwaitServerFinishedResume of session_data * hs_log (* finished expected with a hmac over all handshake packets *) | Established (* handshake successfully completed *) [@@deriving sexp] type handshake_machina_state = | Client of client_handshake_state | Server of server_handshake_state [@@deriving sexp] (* state during a handshake, used in the handlers *) type handshake_state = { session : session_data list ; protocol_version : tls_version ; machina : handshake_machina_state ; (* state machine state *) config : Config.config ; (* given config *) hs_fragment : Cstruct.t ; (* handshake messages can be fragmented, leftover from before *) } [@@deriving sexp] (* connection state: initially None, after handshake a crypto context *) type crypto_state = crypto_context option [@@deriving sexp] (* record consisting of a content type and a byte vector *) type record = Packet.content_type * Cstruct.t [@@deriving sexp] (* response returned by a handler *) type rec_resp = [ either instruction to change the encryptor to the given one either change the decryptor to the given one | `Record of record (* or a record which should be sent out *) ] (* return type of handshake handlers *) type handshake_return = handshake_state * rec_resp list (* Top level state, encapsulating the entire session. *) type state = { handshake : handshake_state ; (* the current handshake state *) decryptor : crypto_state ; (* the current decryption state *) encryptor : crypto_state ; (* the current encryption state *) fragment : Cstruct.t ; (* the leftover fragment from TCP fragmentation *) } [@@deriving sexp] type error = [ | `AuthenticationFailure of X509.Validation.validation_error | `NoConfiguredCiphersuite of Ciphersuite.ciphersuite list | `NoConfiguredVersion of tls_version | `NoConfiguredHash of Hash.hash list | `NoMatchingCertificateFound of string | `NoCertificateConfigured | `CouldntSelectCertificate ] [@@deriving sexp] type fatal = [ | `NoSecureRenegotiation | `NoCiphersuite of Packet.any_ciphersuite list | `NoVersion of tls_any_version | `ReaderError of Reader.error | `NoCertificateReceived | `NotRSACertificate | `NotRSASignature | `KeyTooSmall | `RSASignatureMismatch | `RSASignatureVerificationFailed | `HashAlgorithmMismatch | `BadCertificateChain | `MACMismatch | `MACUnderflow | `RecordOverflow of int | `UnknownRecordVersion of int * int | `UnknownContentType of int | `CannotHandleApplicationDataYet | `NoHeartbeat | `BadRecordVersion of tls_any_version | `BadFinished | `HandshakeFragmentsNotEmpty | `InvalidDH | `InvalidRenegotiation | `InvalidClientHello | `InvalidServerHello | `InvalidRenegotiationVersion of tls_version | `InappropriateFallback | `UnexpectedCCS | `UnexpectedHandshake of tls_handshake | `InvalidCertificateUsage | `InvalidCertificateExtendedUsage | `InvalidSession | `NoApplicationProtocol ] [@@deriving sexp] type failure = [ | `Error of error | `Fatal of fatal ] [@@deriving sexp] Monadic control - flow core . include Control.Or_error_make (struct type err = failure end) type 'a eff = 'a t include Result
null
https://raw.githubusercontent.com/avsm/mirage-duniverse/983e115ff5a9fb37e3176c373e227e9379f0d777/ocaml_modules/tls/lib/state.ml
ocaml
TLS 1.1 and higher explicit IV (we use random) state of a symmetric cipher *** context of a TLS connection (both in and out has each one of these) sequence number cipher state the raw handshake log we need to carry around a collection of client and server verify bytes for renegotiation renegotiation data selected alpn protocol after handshake state machine of the server initial state client key exchange received, next should be change cipher spec resumption: next should be change cipher spec change cipher spec received, next should be the finished including a hmac over all handshake packets change cipher spec received, next should be the finished including a hmac over all handshake packets handshake successfully completed state machine of the client initial state client hello is sent, handshake_params are half-filled client hello is sent, handshake_params are half-filled change cipher spec expected change cipher spec expected finished expected with a hmac over all handshake packets finished expected with a hmac over all handshake packets handshake successfully completed state during a handshake, used in the handlers state machine state given config handshake messages can be fragmented, leftover from before connection state: initially None, after handshake a crypto context record consisting of a content type and a byte vector response returned by a handler or a record which should be sent out return type of handshake handlers Top level state, encapsulating the entire session. the current handshake state the current decryption state the current encryption state the leftover fragment from TCP fragmentation
Defines all high - level datatypes for the TLS library . It is opaque to clients of this library , and only used from within the library . of this library, and only used from within the library. *) open Sexplib open Sexplib.Conv open Core open Nocrypto type hmac_key = Cstruct.t type 'k stream_state = { cipher : (module Cipher_stream.S with type key = 'k) ; cipher_secret : 'k ; hmac : Hash.hash ; hmac_secret : hmac_key } initialisation vector style , depending on TLS version type iv_mode = traditional CBC ( reusing last cipherblock ) [@@deriving sexp] type 'k cbc_cipher = (module Cipher_block.S.CBC with type key = 'k) type 'k cbc_state = { cipher : 'k cbc_cipher ; cipher_secret : 'k ; iv_mode : iv_mode ; hmac : Hash.hash ; hmac_secret : hmac_key } type nonce = Cstruct.t type 'k aead_cipher = | CCM of (module Cipher_block.S.CCM with type key = 'k) | GCM of (module Cipher_block.S.GCM with type key = 'k) type 'k aead_state = { cipher : 'k aead_cipher ; cipher_secret : 'k ; nonce : nonce } type cipher_st = | Stream : 'k stream_state -> cipher_st | CBC : 'k cbc_state -> cipher_st | AEAD : 'k aead_state -> cipher_st stubs -- rethink how to play with crypto . let sexp_of_cipher_st = function | Stream _ -> Sexp.Atom "<stream-state>" | CBC _ -> Sexp.Atom "<cbc-state>" | AEAD _ -> Sexp.Atom "<aead-state>" let cipher_st_of_sexp = Conv.of_sexp_error "cipher_st_of_sexp: not implemented" type crypto_context = { } [@@deriving sexp] type hs_log = Cstruct.t list [@@deriving sexp] diffie hellman group and secret type dh_sent = Dh.group * Dh.secret [@@deriving sexp] type reneg_params = Cstruct.t * Cstruct.t [@@deriving sexp] type session_data = { 32 bytes random from the server hello 32 bytes random from the client hello version in client hello ( needed in RSA client key exchange ) ciphersuite : Ciphersuite.ciphersuite ; peer_certificate_chain : X509.t list ; peer_certificate : X509.t option ; trust_anchor : X509.t option ; received_certificates : X509.t list ; own_certificate : X509.t list ; own_private_key : Nocrypto.Rsa.priv option ; master_secret : master_secret ; own_name : string option ; client_auth : bool ; session_id : Cstruct.t ; extended_ms : bool ; } [@@deriving sexp] type server_handshake_state = | AwaitClientHelloRenegotiate | AwaitClientCertificate_RSA of session_data * hs_log | AwaitClientCertificate_DHE_RSA of session_data * dh_sent * hs_log server hello done is sent , and RSA key exchange used , waiting for a client key exchange message server hello done is sent , and DHE_RSA key exchange used , waiting for client key exchange | AwaitClientCertificateVerify of session_data * crypto_context * crypto_context * hs_log [@@deriving sexp] type client_handshake_state = certificate expected with RSA key exchange certificate expected with DHE_RSA key exchange server key exchange expected with DHE_RSA server hello done expected , client key exchange and premastersecret are ready server hello done expected , client key exchange and premastersecret are ready [@@deriving sexp] type handshake_machina_state = | Client of client_handshake_state | Server of server_handshake_state [@@deriving sexp] type handshake_state = { session : session_data list ; protocol_version : tls_version ; } [@@deriving sexp] type crypto_state = crypto_context option [@@deriving sexp] type record = Packet.content_type * Cstruct.t [@@deriving sexp] type rec_resp = [ either instruction to change the encryptor to the given one either change the decryptor to the given one ] type handshake_return = handshake_state * rec_resp list type state = { } [@@deriving sexp] type error = [ | `AuthenticationFailure of X509.Validation.validation_error | `NoConfiguredCiphersuite of Ciphersuite.ciphersuite list | `NoConfiguredVersion of tls_version | `NoConfiguredHash of Hash.hash list | `NoMatchingCertificateFound of string | `NoCertificateConfigured | `CouldntSelectCertificate ] [@@deriving sexp] type fatal = [ | `NoSecureRenegotiation | `NoCiphersuite of Packet.any_ciphersuite list | `NoVersion of tls_any_version | `ReaderError of Reader.error | `NoCertificateReceived | `NotRSACertificate | `NotRSASignature | `KeyTooSmall | `RSASignatureMismatch | `RSASignatureVerificationFailed | `HashAlgorithmMismatch | `BadCertificateChain | `MACMismatch | `MACUnderflow | `RecordOverflow of int | `UnknownRecordVersion of int * int | `UnknownContentType of int | `CannotHandleApplicationDataYet | `NoHeartbeat | `BadRecordVersion of tls_any_version | `BadFinished | `HandshakeFragmentsNotEmpty | `InvalidDH | `InvalidRenegotiation | `InvalidClientHello | `InvalidServerHello | `InvalidRenegotiationVersion of tls_version | `InappropriateFallback | `UnexpectedCCS | `UnexpectedHandshake of tls_handshake | `InvalidCertificateUsage | `InvalidCertificateExtendedUsage | `InvalidSession | `NoApplicationProtocol ] [@@deriving sexp] type failure = [ | `Error of error | `Fatal of fatal ] [@@deriving sexp] Monadic control - flow core . include Control.Or_error_make (struct type err = failure end) type 'a eff = 'a t include Result
1d84d9179529e2775cc48b3304c0a4b79fd82c32d35fbd73153d440e107bef7b
theoremprover-museum/LCF77
dml.lsp
(MAPC (FUNCTION (LAMBDA (A) (EVLIST (QUOTE DML') (CAR A) 2 (CADR A) (CDDR A)))) (QUOTE ((* *TIMES (int # int) /-> int) (// DIV (int # int) /-> int) (/+ *PLUS (int # int) /-> int) (/- *DIF (int # int) /-> int) (= EQUAL (%a # %a) /-> bool) (< *LESS (int # int) /-> bool) (> *GREAT (int # int) /-> bool) (%& AND (bool # bool) /-> bool) (%or OR (bool # bool) /-> bool) (/@ *APPEND ((%a list) # (%a list)) /-> (%a list)) (/. CONS (%a # (%a list)) /-> (%a list))))) (MAPC (FUNCTION (LAMBDA (A) (EVLIST (QUOTE DML') (CAR A) 1 (CADR A) (CDDR A)))) (QUOTE ((%/- MINUS int /-> int) (not NOT bool /-> bool) (null NULL (%a list) /-> bool) (fst CAR (%a # %b) /-> %a) (snd CDR (%a # %b) /-> %b)))) (DMLC nil NIL (%a list)) (PUTPROP (QUOTE do) 1 (QUOTE NUMARGS)) (PUTPROP (QUOTE do) (MKTIDY (QUOTE (%a /-> /.))) (QUOTE MLTYPE)) (PUTPROP (QUOTE hd) 1 (QUOTE NUMARGS)) (PUTPROP (QUOTE hd) (MKTIDY (QUOTE ((%a list) /-> %a))) (QUOTE MLTYPE)) (PUTPROP (QUOTE tl) 1 (QUOTE NUMARGS)) (PUTPROP (QUOTE tl) (MKTIDY (QUOTE ((%a list) /-> (%a list)))) (QUOTE MLTYPE)) (PUTPROP (QUOTE isl) 1 (QUOTE NUMARGS)) (PUTPROP (QUOTE isl) (MKTIDY (QUOTE ((%a /+ %b) /-> bool))) (QUOTE MLTYPE)) (PUTPROP (QUOTE isr) 1 (QUOTE NUMARGS)) (PUTPROP (QUOTE isr) (MKTIDY (QUOTE ((%a /+ %b) /-> bool))) (QUOTE MLTYPE)) (PUTPROP (QUOTE outl) 1 (QUOTE NUMARGS)) (PUTPROP (QUOTE outl) (MKTIDY (QUOTE ((%a /+ %b) /-> %a))) (QUOTE MLTYPE)) (PUTPROP (QUOTE outr) 1 (QUOTE NUMARGS)) (PUTPROP (QUOTE outr) (MKTIDY (QUOTE ((%a /+ %b) /-> %b))) (QUOTE MLTYPE)) (PUTPROP (QUOTE inl) 1 (QUOTE NUMARGS)) (PUTPROP (QUOTE inl) (MKTIDY (QUOTE (%a /-> (%a /+ %b)))) (QUOTE MLTYPE)) (PUTPROP (QUOTE inr) 1 (QUOTE NUMARGS)) (PUTPROP (QUOTE inr) (MKTIDY (QUOTE (%b /-> (%a /+ %b)))) (QUOTE MLTYPE)) (SETQ EMPTYTOK (GENSYM)) (PUTPROP (QUOTE explode) 1 (QUOTE NUMARGS)) (PUTPROP (QUOTE explode) (MKTIDY (QUOTE (token /-> (token list)))) (QUOTE MLTYPE)) (PUTPROP (QUOTE implode) 1 (QUOTE NUMARGS)) (PUTPROP (QUOTE implode) (MKTIDY (QUOTE ((token list) /-> token))) (QUOTE MLTYPE)) (PUTPROP (QUOTE mlinfix) 1 (QUOTE NUMARGS)) (PUTPROP (QUOTE mlinfix) (MKTIDY (QUOTE (token /-> /.))) (QUOTE MLTYPE)) (PUTPROP (QUOTE mlcinfix) 1 (QUOTE NUMARGS)) (PUTPROP (QUOTE mlcinfix) (MKTIDY (QUOTE (token /-> /.))) (QUOTE MLTYPE)) (DML' gentok 0 GENSYM (/. /-> tok)) (PUTPROP (QUOTE mlin) 2 (QUOTE NUMARGS)) (PUTPROP (QUOTE mlin) (MKTIDY (QUOTE ((token # bool) /-> /.))) (QUOTE MLTYPE))
null
https://raw.githubusercontent.com/theoremprover-museum/LCF77/7a43e95deee18ae37389d98e184b38fdfb3df923/src/dml.lsp
lisp
(MAPC (FUNCTION (LAMBDA (A) (EVLIST (QUOTE DML') (CAR A) 2 (CADR A) (CDDR A)))) (QUOTE ((* *TIMES (int # int) /-> int) (// DIV (int # int) /-> int) (/+ *PLUS (int # int) /-> int) (/- *DIF (int # int) /-> int) (= EQUAL (%a # %a) /-> bool) (< *LESS (int # int) /-> bool) (> *GREAT (int # int) /-> bool) (%& AND (bool # bool) /-> bool) (%or OR (bool # bool) /-> bool) (/@ *APPEND ((%a list) # (%a list)) /-> (%a list)) (/. CONS (%a # (%a list)) /-> (%a list))))) (MAPC (FUNCTION (LAMBDA (A) (EVLIST (QUOTE DML') (CAR A) 1 (CADR A) (CDDR A)))) (QUOTE ((%/- MINUS int /-> int) (not NOT bool /-> bool) (null NULL (%a list) /-> bool) (fst CAR (%a # %b) /-> %a) (snd CDR (%a # %b) /-> %b)))) (DMLC nil NIL (%a list)) (PUTPROP (QUOTE do) 1 (QUOTE NUMARGS)) (PUTPROP (QUOTE do) (MKTIDY (QUOTE (%a /-> /.))) (QUOTE MLTYPE)) (PUTPROP (QUOTE hd) 1 (QUOTE NUMARGS)) (PUTPROP (QUOTE hd) (MKTIDY (QUOTE ((%a list) /-> %a))) (QUOTE MLTYPE)) (PUTPROP (QUOTE tl) 1 (QUOTE NUMARGS)) (PUTPROP (QUOTE tl) (MKTIDY (QUOTE ((%a list) /-> (%a list)))) (QUOTE MLTYPE)) (PUTPROP (QUOTE isl) 1 (QUOTE NUMARGS)) (PUTPROP (QUOTE isl) (MKTIDY (QUOTE ((%a /+ %b) /-> bool))) (QUOTE MLTYPE)) (PUTPROP (QUOTE isr) 1 (QUOTE NUMARGS)) (PUTPROP (QUOTE isr) (MKTIDY (QUOTE ((%a /+ %b) /-> bool))) (QUOTE MLTYPE)) (PUTPROP (QUOTE outl) 1 (QUOTE NUMARGS)) (PUTPROP (QUOTE outl) (MKTIDY (QUOTE ((%a /+ %b) /-> %a))) (QUOTE MLTYPE)) (PUTPROP (QUOTE outr) 1 (QUOTE NUMARGS)) (PUTPROP (QUOTE outr) (MKTIDY (QUOTE ((%a /+ %b) /-> %b))) (QUOTE MLTYPE)) (PUTPROP (QUOTE inl) 1 (QUOTE NUMARGS)) (PUTPROP (QUOTE inl) (MKTIDY (QUOTE (%a /-> (%a /+ %b)))) (QUOTE MLTYPE)) (PUTPROP (QUOTE inr) 1 (QUOTE NUMARGS)) (PUTPROP (QUOTE inr) (MKTIDY (QUOTE (%b /-> (%a /+ %b)))) (QUOTE MLTYPE)) (SETQ EMPTYTOK (GENSYM)) (PUTPROP (QUOTE explode) 1 (QUOTE NUMARGS)) (PUTPROP (QUOTE explode) (MKTIDY (QUOTE (token /-> (token list)))) (QUOTE MLTYPE)) (PUTPROP (QUOTE implode) 1 (QUOTE NUMARGS)) (PUTPROP (QUOTE implode) (MKTIDY (QUOTE ((token list) /-> token))) (QUOTE MLTYPE)) (PUTPROP (QUOTE mlinfix) 1 (QUOTE NUMARGS)) (PUTPROP (QUOTE mlinfix) (MKTIDY (QUOTE (token /-> /.))) (QUOTE MLTYPE)) (PUTPROP (QUOTE mlcinfix) 1 (QUOTE NUMARGS)) (PUTPROP (QUOTE mlcinfix) (MKTIDY (QUOTE (token /-> /.))) (QUOTE MLTYPE)) (DML' gentok 0 GENSYM (/. /-> tok)) (PUTPROP (QUOTE mlin) 2 (QUOTE NUMARGS)) (PUTPROP (QUOTE mlin) (MKTIDY (QUOTE ((token # bool) /-> /.))) (QUOTE MLTYPE))
d937b196e2778bc40075d972948d5f35480f2b450ece84e78b7060998bd00e27
chetmurthy/pa_ppx
std.mli
(****************************************************************************) The Calculus of Inductive Constructions (* *) Projet Coq (* *) INRIA LRI - CNRS ENS - CNRS Rocquencourt Lyon (* *) (* Coq V6.2 *) May 1st 1998 (* *) (****************************************************************************) (* std.mli *) (****************************************************************************) val pair : 'a -> 'b -> 'a * 'b val fst3 : ('a * 'b * 'c) -> 'a val snd3 : ('a * 'b * 'c) -> 'b val third3 : ('a * 'b * 'c) -> 'c val fst4 : ('a * 'b * 'c * 'd) -> 'a val snd4 : ('a * 'b * 'c * 'd) -> 'b val third4 : ('a * 'b * 'c * 'd) -> 'c val fourth4 : ('a * 'b * 'c * 'd) -> 'd val nth1 : 'a list -> int -> 'a returns the n - th element of the given list , where the head of the list is at position 1 val sep_firstn : int -> 'a list -> 'a list * 'a list val sep_last : 'a list -> 'a * 'a list val sizebin_of_string : string -> int val sizebin64_of_string : string -> int64 val string_of_sizebin64 : int64 -> string val string_of_sizebin : int -> string val car : 'a list -> 'a val cdr : 'a list -> 'a list val cddr : 'a list -> 'a list val cdddr : 'a list -> 'a list val safe_cdr : 'a list -> 'a list val safe_cddr : 'a list -> 'a list val safe_cdddr : 'a list -> 'a list val cadr : 'a list -> 'a val caddr : 'a list -> 'a val except : 'a -> 'a list -> 'a list val try_find : ('a -> 'b) -> 'a list -> 'b val filter : ('a -> bool) -> 'a list -> 'a list val last : 'a list -> 'a val firstn : int -> 'a list -> 'a list (* Maps f on the sublist of l where f does not raise an exception Failure _ *) For example , if ( f x2 ) and ( f x4 ) both raise the exception Failure _ map_succed f [ x1 ; x2 ; x3 ; ; x5 ; ] evaluates to [ f x1 ; f X3 ; f x5 ; f x6 ] map_succed f [x1; x2; x3; x4; x5; x6] evaluates to [f x1; f X3; f x5; f x6] *) val map_succeed : ('a -> 'b) -> 'a list -> 'b list val map3 : ('a -> 'b -> 'c -> 'd) -> 'a list -> 'b list -> 'c list -> 'd list val distinct : 'a list -> bool val interval : int -> int -> int list val interval_int32 : int32 -> int32 -> int32 list val range : int -> int list val range_int32 : int32 -> int32 list val push : 'a list ref -> 'a -> unit val pop : 'a list ref -> unit val top : 'a list ref -> 'a type ('a,'b) union = Inl of 'a | Inr of 'b val isl : ('a,'b) union -> bool val isr : ('a,'b) union -> bool val outl : ('a,'b) union -> 'a val outr : ('a,'b) union -> 'b (************************************************************************) (* sets operations on lists; *) (* for an abstract and baltree version of sets, use module Set *) val uniquize : 'a list -> 'a list (* remove redundant elements *) val make_set : 'a list -> 'a list (* synonym of uniquize *) val add_set : 'a -> 'a list -> 'a list (* add if not present *) val rmv_set : 'a -> 'a list -> 'a list val intersect : 'a list -> 'a list -> 'a list val union : 'a list -> 'a list -> 'a list . for large sets val unionq : 'a list -> 'a list -> 'a list (* with == instead of = *) val diff_set : 'a list -> 'a list -> 'a list val subtract : 'a list -> 'a list -> 'a list (* synonym of diff_set *) val subtractq : 'a list -> 'a list -> 'a list (* with == instead of = *) val symdiff : 'a list -> 'a list -> 'a list val subset : 'a list -> 'a list -> bool val same_members : 'a list -> 'a list -> bool val map_option : ('a -> 'b) -> 'a option -> 'b option val isNone : 'a option -> bool val isSome : 'a option -> bool val inSome : 'a -> 'a option val outSome : 'a option -> 'a val plist : ('a Stream.t -> 'b) -> 'a Stream.t -> 'b list val plist_until : ('a Stream.t -> 'b list) -> ('a Stream.t -> 'b) -> 'a Stream.t -> 'b list val parse_fully : ('a Stream.t -> 'b) -> 'a Stream.t -> 'b val string_suffix : string -> int -> string val starts_with : ?improper:bool -> pat:string -> string -> bool val ends_with : pat:string -> string -> bool val fold_option : ('a -> 'b) -> 'b -> 'a option -> 'b val apply_to_in_channel : (in_channel -> 'a) -> string -> 'a val apply_to_out_channel : (out_channel -> 'a) -> string -> 'a val do_option : ('a -> unit) -> 'a option -> unit val implode_chars : char list -> string val list_of_stream : 'a Stream.t -> 'a list val nway_partition : ('a -> 'a -> bool) -> 'a list -> 'a list list val read_ic_fully : ?msg:string -> ?channel:in_channel -> unit -> string val app_i : (int -> 'a -> 'b) -> int -> 'a list -> unit module ColumnFormat : sig val format0 : int -> string list -> string array array val formatted_width : ncols:int -> string list -> int * int array * string array array val format : width:int -> string list -> string array array val output : ?width:int -> out_channel -> string list -> unit end val invoked_with : ?flag:string -> string -> bool val split : ('a * 'b) list -> ('a list * 'b list) val split_option : ('a * 'b) option -> ('a option * 'b option) val combine : 'a list -> 'b list -> ('a * 'b) list val slice_string : ?spos:int -> ?epos:int -> string -> string val pred_or : ('a -> bool) list -> 'a -> bool
null
https://raw.githubusercontent.com/chetmurthy/pa_ppx/7c662fcf4897c978ae8a5ea230af0e8b2fa5858b/util-lib/std.mli
ocaml
************************************************************************** Coq V6.2 ************************************************************************** std.mli ************************************************************************** Maps f on the sublist of l where f does not raise an exception Failure _ ********************************************************************** sets operations on lists; for an abstract and baltree version of sets, use module Set remove redundant elements synonym of uniquize add if not present with == instead of = synonym of diff_set with == instead of =
The Calculus of Inductive Constructions Projet Coq INRIA LRI - CNRS ENS - CNRS Rocquencourt Lyon May 1st 1998 val pair : 'a -> 'b -> 'a * 'b val fst3 : ('a * 'b * 'c) -> 'a val snd3 : ('a * 'b * 'c) -> 'b val third3 : ('a * 'b * 'c) -> 'c val fst4 : ('a * 'b * 'c * 'd) -> 'a val snd4 : ('a * 'b * 'c * 'd) -> 'b val third4 : ('a * 'b * 'c * 'd) -> 'c val fourth4 : ('a * 'b * 'c * 'd) -> 'd val nth1 : 'a list -> int -> 'a returns the n - th element of the given list , where the head of the list is at position 1 val sep_firstn : int -> 'a list -> 'a list * 'a list val sep_last : 'a list -> 'a * 'a list val sizebin_of_string : string -> int val sizebin64_of_string : string -> int64 val string_of_sizebin64 : int64 -> string val string_of_sizebin : int -> string val car : 'a list -> 'a val cdr : 'a list -> 'a list val cddr : 'a list -> 'a list val cdddr : 'a list -> 'a list val safe_cdr : 'a list -> 'a list val safe_cddr : 'a list -> 'a list val safe_cdddr : 'a list -> 'a list val cadr : 'a list -> 'a val caddr : 'a list -> 'a val except : 'a -> 'a list -> 'a list val try_find : ('a -> 'b) -> 'a list -> 'b val filter : ('a -> bool) -> 'a list -> 'a list val last : 'a list -> 'a val firstn : int -> 'a list -> 'a list For example , if ( f x2 ) and ( f x4 ) both raise the exception Failure _ map_succed f [ x1 ; x2 ; x3 ; ; x5 ; ] evaluates to [ f x1 ; f X3 ; f x5 ; f x6 ] map_succed f [x1; x2; x3; x4; x5; x6] evaluates to [f x1; f X3; f x5; f x6] *) val map_succeed : ('a -> 'b) -> 'a list -> 'b list val map3 : ('a -> 'b -> 'c -> 'd) -> 'a list -> 'b list -> 'c list -> 'd list val distinct : 'a list -> bool val interval : int -> int -> int list val interval_int32 : int32 -> int32 -> int32 list val range : int -> int list val range_int32 : int32 -> int32 list val push : 'a list ref -> 'a -> unit val pop : 'a list ref -> unit val top : 'a list ref -> 'a type ('a,'b) union = Inl of 'a | Inr of 'b val isl : ('a,'b) union -> bool val isr : ('a,'b) union -> bool val outl : ('a,'b) union -> 'a val outr : ('a,'b) union -> 'b val rmv_set : 'a -> 'a list -> 'a list val intersect : 'a list -> 'a list -> 'a list val union : 'a list -> 'a list -> 'a list . for large sets val diff_set : 'a list -> 'a list -> 'a list val symdiff : 'a list -> 'a list -> 'a list val subset : 'a list -> 'a list -> bool val same_members : 'a list -> 'a list -> bool val map_option : ('a -> 'b) -> 'a option -> 'b option val isNone : 'a option -> bool val isSome : 'a option -> bool val inSome : 'a -> 'a option val outSome : 'a option -> 'a val plist : ('a Stream.t -> 'b) -> 'a Stream.t -> 'b list val plist_until : ('a Stream.t -> 'b list) -> ('a Stream.t -> 'b) -> 'a Stream.t -> 'b list val parse_fully : ('a Stream.t -> 'b) -> 'a Stream.t -> 'b val string_suffix : string -> int -> string val starts_with : ?improper:bool -> pat:string -> string -> bool val ends_with : pat:string -> string -> bool val fold_option : ('a -> 'b) -> 'b -> 'a option -> 'b val apply_to_in_channel : (in_channel -> 'a) -> string -> 'a val apply_to_out_channel : (out_channel -> 'a) -> string -> 'a val do_option : ('a -> unit) -> 'a option -> unit val implode_chars : char list -> string val list_of_stream : 'a Stream.t -> 'a list val nway_partition : ('a -> 'a -> bool) -> 'a list -> 'a list list val read_ic_fully : ?msg:string -> ?channel:in_channel -> unit -> string val app_i : (int -> 'a -> 'b) -> int -> 'a list -> unit module ColumnFormat : sig val format0 : int -> string list -> string array array val formatted_width : ncols:int -> string list -> int * int array * string array array val format : width:int -> string list -> string array array val output : ?width:int -> out_channel -> string list -> unit end val invoked_with : ?flag:string -> string -> bool val split : ('a * 'b) list -> ('a list * 'b list) val split_option : ('a * 'b) option -> ('a option * 'b option) val combine : 'a list -> 'b list -> ('a * 'b) list val slice_string : ?spos:int -> ?epos:int -> string -> string val pred_or : ('a -> bool) list -> 'a -> bool
95affcbc9c6892bfd59c699d02d2c30e6d043f7592ebf945073c4db19d9b3741
haskell-tools/haskell-tools
ExplicitNamespacesChecker.hs
module Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.ExplicitNamespacesChecker where import Control.Reference ((^.)) import Language.Haskell.Tools.AST import Language.Haskell.Tools.Refactor import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.ExtMonad chkExplicitNamespacesIESpec :: CheckNode IESpec chkExplicitNamespacesIESpec = conditional chkIESpec ExplicitNamespaces where chkIESpec :: CheckNode IESpec chkIESpec x@(IESpec (AnnJust imod) _ _) | UImportType <- imod ^. element = addEvidence ExplicitNamespaces x chkIESpec x = return x
null
https://raw.githubusercontent.com/haskell-tools/haskell-tools/b1189ab4f63b29bbf1aa14af4557850064931e32/src/builtin-refactorings/Language/Haskell/Tools/Refactor/Builtin/ExtensionOrganizer/Checkers/ExplicitNamespacesChecker.hs
haskell
module Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.ExplicitNamespacesChecker where import Control.Reference ((^.)) import Language.Haskell.Tools.AST import Language.Haskell.Tools.Refactor import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.ExtMonad chkExplicitNamespacesIESpec :: CheckNode IESpec chkExplicitNamespacesIESpec = conditional chkIESpec ExplicitNamespaces where chkIESpec :: CheckNode IESpec chkIESpec x@(IESpec (AnnJust imod) _ _) | UImportType <- imod ^. element = addEvidence ExplicitNamespaces x chkIESpec x = return x
b448d44f1fae14c4b85b4980e48a70926a0f4eeee06b8820189d74d3e17f2a1c
martijnbastiaan/doctest-parallel
Foo.hs
-- | -- Examples in various locations... -- -- Some random text. Some random text. Some random text. Some random text. -- Some random text. Some random text. Some random text. Some random text. -- Some random text. -- > > > let x = 10 -- -- Some random text. Some random text. Some random text. Some random text. -- Some random text. Some random text. Some random text. Some random text. -- Some random text. -- -- > > > baz " foobar " module TestCommentLocation.Foo ( | Some documentation not attached to a particular entity -- > > > test 10 -- *** Exception: Prelude.undefined -- ... test, -- | > > > fib 10 55 fib, -- | -- >>> bar -- "bar" bar, foo, baz ) where -- | My test -- > > > test 20 -- *** Exception: Prelude.undefined -- ... test :: Integer -> Integer test = undefined | Note that examples for ' fib ' include the two examples below and the one example with ^ syntax after ' fix ' -- -- >>> foo -- "foo" {- | Example: >>> fib 10 55 -} -- | Calculate Fibonacci number of given `n`. fib :: Integer -- ^ given `n` -- > > > fib 10 55 -> Integer -- ^ Fibonacci of given `n` -- > > > baz " foobar " fib 0 = 0 fib 1 = 1 fib n = fib (n - 1) + fib (n - 2) -- ^ Example: -- -- >>> fib 5 -- 5 foo = "foo" bar = "bar" baz = foo ++ bar
null
https://raw.githubusercontent.com/martijnbastiaan/doctest-parallel/f70d6a1c946cc0ada88571b90a39a7cd4d065452/test/integration/TestCommentLocation/Foo.hs
haskell
| Examples in various locations... Some random text. Some random text. Some random text. Some random text. Some random text. Some random text. Some random text. Some random text. Some random text. Some random text. Some random text. Some random text. Some random text. Some random text. Some random text. Some random text. Some random text. Some random text. *** Exception: Prelude.undefined ... | | >>> bar "bar" | My test *** Exception: Prelude.undefined ... >>> foo "foo" | Example: >>> fib 10 55 | Calculate Fibonacci number of given `n`. ^ given `n` ^ Fibonacci of given `n` ^ Example: >>> fib 5 5
> > > let x = 10 > > > baz " foobar " module TestCommentLocation.Foo ( | Some documentation not attached to a particular entity > > > test 10 test, > > > fib 10 55 fib, bar, foo, baz ) where > > > test 20 test :: Integer -> Integer test = undefined | Note that examples for ' fib ' include the two examples below and the one example with ^ syntax after ' fix ' > > > fib 10 55 > > > baz " foobar " fib 0 = 0 fib 1 = 1 fib n = fib (n - 1) + fib (n - 2) foo = "foo" bar = "bar" baz = foo ++ bar
712df7291631152aae5bc933dea61436cc6c7c2cf707349bbdf6310c97fa2bee
bmeurer/ocaml-arm
exit_codes.mli
(***********************************************************************) (* ocamlbuild *) (* *) , , projet Gallium , INRIA Rocquencourt (* *) Copyright 2007 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . (* *) (***********************************************************************) val rc_ok : int val rc_usage : int val rc_failure : int val rc_invalid_argument : int val rc_system_error : int val rc_hygiene : int val rc_circularity : int val rc_solver_failed : int val rc_ocamldep_error : int val rc_lexing_error : int val rc_build_error : int val rc_executor_subcommand_failed : int val rc_executor_subcommand_got_signal : int val rc_executor_io_error : int val rc_executor_excetptional_condition : int
null
https://raw.githubusercontent.com/bmeurer/ocaml-arm/43f7689c76a349febe3d06ae7a4fc1d52984fd8b/ocamlbuild/exit_codes.mli
ocaml
********************************************************************* ocamlbuild *********************************************************************
, , projet Gallium , INRIA Rocquencourt Copyright 2007 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . val rc_ok : int val rc_usage : int val rc_failure : int val rc_invalid_argument : int val rc_system_error : int val rc_hygiene : int val rc_circularity : int val rc_solver_failed : int val rc_ocamldep_error : int val rc_lexing_error : int val rc_build_error : int val rc_executor_subcommand_failed : int val rc_executor_subcommand_got_signal : int val rc_executor_io_error : int val rc_executor_excetptional_condition : int
b87261f45ed91b167421f2d132a004f704a4e7363e0a560771a4753b30c46415
iambrj/imin
interp-Rwhile.rkt
#lang racket (require racket/fixnum) (require "utilities.rkt") (require "interp-Rany.rkt") (provide interp-Rwhile interp-Rwhile-class) ;; Note to maintainers of this code: ;; A copy of this interpreter is in the book and should be ;; kept in sync with this code. (define interp-Rwhile-class (class interp-Rany-class (super-new) (define/override ((interp-exp env) e) (verbose "Rwhile/interp-exp" e) (define recur (interp-exp env)) (define result (match e [(SetBang x rhs) (set-box! (lookup x env) (recur rhs))] [(WhileLoop cnd body) (define (loop) (cond [(recur cnd) (recur body) (loop)] [else (void)])) (loop)] [(Begin es body) (for ([e es]) (recur e)) (recur body)] [else ((super interp-exp env) e)])) (verbose "Rwhile/interp-exp" e result) result) )) (define (interp-Rwhile p) (send (new interp-Rwhile-class) interp-program p))
null
https://raw.githubusercontent.com/iambrj/imin/baf9e829c2aa85b69a2e86bfba320969ddf05f95/interp-Rwhile.rkt
racket
Note to maintainers of this code: A copy of this interpreter is in the book and should be kept in sync with this code.
#lang racket (require racket/fixnum) (require "utilities.rkt") (require "interp-Rany.rkt") (provide interp-Rwhile interp-Rwhile-class) (define interp-Rwhile-class (class interp-Rany-class (super-new) (define/override ((interp-exp env) e) (verbose "Rwhile/interp-exp" e) (define recur (interp-exp env)) (define result (match e [(SetBang x rhs) (set-box! (lookup x env) (recur rhs))] [(WhileLoop cnd body) (define (loop) (cond [(recur cnd) (recur body) (loop)] [else (void)])) (loop)] [(Begin es body) (for ([e es]) (recur e)) (recur body)] [else ((super interp-exp env) e)])) (verbose "Rwhile/interp-exp" e result) result) )) (define (interp-Rwhile p) (send (new interp-Rwhile-class) interp-program p))
2c766c1c3bd917394329f74ef3f5f707debd21dc3cde18c50a757df3e93c947c
philoskim/debux
util.cljc
(ns debux.cs.util "Utilities for clojurescript only" (:require [clojure.string :as str] #?@(:bb [] :default [[cljs.analyzer.api :as ana]]) #?(:cljs [cljs.pprint :as pp]) [debux.common.util :as ut] )) ;;; caching (def ^:private prev-returns* (atom {})) (defn changed? "Checks if prev-returns* contains <form>." [form return] ;; init (when-not (contains? @prev-returns* form) (swap! prev-returns* assoc form "")) ;; update (and (not= return (get @prev-returns* form)) (swap! prev-returns* assoc form return) )) ;;; styling (def style* (atom {:error "background-color: red; color: white" :warn "background-color: green; color: white" :info "background-color: #0000cd; color: white" :debug "background-color: #ffc125; color: black" :normal "background-color: white; color: black" :title "background-color: white; color: #8b008b"} )) (defn- get-style [style] (cond (keyword? style) (cond (#{:error :e} style) (:error @style*) (#{:warn :w} style) (:warn @style*) (#{:info :i} style) (:info @style*) (#{:debug :d} style) (:debug @style*) :else (get @style* style)) (string? style) style)) (defn merge-styles "Merges <new-style> into style*. <new-style {<style-name kw, style-value str>+}>" [new-style] (swap! style* merge new-style)) ;;; printing for browser console #?(:cljs (defn form-header [form & [msg]] (str "%c " (ut/truncate (pr-str form)) " %c" (and msg (str " <" msg ">")) " =>") )) #?(:cljs (defn clog-title [src-info title form-style] (when (:source-info-mode @ut/config*) (.log js/console (ut/prepend-bullets-in-line src-info (dec ut/*indent-level*)) )) (.log js/console (ut/prepend-bullets-in-line title (dec ut/*indent-level*)) (:title @style*) (get-style form-style) (:normal @style*) ))) #?(:cljs (defn clog-form-with-indent [form style] (.log js/console (ut/prepend-bullets form ut/*indent-level*) (get-style style) (:normal @style*) ))) #?(:cljs (defn clog-result-with-indent [result & [js-mode]] (let [pprint (str/trim (with-out-str (pp/pprint result))) prefix (str (ut/make-bullets ut/*indent-level*) " ")] (if (:cljs-devtools @ut/config*) (.log js/console prefix result) (.log js/console (->> (str/split pprint #"\n") (mapv #(str prefix %)) (str/join "\n") ))) (when js-mode (.log js/console "%s %c<js>%c %O" prefix (:info @style*) (:normal @style*) result) )))) #?(:cljs (defn clog-locals-with-indent [result style & [js-mode]] (.log js/console (ut/prepend-bullets "%c :locals %c =>" ut/*indent-level*) (get-style style) (:normal @style*)) (clog-result-with-indent result js-mode))) ;;; spy functions #?(:cljs (defn spy-first [result quoted-form {:keys [msg style js] :as opts}] (clog-form-with-indent (form-header quoted-form msg) (or style :debug)) (clog-result-with-indent result js) result)) #?(:cljs (defn spy-last [quoted-form {:keys [msg style js] :as opts} result] (clog-form-with-indent (form-header quoted-form msg) (or style :debug)) (clog-result-with-indent result js) result)) #?(:cljs (defn spy-comp [quoted-form form {:keys [msg style js] :as opts}] (fn [& arg] (binding [ut/*indent-level* (inc ut/*indent-level*)] (let [result (apply form arg)] (clog-form-with-indent (form-header quoted-form msg) (or style :debug)) (clog-result-with-indent result js) result) )))) ;;; spy macros #?(:clj (defmacro spy [form {:keys [msg style js] :as opts}] `(let [result# ~form] (clog-form-with-indent (form-header '~form ~msg) (or ~style :debug)) (clog-result-with-indent result# ~js) result#) )) #?(:clj (defmacro spy-first2 [pre-result form {:keys [msg style js] :as opts}] `(let [result# (-> ~pre-result ~form)] (clog-form-with-indent (form-header '~form ~msg) (or ~style :debug)) (clog-result-with-indent result# ~js) result#) )) #?(:clj (defmacro spy-last2 [form {:keys [msg style js] :as opts} pre-result] `(let [result# (->> ~pre-result ~form)] (clog-form-with-indent (form-header '~form ~msg) (or ~style :debug)) (clog-result-with-indent result# ~js) result#) ))
null
https://raw.githubusercontent.com/philoskim/debux/26771cb65534f6f80f521b44c38f14e274f2332f/src/debux/cs/util.cljc
clojure
caching init update styling printing for browser console spy functions spy macros
(ns debux.cs.util "Utilities for clojurescript only" (:require [clojure.string :as str] #?@(:bb [] :default [[cljs.analyzer.api :as ana]]) #?(:cljs [cljs.pprint :as pp]) [debux.common.util :as ut] )) (def ^:private prev-returns* (atom {})) (defn changed? "Checks if prev-returns* contains <form>." [form return] (when-not (contains? @prev-returns* form) (swap! prev-returns* assoc form "")) (and (not= return (get @prev-returns* form)) (swap! prev-returns* assoc form return) )) (def style* (atom {:error "background-color: red; color: white" :warn "background-color: green; color: white" :info "background-color: #0000cd; color: white" :debug "background-color: #ffc125; color: black" :normal "background-color: white; color: black" :title "background-color: white; color: #8b008b"} )) (defn- get-style [style] (cond (keyword? style) (cond (#{:error :e} style) (:error @style*) (#{:warn :w} style) (:warn @style*) (#{:info :i} style) (:info @style*) (#{:debug :d} style) (:debug @style*) :else (get @style* style)) (string? style) style)) (defn merge-styles "Merges <new-style> into style*. <new-style {<style-name kw, style-value str>+}>" [new-style] (swap! style* merge new-style)) #?(:cljs (defn form-header [form & [msg]] (str "%c " (ut/truncate (pr-str form)) " %c" (and msg (str " <" msg ">")) " =>") )) #?(:cljs (defn clog-title [src-info title form-style] (when (:source-info-mode @ut/config*) (.log js/console (ut/prepend-bullets-in-line src-info (dec ut/*indent-level*)) )) (.log js/console (ut/prepend-bullets-in-line title (dec ut/*indent-level*)) (:title @style*) (get-style form-style) (:normal @style*) ))) #?(:cljs (defn clog-form-with-indent [form style] (.log js/console (ut/prepend-bullets form ut/*indent-level*) (get-style style) (:normal @style*) ))) #?(:cljs (defn clog-result-with-indent [result & [js-mode]] (let [pprint (str/trim (with-out-str (pp/pprint result))) prefix (str (ut/make-bullets ut/*indent-level*) " ")] (if (:cljs-devtools @ut/config*) (.log js/console prefix result) (.log js/console (->> (str/split pprint #"\n") (mapv #(str prefix %)) (str/join "\n") ))) (when js-mode (.log js/console "%s %c<js>%c %O" prefix (:info @style*) (:normal @style*) result) )))) #?(:cljs (defn clog-locals-with-indent [result style & [js-mode]] (.log js/console (ut/prepend-bullets "%c :locals %c =>" ut/*indent-level*) (get-style style) (:normal @style*)) (clog-result-with-indent result js-mode))) #?(:cljs (defn spy-first [result quoted-form {:keys [msg style js] :as opts}] (clog-form-with-indent (form-header quoted-form msg) (or style :debug)) (clog-result-with-indent result js) result)) #?(:cljs (defn spy-last [quoted-form {:keys [msg style js] :as opts} result] (clog-form-with-indent (form-header quoted-form msg) (or style :debug)) (clog-result-with-indent result js) result)) #?(:cljs (defn spy-comp [quoted-form form {:keys [msg style js] :as opts}] (fn [& arg] (binding [ut/*indent-level* (inc ut/*indent-level*)] (let [result (apply form arg)] (clog-form-with-indent (form-header quoted-form msg) (or style :debug)) (clog-result-with-indent result js) result) )))) #?(:clj (defmacro spy [form {:keys [msg style js] :as opts}] `(let [result# ~form] (clog-form-with-indent (form-header '~form ~msg) (or ~style :debug)) (clog-result-with-indent result# ~js) result#) )) #?(:clj (defmacro spy-first2 [pre-result form {:keys [msg style js] :as opts}] `(let [result# (-> ~pre-result ~form)] (clog-form-with-indent (form-header '~form ~msg) (or ~style :debug)) (clog-result-with-indent result# ~js) result#) )) #?(:clj (defmacro spy-last2 [form {:keys [msg style js] :as opts} pre-result] `(let [result# (->> ~pre-result ~form)] (clog-form-with-indent (form-header '~form ~msg) (or ~style :debug)) (clog-result-with-indent result# ~js) result#) ))
21c15dafa261393fbc1051bb73628df5499710326c2c686df290701591299f05
batterseapower/openshake
Files.hs
# LANGUAGE TypeFamilies , TypeOperators , GeneralizedNewtypeDeriving , FlexibleContexts , TupleSections , CPP # module Development.Shake.Files ( -- * File modification times ModTime, getFileModTime, -- * Normalised file paths CanonicalFilePath, canonical, -- * Rules for building files CreatesFiles, Rule, (*>), (*@>), (**>), (**@>), (?>), (?@>), addRule, -- * Requesting that files get built need, want ) where import Development.Shake.Core hiding (Rule, addRule, need) import qualified Development.Shake.Core as Core import Development.Shake.Core.Binary import Development.Shake.Core.Utilities import Development.Shake.Composition hiding (need) import qualified Development.Shake.Composition as Composition import Data.Binary import Control.DeepSeq import Control.Monad import Control.Monad.IO.Class import Data.Traversable (Traversable(traverse)) import Data.Int (Int64) import Data.List import Data.List.Split (splitOn) import qualified Data.Map as M import qualified Data.Set as S import Data.Time.Clock (UTCTime) import Data.Time.Clock.POSIX (utcTimeToPOSIXSeconds, posixSecondsToUTCTime) import System.Directory import System.Directory.AccessTime import System.FilePath (takeDirectory, equalFilePath, makeRelative, (</>)) import System.FilePath.Glob import System.Time (ClockTime(..)) type ModTime = UTCTime -- TODO: remove orphan instance instance Binary UTCTime where get = getModTime put = putModTime getModTime :: Get ModTime getModTime = fmap (posixSecondsToUTCTime . (/ 1000) . fromIntegral) (get :: Get Int64) putModTime :: ModTime -> Put putModTime mtime = put (round (utcTimeToPOSIXSeconds mtime * 1000) :: Int64) getFileModTime :: FilePath -> IO (Maybe ModTime) getFileModTime fp = handleDoesNotExist (return Nothing) (fmap Just (getModificationTime fp)) data CanonicalFilePath = UnsafeCanonicalise { originalFilePath :: FilePath, canonicalFilePath :: FilePath } instance Show CanonicalFilePath where show = originalFilePath -- TODO: confirm that Show is only used in errors, and use Pretty instead? instance Eq CanonicalFilePath where cfp1 == cfp2 = canonicalFilePath cfp1 `equalFilePath` canonicalFilePath cfp2 instance Ord CanonicalFilePath where cfp1 `compare` cfp2 = canonicalFilePath cfp1 `compare` canonicalFilePath cfp2 instance NFData CanonicalFilePath where rnf (UnsafeCanonicalise a b) = rnf a `seq` rnf b instance Binary CanonicalFilePath where get = liftM2 UnsafeCanonicalise getUTF8String getUTF8String put (UnsafeCanonicalise fp1 fp2) = putUTF8String fp1 >> putUTF8String fp2 canonical :: FilePath -> IO CanonicalFilePath canonical fp = do exists <- liftM2 (||) (doesFileExist fp) (doesDirectoryExist fp) if exists then fmap (UnsafeCanonicalise fp) $ canonicalizePath fp else fmap (UnsafeCanonicalise fp . approximateCanonicalize . (</> fp)) getCurrentDirectory -- Used for non-existant filenames. Consequently, can only be approximately correct! -- Nonetheless, it's important that we make some sort of guess here, or else we get -- ridiculous behaviour like rules for ./Foo.hs not matching requests for ./Bar/../Foo.hs -- simply because Foo.hs doesn't yet exist. approximateCanonicalize :: FilePath -> FilePath approximateCanonicalize = intercalate [head seperators] . go 0 [] . splitOn seperators where go n acc [] = replicate n ".." ++ reverse acc go n acc ("." :xs) = go n acc xs go n [] ("..":xs) = go (n+1) [] xs go n (_:acc) ("..":xs) = go n acc xs go n acc (x :xs) = go n (x:acc) xs #ifdef WINDOWS seperators = "\\/" #else seperators = "/" #endif instance Namespace CanonicalFilePath where type Entry CanonicalFilePath = ModTime -- In standard Shake, we would: -- * Not sanity check anything -- * Recover the ModTime by looking at the file modification time -- * And hence dependent files would be rebuilt but the file would not be, even if the modification time had changed since the last run -- In OpenShake , we would : -- * Cache the ModTime * Sanity check the current ModTime against the current one -- * Thus we detect changes in this file since the last run, so changed files will be rebuilt even if their dependents haven't changed sanityCheck fp old_mtime = getFileModTime (canonicalFilePath fp) >>= \mb_new_mtime -> return $ guard (mb_new_mtime /= Just old_mtime) >> Just "the file has been modified (or deleted) even though its dependents have not changed" defaultRule fp = do -- Not having a rule might still be OK, as long as there is some existing file here: mb_nested_time <- getFileModTime (canonicalFilePath fp) case mb_nested_time of Nothing -> return Nothing NB : it is important that this fake oracle is not reachable if we change from having a rule for a file to not having one , -- but the file still exists. In that case we will try to recheck the old oracle answers against our new oracle and the type -- check will catch the change. Just nested_time -> return $ Just ([fp], return [nested_time]) -- TODO: distinguish between files created b/c of rule match and b/c they already exist in history? Lets us rebuild if the reason changes. data Snapshot CanonicalFilePath = CFPSS { unCFPSS :: M.Map CanonicalFilePath ClockTime } takeSnapshot = do cwd <- getCurrentDirectory >>= canonical (_, fps) <- explore cwd (S.empty, S.empty) "." liftM (CFPSS . M.fromAscList) $ forM (S.toAscList fps) $ \fp -> liftM (fp,) (getAccessTime (canonicalFilePath fp)) where explore parent_fp (seen, seen_files) fp = do fp <- canonical fp if fp `S.member` seen || not (canonicalFilePath parent_fp `isPrefixOf` canonicalFilePath fp) -- Must prevent explore following ".." downwards to the root file system! then return (seen, seen_files) else do let seen' = S.insert fp seen is_file <- doesFileExist (canonicalFilePath fp) if is_file then return (seen', S.insert fp seen_files) else getDirectoryContents (canonicalFilePath fp) >>= (foldM (explore fp) (seen', seen_files) . map (originalFilePath fp </>)) -- TODO: I could lint modification times as well? For example, you should probably not modify a file you need lintSnapshots building_fps = go S.empty S.empty S.empty where go needed accessed accessed_without_need history = case history of [] -> [show fp ++ " was accessed without 'need'ing it first" | fp <- S.toList (accessed_without_need S.\\ S.fromList building_fps)] ++ [show fp ++ " was 'need'ed without ever being accessed" | not (null building_fps), fp <- S.toList needed_without_access] It is OK to need something " uselessly " at the top level , hence the check against building_fps here 2 ) We should not " need " files that we never access needed_without_access = needed S.\\ accessed ((ss, ss', needs):history') -> go -- a) In the successor, it is now OK to access anything we just "need"ed (needed `S.union` S.fromList needs) -- b) In the successor, we need not warn about over-needing those things we have just accessed (accessed `S.union` accesses) -- 1) We should not be allowed to access files that we didn't "need" or are building (accessed_without_need `S.union` (accesses S.\\ needed)) history' where (_ss_deleted, ss_continued, _ss_created) = zipMaps (unCFPSS ss) (unCFPSS ss') accesses = M.keysSet $ M.filter (\(atime1, atime2) -> atime1 < atime2) ss_continued 3 ) We should not create files there are rules for but are not in our " also " list FIXME 4 ) We should not delete files there are rules for FIXME zipMaps :: Ord k => M.Map k v -> M.Map k v -> (M.Map k v, M.Map k (v, v), M.Map k v) zipMaps m1 m2 = (m1 `M.difference` m2, M.intersectionWith (,) m1 m2, m2 `M.difference` m1) type CreatesFiles = [FilePath] type Rule ntop o = FilePath -> Maybe (CreatesFiles, Act ntop ()) (*>) :: (CanonicalFilePath :< ntop, Namespace ntop) => String -> (FilePath -> Act ntop ()) -> Shake ntop () (*>) pattern action = (compiled `match`) ?> action where compiled = compile pattern (*@>) :: (CanonicalFilePath :< ntop, Namespace ntop) => (String, CreatesFiles) -> (FilePath -> Act ntop ()) -> Shake ntop () (*@>) (pattern, alsos) action = (\fp -> guard (compiled `match` fp) >> return alsos) ?@> action where compiled = compile pattern (**>) :: (CanonicalFilePath :< ntop, Namespace ntop) => (FilePath -> Maybe a) -> (FilePath -> a -> Act ntop ()) -> Shake ntop () (**>) p action = addRule $ \fp -> p fp >>= \x -> return ([fp], action fp x) (**@>) :: (CanonicalFilePath :< ntop, Namespace ntop) => (FilePath -> Maybe ([FilePath], a)) -> (FilePath -> a -> Act ntop ()) -> Shake ntop () (**@>) p action = addRule $ \fp -> p fp >>= \(creates, x) -> return (creates, action fp x) (?>) :: (CanonicalFilePath :< ntop, Namespace ntop) => (FilePath -> Bool) -> (FilePath -> Act ntop ()) -> Shake ntop () (?>) p action = addRule $ \fp -> guard (p fp) >> return ([fp], action fp) (?@>) :: (CanonicalFilePath :< ntop, Namespace ntop) => (FilePath -> Maybe CreatesFiles) -> (FilePath -> Act ntop ()) -> Shake ntop () (?@>) p action = addRule $ \fp -> p fp >>= \creates -> return (creates, action fp) addRule :: (CanonicalFilePath :< ntop, Namespace ntop) => Rule ntop o -> Shake ntop () addRule rule = Core.addRule $ liftRule $ \fp -> do cwd <- getCurrentDirectory flip traverse (rule (makeRelative cwd (canonicalFilePath fp))) $ \(creates, act) -> do creates <- mapM (canonical . (cwd </>)) creates return (creates, mapM_ (liftIO . createDirectoryIfMissing True . takeDirectory . canonicalFilePath) creates >> act >> mapM (liftIO . getCleanFileModTime . canonicalFilePath) creates) where getCleanFileModTime :: FilePath -> IO ModTime getCleanFileModTime fp = getFileModTime fp >>= maybe (shakefileError $ "The rule did not create a file that it promised to create " ++ fp) return need :: (CanonicalFilePath :< ntop, Namespace ntop) => [FilePath] -> Act ntop () need fps = liftIO (mapM canonical fps) >>= Composition.need >> return () -- | Attempt to build the specified files once are done collecting rules in the 'Shake' monad. There is no guarantee about the order in which files will be built : in particular , files mentioned in one -- 'want' will not necessarily be built before we begin building files in the following 'want'. want :: (CanonicalFilePath :< ntop, Namespace ntop) => [FilePath] -> Shake ntop () want = act . need
null
https://raw.githubusercontent.com/batterseapower/openshake/4d590c6c4191d5970f2d88f45d9425421d4f64af/Development/Shake/Files.hs
haskell
* File modification times * Normalised file paths * Rules for building files * Requesting that files get built TODO: remove orphan instance TODO: confirm that Show is only used in errors, and use Pretty instead? Used for non-existant filenames. Consequently, can only be approximately correct! Nonetheless, it's important that we make some sort of guess here, or else we get ridiculous behaviour like rules for ./Foo.hs not matching requests for ./Bar/../Foo.hs simply because Foo.hs doesn't yet exist. In standard Shake, we would: * Not sanity check anything * Recover the ModTime by looking at the file modification time * And hence dependent files would be rebuilt but the file would not be, even if the modification time had changed since the last run * Cache the ModTime * Thus we detect changes in this file since the last run, so changed files will be rebuilt even if their dependents haven't changed Not having a rule might still be OK, as long as there is some existing file here: but the file still exists. In that case we will try to recheck the old oracle answers against our new oracle and the type check will catch the change. TODO: distinguish between files created b/c of rule match and b/c they already exist in history? Lets us rebuild if the reason changes. Must prevent explore following ".." downwards to the root file system! TODO: I could lint modification times as well? For example, you should probably not modify a file you need a) In the successor, it is now OK to access anything we just "need"ed b) In the successor, we need not warn about over-needing those things we have just accessed 1) We should not be allowed to access files that we didn't "need" or are building | Attempt to build the specified files once are done collecting rules in the 'Shake' monad. 'want' will not necessarily be built before we begin building files in the following 'want'.
# LANGUAGE TypeFamilies , TypeOperators , GeneralizedNewtypeDeriving , FlexibleContexts , TupleSections , CPP # module Development.Shake.Files ( ModTime, getFileModTime, CanonicalFilePath, canonical, CreatesFiles, Rule, (*>), (*@>), (**>), (**@>), (?>), (?@>), addRule, need, want ) where import Development.Shake.Core hiding (Rule, addRule, need) import qualified Development.Shake.Core as Core import Development.Shake.Core.Binary import Development.Shake.Core.Utilities import Development.Shake.Composition hiding (need) import qualified Development.Shake.Composition as Composition import Data.Binary import Control.DeepSeq import Control.Monad import Control.Monad.IO.Class import Data.Traversable (Traversable(traverse)) import Data.Int (Int64) import Data.List import Data.List.Split (splitOn) import qualified Data.Map as M import qualified Data.Set as S import Data.Time.Clock (UTCTime) import Data.Time.Clock.POSIX (utcTimeToPOSIXSeconds, posixSecondsToUTCTime) import System.Directory import System.Directory.AccessTime import System.FilePath (takeDirectory, equalFilePath, makeRelative, (</>)) import System.FilePath.Glob import System.Time (ClockTime(..)) type ModTime = UTCTime instance Binary UTCTime where get = getModTime put = putModTime getModTime :: Get ModTime getModTime = fmap (posixSecondsToUTCTime . (/ 1000) . fromIntegral) (get :: Get Int64) putModTime :: ModTime -> Put putModTime mtime = put (round (utcTimeToPOSIXSeconds mtime * 1000) :: Int64) getFileModTime :: FilePath -> IO (Maybe ModTime) getFileModTime fp = handleDoesNotExist (return Nothing) (fmap Just (getModificationTime fp)) data CanonicalFilePath = UnsafeCanonicalise { originalFilePath :: FilePath, canonicalFilePath :: FilePath } instance Show CanonicalFilePath where instance Eq CanonicalFilePath where cfp1 == cfp2 = canonicalFilePath cfp1 `equalFilePath` canonicalFilePath cfp2 instance Ord CanonicalFilePath where cfp1 `compare` cfp2 = canonicalFilePath cfp1 `compare` canonicalFilePath cfp2 instance NFData CanonicalFilePath where rnf (UnsafeCanonicalise a b) = rnf a `seq` rnf b instance Binary CanonicalFilePath where get = liftM2 UnsafeCanonicalise getUTF8String getUTF8String put (UnsafeCanonicalise fp1 fp2) = putUTF8String fp1 >> putUTF8String fp2 canonical :: FilePath -> IO CanonicalFilePath canonical fp = do exists <- liftM2 (||) (doesFileExist fp) (doesDirectoryExist fp) if exists then fmap (UnsafeCanonicalise fp) $ canonicalizePath fp else fmap (UnsafeCanonicalise fp . approximateCanonicalize . (</> fp)) getCurrentDirectory approximateCanonicalize :: FilePath -> FilePath approximateCanonicalize = intercalate [head seperators] . go 0 [] . splitOn seperators where go n acc [] = replicate n ".." ++ reverse acc go n acc ("." :xs) = go n acc xs go n [] ("..":xs) = go (n+1) [] xs go n (_:acc) ("..":xs) = go n acc xs go n acc (x :xs) = go n (x:acc) xs #ifdef WINDOWS seperators = "\\/" #else seperators = "/" #endif instance Namespace CanonicalFilePath where type Entry CanonicalFilePath = ModTime In OpenShake , we would : * Sanity check the current ModTime against the current one sanityCheck fp old_mtime = getFileModTime (canonicalFilePath fp) >>= \mb_new_mtime -> return $ guard (mb_new_mtime /= Just old_mtime) >> Just "the file has been modified (or deleted) even though its dependents have not changed" defaultRule fp = do mb_nested_time <- getFileModTime (canonicalFilePath fp) case mb_nested_time of Nothing -> return Nothing NB : it is important that this fake oracle is not reachable if we change from having a rule for a file to not having one , data Snapshot CanonicalFilePath = CFPSS { unCFPSS :: M.Map CanonicalFilePath ClockTime } takeSnapshot = do cwd <- getCurrentDirectory >>= canonical (_, fps) <- explore cwd (S.empty, S.empty) "." liftM (CFPSS . M.fromAscList) $ forM (S.toAscList fps) $ \fp -> liftM (fp,) (getAccessTime (canonicalFilePath fp)) where explore parent_fp (seen, seen_files) fp = do fp <- canonical fp then return (seen, seen_files) else do let seen' = S.insert fp seen is_file <- doesFileExist (canonicalFilePath fp) if is_file then return (seen', S.insert fp seen_files) else getDirectoryContents (canonicalFilePath fp) >>= (foldM (explore fp) (seen', seen_files) . map (originalFilePath fp </>)) lintSnapshots building_fps = go S.empty S.empty S.empty where go needed accessed accessed_without_need history = case history of [] -> [show fp ++ " was accessed without 'need'ing it first" | fp <- S.toList (accessed_without_need S.\\ S.fromList building_fps)] ++ [show fp ++ " was 'need'ed without ever being accessed" | not (null building_fps), fp <- S.toList needed_without_access] It is OK to need something " uselessly " at the top level , hence the check against building_fps here 2 ) We should not " need " files that we never access needed_without_access = needed S.\\ accessed (needed `S.union` S.fromList needs) (accessed `S.union` accesses) (accessed_without_need `S.union` (accesses S.\\ needed)) history' where (_ss_deleted, ss_continued, _ss_created) = zipMaps (unCFPSS ss) (unCFPSS ss') accesses = M.keysSet $ M.filter (\(atime1, atime2) -> atime1 < atime2) ss_continued 3 ) We should not create files there are rules for but are not in our " also " list FIXME 4 ) We should not delete files there are rules for FIXME zipMaps :: Ord k => M.Map k v -> M.Map k v -> (M.Map k v, M.Map k (v, v), M.Map k v) zipMaps m1 m2 = (m1 `M.difference` m2, M.intersectionWith (,) m1 m2, m2 `M.difference` m1) type CreatesFiles = [FilePath] type Rule ntop o = FilePath -> Maybe (CreatesFiles, Act ntop ()) (*>) :: (CanonicalFilePath :< ntop, Namespace ntop) => String -> (FilePath -> Act ntop ()) -> Shake ntop () (*>) pattern action = (compiled `match`) ?> action where compiled = compile pattern (*@>) :: (CanonicalFilePath :< ntop, Namespace ntop) => (String, CreatesFiles) -> (FilePath -> Act ntop ()) -> Shake ntop () (*@>) (pattern, alsos) action = (\fp -> guard (compiled `match` fp) >> return alsos) ?@> action where compiled = compile pattern (**>) :: (CanonicalFilePath :< ntop, Namespace ntop) => (FilePath -> Maybe a) -> (FilePath -> a -> Act ntop ()) -> Shake ntop () (**>) p action = addRule $ \fp -> p fp >>= \x -> return ([fp], action fp x) (**@>) :: (CanonicalFilePath :< ntop, Namespace ntop) => (FilePath -> Maybe ([FilePath], a)) -> (FilePath -> a -> Act ntop ()) -> Shake ntop () (**@>) p action = addRule $ \fp -> p fp >>= \(creates, x) -> return (creates, action fp x) (?>) :: (CanonicalFilePath :< ntop, Namespace ntop) => (FilePath -> Bool) -> (FilePath -> Act ntop ()) -> Shake ntop () (?>) p action = addRule $ \fp -> guard (p fp) >> return ([fp], action fp) (?@>) :: (CanonicalFilePath :< ntop, Namespace ntop) => (FilePath -> Maybe CreatesFiles) -> (FilePath -> Act ntop ()) -> Shake ntop () (?@>) p action = addRule $ \fp -> p fp >>= \creates -> return (creates, action fp) addRule :: (CanonicalFilePath :< ntop, Namespace ntop) => Rule ntop o -> Shake ntop () addRule rule = Core.addRule $ liftRule $ \fp -> do cwd <- getCurrentDirectory flip traverse (rule (makeRelative cwd (canonicalFilePath fp))) $ \(creates, act) -> do creates <- mapM (canonical . (cwd </>)) creates return (creates, mapM_ (liftIO . createDirectoryIfMissing True . takeDirectory . canonicalFilePath) creates >> act >> mapM (liftIO . getCleanFileModTime . canonicalFilePath) creates) where getCleanFileModTime :: FilePath -> IO ModTime getCleanFileModTime fp = getFileModTime fp >>= maybe (shakefileError $ "The rule did not create a file that it promised to create " ++ fp) return need :: (CanonicalFilePath :< ntop, Namespace ntop) => [FilePath] -> Act ntop () need fps = liftIO (mapM canonical fps) >>= Composition.need >> return () There is no guarantee about the order in which files will be built : in particular , files mentioned in one want :: (CanonicalFilePath :< ntop, Namespace ntop) => [FilePath] -> Shake ntop () want = act . need
00bbaaf45a9fc0087d8f2089daa531cf30e686788990b9fd1792007bd9df0cfd
sweet-tooth-clojure/todo-example
core.cljs
(ns sweet-tooth.todo-example.frontend.core (:require [reagent.dom :as rdom] [re-frame.core :as rf] [re-frame.db :as rfdb] [integrant.core :as ig] [meta-merge.core :as mm] [sweet-tooth.frontend.core.flow :as stcf] [sweet-tooth.frontend.load-all-handler-ns] ;; for side effects [sweet-tooth.frontend.core.utils :as stcu] [sweet-tooth.frontend.config :as stconfig] [sweet-tooth.frontend.nav.flow :as stnf] [sweet-tooth.frontend.routes :as stfr] [sweet-tooth.frontend.js-event-handlers.flow :as stjehf] [sweet-tooth.todo-example.frontend.components.app :as app] [sweet-tooth.todo-example.frontend.handlers] ;; for side effects [sweet-tooth.todo-example.frontend.routes :as froutes] [sweet-tooth.todo-example.frontend.subs] ;; for side effects [sweet-tooth.todo-example.cross.endpoint-routes :as eroutes])) (enable-console-print!) treat node lists as seqs ; not related to the rest (extend-protocol ISeqable js/NodeList (-seq [node-list] (array-seq node-list)) js/HTMLCollection (-seq [node-list] (array-seq node-list))) (defn system-config "This is a function instead of a static value so that it will pick up reloaded changes" [] (mm/meta-merge stconfig/default-config {::stfr/frontend-router {:use :reitit :routes froutes/frontend-routes} ::stfr/sync-router {:use :reitit :routes eroutes/routes} ;; Treat handler registration as an external service, ;; interact with it via re-frame effects ::stjehf/handlers {}})) (defn -main [] (rf/dispatch-sync [::stcf/init-system (system-config)]) (rf/dispatch-sync [::stnf/dispatch-current]) (rdom/render [app/app] (stcu/el-by-id "app"))) (defonce initial-load (delay (-main))) @initial-load (defn stop [_] (when-let [system (:sweet-tooth/system @rfdb/app-db)] (ig/halt! system)))
null
https://raw.githubusercontent.com/sweet-tooth-clojure/todo-example/4acb37459bc3d2f534bb00dee07d9e361f414e8f/src/sweet_tooth/todo_example/frontend/core.cljs
clojure
for side effects for side effects for side effects not related to the rest Treat handler registration as an external service, interact with it via re-frame effects
(ns sweet-tooth.todo-example.frontend.core (:require [reagent.dom :as rdom] [re-frame.core :as rf] [re-frame.db :as rfdb] [integrant.core :as ig] [meta-merge.core :as mm] [sweet-tooth.frontend.core.flow :as stcf] [sweet-tooth.frontend.core.utils :as stcu] [sweet-tooth.frontend.config :as stconfig] [sweet-tooth.frontend.nav.flow :as stnf] [sweet-tooth.frontend.routes :as stfr] [sweet-tooth.frontend.js-event-handlers.flow :as stjehf] [sweet-tooth.todo-example.frontend.components.app :as app] [sweet-tooth.todo-example.frontend.routes :as froutes] [sweet-tooth.todo-example.cross.endpoint-routes :as eroutes])) (enable-console-print!) (extend-protocol ISeqable js/NodeList (-seq [node-list] (array-seq node-list)) js/HTMLCollection (-seq [node-list] (array-seq node-list))) (defn system-config "This is a function instead of a static value so that it will pick up reloaded changes" [] (mm/meta-merge stconfig/default-config {::stfr/frontend-router {:use :reitit :routes froutes/frontend-routes} ::stfr/sync-router {:use :reitit :routes eroutes/routes} ::stjehf/handlers {}})) (defn -main [] (rf/dispatch-sync [::stcf/init-system (system-config)]) (rf/dispatch-sync [::stnf/dispatch-current]) (rdom/render [app/app] (stcu/el-by-id "app"))) (defonce initial-load (delay (-main))) @initial-load (defn stop [_] (when-let [system (:sweet-tooth/system @rfdb/app-db)] (ig/halt! system)))
40a62752db76375d2a36cda70a904308b5c4455a8a66165bf61398b455128f00
tweag/linear-base
Ur.hs
# LANGUAGE DataKinds # # LANGUAGE DeriveGeneric # {-# LANGUAGE GADTs #-} # LANGUAGE KindSignatures # {-# LANGUAGE LinearTypes #-} # LANGUAGE StandaloneDeriving # for GHC.Types # LANGUAGE Trustworthy # # LANGUAGE TypeFamilies # # LANGUAGE UndecidableInstances # {-# OPTIONS_HADDOCK hide #-} module Data.Unrestricted.Linear.Internal.Ur ( Ur (..), unur, lift, lift2, ) where import qualified GHC.Generics as GHCGen import GHC.Types (Multiplicity (..)) import Generics.Linear import Prelude.Linear.GenericUtil import qualified Prelude -- | @Ur a@ represents unrestricted values of type @a@ in a linear -- context. The key idea is that because the contructor holds @a@ with a -- regular arrow, a function that uses @Ur a@ linearly can use @a@ -- however it likes. -- -- > someLinear :: Ur a %1-> (a,a) -- > someLinear (Ur a) = (a,a) data Ur a where Ur :: a -> Ur a deriving instance GHCGen.Generic (Ur a) deriving instance GHCGen.Generic1 Ur -- | Get an @a@ out of an @Ur a@. If you call this function on a -- linearly bound @Ur a@, then the @a@ you get out has to be used -- linearly, for example: -- -- > restricted :: Ur a %1-> b -- > restricted x = f (unur x) -- > where -- > -- f __must__ be linear -- > f :: a %1-> b -- > f x = ... unur :: Ur a %1 -> a unur (Ur a) = a -- | Lifts a function on a linear @Ur a@. lift :: (a -> b) -> Ur a %1 -> Ur b lift f (Ur a) = Ur (f a) | Lifts a function to work on two linear @Ur a@. lift2 :: (a -> b -> c) -> Ur a %1 -> Ur b %1 -> Ur c lift2 f (Ur a) (Ur b) = Ur (f a b) instance Prelude.Functor Ur where fmap f (Ur a) = Ur (f a) instance Prelude.Foldable Ur where foldMap f (Ur x) = f x instance Prelude.Traversable Ur where sequenceA (Ur x) = Prelude.fmap Ur x instance Prelude.Applicative Ur where pure = Ur Ur f <*> Ur x = Ur (f x) instance Prelude.Monad Ur where Ur a >>= f = f a -- ------------------- Generic and Generic1 instances instance Generic (Ur a) where type Rep (Ur a) = FixupMetaData (Ur a) ( D1 Any ( C1 Any ( S1 Any (MP1 'Many (Rec0 a)) ) ) ) to rur = to' rur where to' :: Rep (Ur a) p %1 -> Ur a to' (M1 (M1 (M1 (MP1 (K1 a))))) = Ur a from ur = from' ur where from' :: Ur a %1 -> Rep (Ur a) p from' (Ur a) = M1 (M1 (M1 (MP1 (K1 a)))) instance Generic1 Ur where type Rep1 Ur = FixupMetaData1 Ur ( D1 Any ( C1 Any ( S1 Any (MP1 'Many Par1) ) ) ) to1 rur = to1' rur where to1' :: Rep1 Ur a %1 -> Ur a to1' (M1 (M1 (M1 (MP1 (Par1 a))))) = Ur a from1 ur = from1' ur where from1' :: Ur a %1 -> Rep1 Ur a from1' (Ur a) = M1 (M1 (M1 (MP1 (Par1 a)))) type family Any :: Meta
null
https://raw.githubusercontent.com/tweag/linear-base/9d82f67f1415dda385a6349954bf55f9bfa4e62e/src/Data/Unrestricted/Linear/Internal/Ur.hs
haskell
# LANGUAGE GADTs # # LANGUAGE LinearTypes # # OPTIONS_HADDOCK hide # | @Ur a@ represents unrestricted values of type @a@ in a linear context. The key idea is that because the contructor holds @a@ with a regular arrow, a function that uses @Ur a@ linearly can use @a@ however it likes. > someLinear :: Ur a %1-> (a,a) > someLinear (Ur a) = (a,a) | Get an @a@ out of an @Ur a@. If you call this function on a linearly bound @Ur a@, then the @a@ you get out has to be used linearly, for example: > restricted :: Ur a %1-> b > restricted x = f (unur x) > where > -- f __must__ be linear > f :: a %1-> b > f x = ... | Lifts a function on a linear @Ur a@. -------------------
# LANGUAGE DataKinds # # LANGUAGE DeriveGeneric # # LANGUAGE KindSignatures # # LANGUAGE StandaloneDeriving # for GHC.Types # LANGUAGE Trustworthy # # LANGUAGE TypeFamilies # # LANGUAGE UndecidableInstances # module Data.Unrestricted.Linear.Internal.Ur ( Ur (..), unur, lift, lift2, ) where import qualified GHC.Generics as GHCGen import GHC.Types (Multiplicity (..)) import Generics.Linear import Prelude.Linear.GenericUtil import qualified Prelude data Ur a where Ur :: a -> Ur a deriving instance GHCGen.Generic (Ur a) deriving instance GHCGen.Generic1 Ur unur :: Ur a %1 -> a unur (Ur a) = a lift :: (a -> b) -> Ur a %1 -> Ur b lift f (Ur a) = Ur (f a) | Lifts a function to work on two linear @Ur a@. lift2 :: (a -> b -> c) -> Ur a %1 -> Ur b %1 -> Ur c lift2 f (Ur a) (Ur b) = Ur (f a b) instance Prelude.Functor Ur where fmap f (Ur a) = Ur (f a) instance Prelude.Foldable Ur where foldMap f (Ur x) = f x instance Prelude.Traversable Ur where sequenceA (Ur x) = Prelude.fmap Ur x instance Prelude.Applicative Ur where pure = Ur Ur f <*> Ur x = Ur (f x) instance Prelude.Monad Ur where Ur a >>= f = f a Generic and Generic1 instances instance Generic (Ur a) where type Rep (Ur a) = FixupMetaData (Ur a) ( D1 Any ( C1 Any ( S1 Any (MP1 'Many (Rec0 a)) ) ) ) to rur = to' rur where to' :: Rep (Ur a) p %1 -> Ur a to' (M1 (M1 (M1 (MP1 (K1 a))))) = Ur a from ur = from' ur where from' :: Ur a %1 -> Rep (Ur a) p from' (Ur a) = M1 (M1 (M1 (MP1 (K1 a)))) instance Generic1 Ur where type Rep1 Ur = FixupMetaData1 Ur ( D1 Any ( C1 Any ( S1 Any (MP1 'Many Par1) ) ) ) to1 rur = to1' rur where to1' :: Rep1 Ur a %1 -> Ur a to1' (M1 (M1 (M1 (MP1 (Par1 a))))) = Ur a from1 ur = from1' ur where from1' :: Ur a %1 -> Rep1 Ur a from1' (Ur a) = M1 (M1 (M1 (MP1 (Par1 a)))) type family Any :: Meta
ab22cfc3139c218bc47124f1a9daeba9b0ba15b38fcd8c677ec63b299660393e
robert-strandh/SICL
ensure-class.lisp
(cl:in-package #:sicl-clos) ;;; For the specification of this function, see ;;; -MOP/ensure-class.html (defun ensure-class (name &rest arguments &key &allow-other-keys) (unless (and (symbolp name) (not (null name))) (error 'class-name-must-be-non-nil-symbol :name name)) (apply #'ensure-class-using-class (find-class name nil) name arguments))
null
https://raw.githubusercontent.com/robert-strandh/SICL/3de572954c09423a81cbce818fbf83b555f133f9/Code/CLOS/ensure-class.lisp
lisp
For the specification of this function, see -MOP/ensure-class.html
(cl:in-package #:sicl-clos) (defun ensure-class (name &rest arguments &key &allow-other-keys) (unless (and (symbolp name) (not (null name))) (error 'class-name-must-be-non-nil-symbol :name name)) (apply #'ensure-class-using-class (find-class name nil) name arguments))
2f337fc6464d7d77fbb706b3501ab0b85a83509b229542691e55619e8e1e2a41
threatgrid/ctia
schemas.clj
(ns ctia.entity.event.schemas (:require [ctia.schemas.core :refer [TLP]] [schema.core :as s] [schema-tools.core :as st])) (def CreateEventType :record-created) (def UpdateEventType :record-updated) (def DeleteEventType :record-deleted) (def event-types [CreateEventType UpdateEventType DeleteEventType]) (s/defschema Update ;; simplified schema for Swagger UI {:field s/Keyword :action (s/enum "modified" "added" "deleted") :change (st/optional-keys {:before s/Any :after s/Any})} ;; actual schema #_ (s/conditional map? (s/conditional (comp #{"modified"} :action) {:field s/Keyword :action s/Str :change {:before s/Any :after s/Any}} (comp #{"added"} :action) {:field s/Keyword :action s/Str :change {:after s/Any}} (comp #{"deleted"} :action) {:field s/Keyword :action s/Str :change {:before s/Any}}))) (s/defschema Event (st/merge {:owner s/Str :groups [s/Str] :tlp TLP :timestamp s/Inst :entity {s/Any s/Any} :id s/Str :type (s/enum "event") :event_type (apply s/enum event-types)} (st/optional-keys {:fields [Update]}))) (s/defschema PartialEvent (st/optional-keys Event)) (s/defschema PartialEventList [PartialEvent]) (s/defschema EventBucket {:count s/Int :from s/Inst :to s/Inst :owner s/Str :events PartialEventList})
null
https://raw.githubusercontent.com/threatgrid/ctia/43ff86881b099bfd5a86f6a24a7ec0e05e980c04/src/ctia/entity/event/schemas.clj
clojure
simplified schema for Swagger UI actual schema
(ns ctia.entity.event.schemas (:require [ctia.schemas.core :refer [TLP]] [schema.core :as s] [schema-tools.core :as st])) (def CreateEventType :record-created) (def UpdateEventType :record-updated) (def DeleteEventType :record-deleted) (def event-types [CreateEventType UpdateEventType DeleteEventType]) (s/defschema Update {:field s/Keyword :action (s/enum "modified" "added" "deleted") :change (st/optional-keys {:before s/Any :after s/Any})} #_ (s/conditional map? (s/conditional (comp #{"modified"} :action) {:field s/Keyword :action s/Str :change {:before s/Any :after s/Any}} (comp #{"added"} :action) {:field s/Keyword :action s/Str :change {:after s/Any}} (comp #{"deleted"} :action) {:field s/Keyword :action s/Str :change {:before s/Any}}))) (s/defschema Event (st/merge {:owner s/Str :groups [s/Str] :tlp TLP :timestamp s/Inst :entity {s/Any s/Any} :id s/Str :type (s/enum "event") :event_type (apply s/enum event-types)} (st/optional-keys {:fields [Update]}))) (s/defschema PartialEvent (st/optional-keys Event)) (s/defschema PartialEventList [PartialEvent]) (s/defschema EventBucket {:count s/Int :from s/Inst :to s/Inst :owner s/Str :events PartialEventList})
f08269a771c53b721cf08607ca45c3944c954c8fc2b66c9153b8e6b6f77f7864
janestreet/krb
currently_running_user.ml
open! Core open Async let passwd () = Unix.Passwd.getbyuid_exn (Unix.geteuid ()) let name () = let%bind passwd = passwd () in return passwd.name ;; module Blocking = struct let passwd () = Core_unix.Passwd.getbyuid_exn (Core_unix.geteuid ()) let name () = (passwd ()).name end
null
https://raw.githubusercontent.com/janestreet/krb/76ff1f5372c7610d8b14ea1a143a79f74d6e8c26/src/currently_running_user.ml
ocaml
open! Core open Async let passwd () = Unix.Passwd.getbyuid_exn (Unix.geteuid ()) let name () = let%bind passwd = passwd () in return passwd.name ;; module Blocking = struct let passwd () = Core_unix.Passwd.getbyuid_exn (Core_unix.geteuid ()) let name () = (passwd ()).name end
7db8555f1c5cd442e445bd6082b8c066f2bf828fba4ba2c7969a31a8df8776ac
BnMcGn/ps-gadgets
ps-gadgets.lisp
;;;; ps-gadgets.lisp (in-package #:ps-gadgets) ;;; "ps-gadgets" goes here. Hacks and glory await! (defparameter *js-second* 1000) (defparameter *js-minute* (* 60 *js-second*)) (defparameter *js-hour* (* 60 *js-minute*)) (defparameter *js-day* (* 24 *js-hour*)) (defparameter *js-week* (* 7 *js-day*)) (defparameter *js-month* (* 30 *js-day*)) ;Ok, things start to get weird. (defparameter *js-year* (* 365 *js-day*)) (def-ps-package ps-lisp-library :code (ps* *ps-lisp-library*) :export '(#:mapcar #:map-into #:map #:member #:set-difference #:reduce #:nconc)) (def-ps-package ps-gadgets :ps-requirements '(ps-lisp-library) :code (ps (setf *whitespace-characters* (lisp (list* 'list gadgets:*whitespace-characters*))) (defun say (thing) (chain console (log thing)) thing) (defun grab (thing) (if (@ window grabbed) (chain window grabbed (push thing)) (setf (@ window grabbed) (list thing))) thing) ;;FIXME: Should check that isn't some other compound type. Else check if is ;; known atom type. (defun atom (itm) (not (arrayp itm))) (defun arrayp (itm) (chain -array (is-array itm))) (defun numberp (itm) (equal "number" (typeof itm))) (defun integerp (itm) (chain -number (is-integer itm))) (defun string-object-p (itm) (and (equal (typeof itm) "object") (instanceof itm -string))) (defun string-object-to-literal (obj) (chain obj (to-string))) (defun string-literal-p (itm) (equal "string" (typeof itm))) (defun stringishp (itm) (or (string-literal-p itm) (string-object-p itm))) (defun ensure-string-literal (itm) (cond ((stringp itm) itm) ((string-object-p itm) (string-object-to-literal itm)) (t (throw "Not a string type")))) (defun ensure-array (arr) (cond ((or (equal (typeof arr) "undefined") (null arr)) ([])) ((chain arr (has-own-property 'length)) arr) (t ([] arr)))) (defun js-string-equal (a b) (cond ((eq a b) t) ((or (not (stringishp a)) (not (stringishp b))) nil) ((equal (ensure-string-literal a) (ensure-string-literal b)) t))) (defun has-property (obj key) (chain obj (has-own-property key))) ;;FIXME: maybe should use version from lodash (defun array-equal (a b) (cond ((eq a b) t) ((or (not a) (not b)) false) ((not (eq (@ a length) (@ b length))) false) (t (progn (dotimes (i (@ a length)) (when (not (equal (getprop a i) (getprop b i))) (return false))) t)))) (defun get/d (obj key value) (if (eq (typeof (getprop obj key)) "undefined") value (getprop obj key))) (defun array-cdr (arr) (chain (ensure-array arr) (slice 1))) (defun unique (arr &key (test (lambda (a b) (eql a b)))) (chain arr (filter (lambda (val ind self) (eq (chain self (find-index (lambda (itm) (test val itm)))) ind))))) (defun ensure-string (str) (if (equal (typeof str) "string") str "")) (defun copy-string (str) (chain (+ " " str) (slice 1))) (defun capitalize-first (str) (chain str (replace (regex "^[a-z]") (lambda (first-char) (chain first-char (to-upper-case)))))) (defun newline () "Because parenscript doesn't allow \n" (chain -string (from-char-code 10))) (defun remove-if (test arr) (collecting (dolist (itm (ensure-array arr)) (unless (funcall test itm) (collect itm))))) (defun remove-if-not (test arr) (collecting (dolist (itm (ensure-array arr)) (when (funcall test itm) (collect itm))))) (defun some (pred first-seq &rest more-seqs) (loop for i from 0 for itm in first-seq for res = (apply pred itm (mapcar (lambda (x) (elt x i)) more-seqs)) until res finally (return res))) (defun range (start &optional stop (step 1)) (let ((start (if stop start 0)) (stop (if stop stop start))) (let ((stop-p (if (> step 0) (lambda (x) (< x stop)) (lambda (x) (> x stop))))) (if (or (and (> step 0) (>= start stop) (and (< step 0) (<= start stop)))) ([]) (collecting (loop while (funcall stop-p start) do (collect start) do (incf start step))))))) (defun position-difference (element1 element2) (let ((pos1 (chain element1 (get-bounding-client-rect))) (pos2 (chain element2 (get-bounding-client-rect)))) (create top (- (@ pos1 top) (@ pos2 top)) left (- (@ pos1 left) (@ pos2 left)) bottom (- (@ pos1 bottom) (@ pos2 bottom)) right (- (@ pos1 right) (@ pos2 right))))) (defun mapleaves (fn tree &key test) "Map a one-argument function FN over each leaf node of the TREE in depth-first order, returning a new tree with the same structure." (labels ((rec (node) (if (and (atom node) (or (not test) (funcall test node))) (funcall fn node) (mapcar #'rec node)))) (when tree (rec tree)))) (defun try-awhile (predicate &key (sleep 1) (wait 1000) on-success on-fail) "Will continue to call predicate until either it returns success or a given amount of time elapses. Duration can be set with the :wait keyword. It defaults to 1000 milliseconds. Try-awhile will sleep between predicate calls unless the :sleep keyword is set to nil. Default sleep is 100 milliseconds. Try-awhile will return the predicate value on success or nil on failure. If a function is supplied to the :on-success argument, it will be executed if the predicate succeeds and its result will be returned instead of the predicate result. The :on-fail keyword may be used to supply a function that will be run if the time elapses without a predicate success. It's result will be returned instead of the default nil." ;;FIXME: Needs to return? a promise (let ((start-time (chain -date (now)))) (defun func () (let ((result (funcall predicate))) (if result (if on-success (funcall on-success) result) (if (< (+ start-time wait) (chain -date (now))) (if on-fail (funcall on-fail) nil) (set-timeout func sleep))))) (func))) (defun random-element (arr) (getprop arr (chain -math (floor (* (chain -math (random)) (@ arr length)))))) (defun flatten (tree) (collecting (labels ((proc (itm) (if (atom itm) (collect itm) (dolist (i itm) (proc i))))) (proc tree)))) (defun ago (date-obj) (let ((diff (- (chain -date (now)) date-obj))) (create get-years (lambda () (parse-int (/ diff (lisp *js-year*)))) get-months (lambda () (parse-int (/ diff (lisp *js-month*)))) get-weeks (lambda () (parse-int (/ diff (lisp *js-week*)))) get-days (lambda () (parse-int (/ diff (lisp *js-day*)))) get-hours (lambda () (parse-int (/ diff (lisp *js-hour*)))) get-minutes (lambda () (parse-int (/ diff (lisp *js-minute*)))) get-seconds (lambda () (parse-int (/ diff (lisp *js-second*))))))) (defun url-domain (url) ;;FIXME: Maybe we should error out if we get a bad URL (let* ((part1 (or (chain url (split "//") 1) "")) (part2 (chain part1 (split "/") 0))) (if (equal "www." (chain part2 (substring 0 4))) (chain part2 (slice 4)) part2))) (defun url-parameters-location (url) (let ((start (chain url (index-of "?"))) (end (chain url (index-of "#")))) (when (eq -1 start) (setf start undefined)) (when (eq -1 end) (setf end undefined)) (when (and end start (> start end)) (setf start undefined)) (when start (incf start)) (list start end))) (defun url-parameters (url) (let* ((res (create)) (loc (url-parameters-location url)) (parstring (when (or (@ loc 0) (@ loc 1)) (chain url (slice (@ loc 0) (@ loc 1)))))) (when parstring (dolist (par (chain parstring (split "&"))) (let ((pair (chain par (split "=")))) (setf (getprop res (decode-u-r-i-component (@ pair 0))) (decode-u-r-i-component (@ pair 1)))))) res)) (defun url-parameter-string-from-object (obj) (chain (collecting (do-keyvalue (k v obj) (collect (+ (encode-u-r-i-component k) "=" (encode-u-r-i-component v))))) (join "&"))) (defun replace-url-parameters (url new-param-string) (if (< 0 (@ new-param-string length)) (let* ((loc (url-parameters-location url)) (tail (if (@ loc 1) (chain url (slice (@ loc 1))) "")) (head (chain url (slice undefined (if (@ loc 0) (1- (@ loc 0)) (@ loc 1)))))) (+ head (if (@ loc 0) "" "?") new-param-string tail)) url)) (defun set-url-parameters (url obj) "Return a copy of url with the keys in obj set as parameters. Overwrite parameters in url when names are shared, but retain other parameters from url." (let ((existing (url-parameters url))) (do-keyvalue (k v obj) (setf (getprop existing k) v)) (replace-url-parameters url (url-parameter-string-from-object existing)))) (defun update-url-parameter (url param value) (let* ((parts (chain url (split "#"))) (base (getprop parts 0)) (anchor (getprop parts 1)) (parts (chain base (split "?"))) (base (getprop parts 0)) (params (if (getprop parts 1) (chain (getprop parts 1) (split "&")) (list))) (parstring (+ param "=" value)) (found nil) (params (mapcar (lambda (par) (let ((kv (chain par (split "=")))) (if (equal (getprop kv 0) param) (progn (setf found t) parstring) par))) params)) (params (if found params (chain params (concat (list parstring)))))) (+ base "?" (chain params (join "&")) (if anchor (+ "#" anchor) "")))) (defun http-url-p (item) (let ((url nil)) (try (setf url (new (-u-r-l item))) (:catch (_) (return-from http-url-p nil))) (or (eq (@ url protocol) "http:") (eq (@ url protocol) "https:")))) (defun not-empty (itm) (and itm (< 0 (if (eq undefined (@ itm length)) (chain -object (keys itm) length) (@ itm length))))) (defun first-match (predicate input-list) (let ((res nil) (sig nil)) (dolist (x input-list) (when (funcall predicate x) (setf res x) (setf sig t) (break))) (values res sig))) (defun array-equal (arr1 arr2) (when (eq (@ arr1 length) (@ arr2 length)) (dotimes (i (@ arr1 length)) (unless (eq (getprop arr1 i) (getprop arr2 i)) (return-from array-equal nil))) t)) (defun boolify (val) ;;FIXME: Should be using case insensitive test (when val (if (member val '(0 "false" "False" "NIL" "nil" "null" "Null" "No" "no")) nil t))) (defun identity (x) x) (defun funcall (func &rest params) (apply func params)) (defun relative-to-range (start end num) "Returns a value indicating where num is positioned relative to start and end. If num lies between start and end, the return value will be between 0.0 and 1.0." (/ (- num start) (- end start))) (defun as-in-range (start end num) "Complement of relative-of-range function. Treats num as if it were a fraction of the range specified by start and end. Returns the absolute number that results." (+ start (* num (- end start)))) (let ((counter 0)) (defun unique-id () (incf counter))) (defun list-last (list-obj) (when (and (chain list-obj (has-own-property 'length)) (< 0 (@ list-obj length))) (@ list-obj (- (@ list-obj length) 1)))) (defun create-from-list (keys-and-values) (let ((res (create))) (do-window ((k v) keys-and-values :step 2) (setf (getprop res k) v)) res)) ;;Based on code from (defun json-promise (url) (new (-promise (lambda (resolve reject) (let ((req (new (-x-m-l-http-request)))) (chain req (open "GET" url)) (setf (@ req onload) (lambda () (if (eql 200 (@ req status)) (funcall resolve (chain -j-s-o-n (parse (@ req response)))) (funcall reject (-error (@ req status-text)))))) (setf (@ req onerror) (lambda () (funcall reject (-error "Network Error")))) (chain req (send))))))) ;; Set operations (defun is-superset (set subset) (paren6:for-of (itm subset) (unless (chain set (has itm)) (return nil))) t) (defun union (x y) (let ((res (new (-set x)))) (paren6:for-of (itm y) (chain res (add itm))) res)) (defun intersection (x y) (let ((res (new (-set)))) (paren6:for-of (itm y) (when (chain x (has itm)) (chain res (add itm)))) res)) (defun difference (x y) (let ((res (new (-set x)))) (paren6:for-of (itm y) (chain res (delete itm))) res)) (defun set-xor (x y) (let ((res (new (-set x)))) (paren6:for-of (itm y) (if (chain res (has itm)) (chain res (delete itm)) (chain res (add itm)))) res)) ;;Tools for non-destructive editing. Useful for redux. (defun shallow-copy (obj) (let ((res (create))) (do-keyvalue (k v obj) (setf (aref res k) v)) res)) (defun copy-merge-objects (base addition) "Makes a copy of base, overwrites key values in base with those found in addition. Silently ignores extra keys in addition." (let ((res (create))) (do-keyvalue (k v base) (setf (getprop res k) (if (chain addition (has-own-property k)) (getprop addition k) (getprop base k)))) res)) (defun copy-merge-all (&rest objects) (let ((res (create))) (dolist (ob objects) (when ob (do-keyvalue (k v ob) (setf (getprop res k) v)))) res)) (defun copy-remove-keys (obj keys) (let ((res (shallow-copy obj))) (dolist (k keys) (delete (getprop res k))) res)) (defun safe-set-copy (arr &rest key/values) "Creates copy of arr, setting keys to values in the copy only if they exist in the original." (let ((res (create))) (do-window ((k v) key/values :step 2) (unless (chain arr (has-own-property k)) (throw "Tried to set non-existent key in safe-set-copy")) (setf (getprop res k) v)) (copy-merge-objects arr res))) (defun set-copy (arr &rest key/values) "Creates copy of arr, setting key to value in the copy regardless of whether it exists in the original." (let ((res (shallow-copy arr))) (do-window ((k v) key/values :step 2) (setf (getprop res k) v)) res)) (defun copy-updates (orig changes) "Creates a copy of changes that only contains things that are different from orig." (let ((res (create))) (do-keyvalue (k v changes) (if (chain orig (has-own-property k)) (unless (equal (getprop orig k) v) (setf (getprop res k) v)) (setf (getprop res k) v))) res)) (defun incf-copy (arr key &optional (value 1)) (safe-set-copy arr key (+ (getprop arr key) value))) (defun decf-copy (arr key &optional (value 1)) (safe-set-copy arr key (- (getprop arr key) value))) (defun inc-or-set-copy (arr key &optional (value 1)) (if (chain arr (has-own-property key)) (incf-copy arr key value) (set-copy arr key value))) (defun get-path (arr path) (if (> 1 (chain path (length))) (get-path (getprop arr (car path)) (cdr path)) (getprop arr (car path)))) (defun deep-set-copy (arr path value) (case (@ path length) (0 (throw "Shouldn't have zero length path")) (1 (safe-set-copy arr (elt path 0) value)) (otherwise (safe-set-copy arr (elt path 0) (deep-set-copy (getprop arr (elt path 0)) (chain path (slice 1)) value))))) (defun push-copy (alist val) (collecting (collect val) (dolist (itm (ensure-array alist)) (collect itm)))) (defvar *tree-leaf-p* nil "Is the node being processed a leaf or a branch?") (defvar *tree-stack* nil "Pointers to the parentage of the current node. Includes current node.") (defvar *tree-index-stack* nil "Indices that lead to the address of the current node.") (defvar *tree-process-branches* t) (defvar *tree-process-leaves* t) (defvar *tree-breadth-first* nil) (defvar *tree-leaf-test* nil) (defvar *tree-branch-filter* nil) (defun %proc-branch (branch exec) (collecting (let ((stor nil)) (dotimes (i (@ branch length)) (let* ((*tree-stack* (push-copy *tree-stack* (getprop branch i))) (*tree-index-stack* (push-copy *tree-index-stack* i)) (item (getprop branch i)) (ts *tree-stack*) (tis *tree-index-stack*)) (if (funcall *tree-leaf-test* item) (when *tree-process-leaves* (collect (let ((*tree-leaf-p* t)) (lambda () (let ((*tree-stack* ts) (*tree-index-stack* tis)) (funcall exec item) nil))))) (progn (when *tree-process-branches* (collect (let ((*tree-leaf-p* nil)) (lambda () (let ((*tree-stack* ts) (*tree-index-stack* tis)) (funcall exec item) nil))))) FIXME : prev will want to be able to effect how and if of ;; execution of following. (let ((sub (lambda () (let ((*tree-stack* ts) (*tree-index-stack* tis)) (let ((res (%proc-branch (funcall (or *tree-branch-filter* #'identity) item) exec))) (mapcar #'funcall (chain res (slice 0 -1))) (getprop res -1)))))) (if *tree-breadth-first* (chain stor (push sub)) ;; Store to execute at end (collect sub))))))) ;; Execute as found (collect stor)))) FIXME : Does n't support switching between depth and breadth first mid - tree . (defun %handle-proc-branch-tail (tail) (cl-utilities:collecting (dolist (item tail) (dolist (res (funcall item)) (when (functionp res) (cl-utilities:collect res)))))) (defun call-with-tree (func tree &key (order :depth) (proc-branch t) proc-leaf branch-filter leaf-test) (unless (member order '(:depth :breadth)) (error "Order must be :depth or :breadth")) (let ((*tree-process-branches* proc-branch) (*tree-process-leaves* proc-leaf) (*tree-breadth-first* (eq order :breadth)) (*tree-leaf-test* (or leaf-test #'atom)) (*tree-branch-filter* branch-filter)) (let ((res (%proc-branch (funcall (or *tree-branch-filter* #'identity) tree) func))) (mapcar #'funcall (chain res (slice 0 -1))) (loop with items = (getprop res -1) while items do (setf items (%handle-proc-branch-tail items)))))) )); End ps-gadgets (defun alist->ps-object-code (alist &key (wrap t)) (let ((res (cl-utilities:collecting (dolist (item alist) (cl-utilities:collect (car item)) (cl-utilities:collect (cdr item)))))) (if wrap (cons 'ps:create res) res)))
null
https://raw.githubusercontent.com/BnMcGn/ps-gadgets/e8a769931728510dc3639069c7d6053433b22d80/ps-gadgets.lisp
lisp
ps-gadgets.lisp "ps-gadgets" goes here. Hacks and glory await! Ok, things start to get weird. FIXME: Should check that isn't some other compound type. Else check if is known atom type. FIXME: maybe should use version from lodash FIXME: Needs to return? a promise FIXME: Maybe we should error out if we get a bad URL FIXME: Should be using case insensitive test Based on code from Set operations Tools for non-destructive editing. Useful for redux. execution of following. Store to execute at end Execute as found End ps-gadgets
(in-package #:ps-gadgets) (defparameter *js-second* 1000) (defparameter *js-minute* (* 60 *js-second*)) (defparameter *js-hour* (* 60 *js-minute*)) (defparameter *js-day* (* 24 *js-hour*)) (defparameter *js-week* (* 7 *js-day*)) (defparameter *js-year* (* 365 *js-day*)) (def-ps-package ps-lisp-library :code (ps* *ps-lisp-library*) :export '(#:mapcar #:map-into #:map #:member #:set-difference #:reduce #:nconc)) (def-ps-package ps-gadgets :ps-requirements '(ps-lisp-library) :code (ps (setf *whitespace-characters* (lisp (list* 'list gadgets:*whitespace-characters*))) (defun say (thing) (chain console (log thing)) thing) (defun grab (thing) (if (@ window grabbed) (chain window grabbed (push thing)) (setf (@ window grabbed) (list thing))) thing) (defun atom (itm) (not (arrayp itm))) (defun arrayp (itm) (chain -array (is-array itm))) (defun numberp (itm) (equal "number" (typeof itm))) (defun integerp (itm) (chain -number (is-integer itm))) (defun string-object-p (itm) (and (equal (typeof itm) "object") (instanceof itm -string))) (defun string-object-to-literal (obj) (chain obj (to-string))) (defun string-literal-p (itm) (equal "string" (typeof itm))) (defun stringishp (itm) (or (string-literal-p itm) (string-object-p itm))) (defun ensure-string-literal (itm) (cond ((stringp itm) itm) ((string-object-p itm) (string-object-to-literal itm)) (t (throw "Not a string type")))) (defun ensure-array (arr) (cond ((or (equal (typeof arr) "undefined") (null arr)) ([])) ((chain arr (has-own-property 'length)) arr) (t ([] arr)))) (defun js-string-equal (a b) (cond ((eq a b) t) ((or (not (stringishp a)) (not (stringishp b))) nil) ((equal (ensure-string-literal a) (ensure-string-literal b)) t))) (defun has-property (obj key) (chain obj (has-own-property key))) (defun array-equal (a b) (cond ((eq a b) t) ((or (not a) (not b)) false) ((not (eq (@ a length) (@ b length))) false) (t (progn (dotimes (i (@ a length)) (when (not (equal (getprop a i) (getprop b i))) (return false))) t)))) (defun get/d (obj key value) (if (eq (typeof (getprop obj key)) "undefined") value (getprop obj key))) (defun array-cdr (arr) (chain (ensure-array arr) (slice 1))) (defun unique (arr &key (test (lambda (a b) (eql a b)))) (chain arr (filter (lambda (val ind self) (eq (chain self (find-index (lambda (itm) (test val itm)))) ind))))) (defun ensure-string (str) (if (equal (typeof str) "string") str "")) (defun copy-string (str) (chain (+ " " str) (slice 1))) (defun capitalize-first (str) (chain str (replace (regex "^[a-z]") (lambda (first-char) (chain first-char (to-upper-case)))))) (defun newline () "Because parenscript doesn't allow \n" (chain -string (from-char-code 10))) (defun remove-if (test arr) (collecting (dolist (itm (ensure-array arr)) (unless (funcall test itm) (collect itm))))) (defun remove-if-not (test arr) (collecting (dolist (itm (ensure-array arr)) (when (funcall test itm) (collect itm))))) (defun some (pred first-seq &rest more-seqs) (loop for i from 0 for itm in first-seq for res = (apply pred itm (mapcar (lambda (x) (elt x i)) more-seqs)) until res finally (return res))) (defun range (start &optional stop (step 1)) (let ((start (if stop start 0)) (stop (if stop stop start))) (let ((stop-p (if (> step 0) (lambda (x) (< x stop)) (lambda (x) (> x stop))))) (if (or (and (> step 0) (>= start stop) (and (< step 0) (<= start stop)))) ([]) (collecting (loop while (funcall stop-p start) do (collect start) do (incf start step))))))) (defun position-difference (element1 element2) (let ((pos1 (chain element1 (get-bounding-client-rect))) (pos2 (chain element2 (get-bounding-client-rect)))) (create top (- (@ pos1 top) (@ pos2 top)) left (- (@ pos1 left) (@ pos2 left)) bottom (- (@ pos1 bottom) (@ pos2 bottom)) right (- (@ pos1 right) (@ pos2 right))))) (defun mapleaves (fn tree &key test) "Map a one-argument function FN over each leaf node of the TREE in depth-first order, returning a new tree with the same structure." (labels ((rec (node) (if (and (atom node) (or (not test) (funcall test node))) (funcall fn node) (mapcar #'rec node)))) (when tree (rec tree)))) (defun try-awhile (predicate &key (sleep 1) (wait 1000) on-success on-fail) "Will continue to call predicate until either it returns success or a given amount of time elapses. Duration can be set with the :wait keyword. It defaults to 1000 milliseconds. Try-awhile will sleep between predicate calls unless the :sleep keyword is set to nil. Default sleep is 100 milliseconds. Try-awhile will return the predicate value on success or nil on failure. If a function is supplied to the :on-success argument, it will be executed if the predicate succeeds and its result will be returned instead of the predicate result. The :on-fail keyword may be used to supply a function that will be run if the time elapses without a predicate success. It's result will be returned instead of the default nil." (let ((start-time (chain -date (now)))) (defun func () (let ((result (funcall predicate))) (if result (if on-success (funcall on-success) result) (if (< (+ start-time wait) (chain -date (now))) (if on-fail (funcall on-fail) nil) (set-timeout func sleep))))) (func))) (defun random-element (arr) (getprop arr (chain -math (floor (* (chain -math (random)) (@ arr length)))))) (defun flatten (tree) (collecting (labels ((proc (itm) (if (atom itm) (collect itm) (dolist (i itm) (proc i))))) (proc tree)))) (defun ago (date-obj) (let ((diff (- (chain -date (now)) date-obj))) (create get-years (lambda () (parse-int (/ diff (lisp *js-year*)))) get-months (lambda () (parse-int (/ diff (lisp *js-month*)))) get-weeks (lambda () (parse-int (/ diff (lisp *js-week*)))) get-days (lambda () (parse-int (/ diff (lisp *js-day*)))) get-hours (lambda () (parse-int (/ diff (lisp *js-hour*)))) get-minutes (lambda () (parse-int (/ diff (lisp *js-minute*)))) get-seconds (lambda () (parse-int (/ diff (lisp *js-second*))))))) (defun url-domain (url) (let* ((part1 (or (chain url (split "//") 1) "")) (part2 (chain part1 (split "/") 0))) (if (equal "www." (chain part2 (substring 0 4))) (chain part2 (slice 4)) part2))) (defun url-parameters-location (url) (let ((start (chain url (index-of "?"))) (end (chain url (index-of "#")))) (when (eq -1 start) (setf start undefined)) (when (eq -1 end) (setf end undefined)) (when (and end start (> start end)) (setf start undefined)) (when start (incf start)) (list start end))) (defun url-parameters (url) (let* ((res (create)) (loc (url-parameters-location url)) (parstring (when (or (@ loc 0) (@ loc 1)) (chain url (slice (@ loc 0) (@ loc 1)))))) (when parstring (dolist (par (chain parstring (split "&"))) (let ((pair (chain par (split "=")))) (setf (getprop res (decode-u-r-i-component (@ pair 0))) (decode-u-r-i-component (@ pair 1)))))) res)) (defun url-parameter-string-from-object (obj) (chain (collecting (do-keyvalue (k v obj) (collect (+ (encode-u-r-i-component k) "=" (encode-u-r-i-component v))))) (join "&"))) (defun replace-url-parameters (url new-param-string) (if (< 0 (@ new-param-string length)) (let* ((loc (url-parameters-location url)) (tail (if (@ loc 1) (chain url (slice (@ loc 1))) "")) (head (chain url (slice undefined (if (@ loc 0) (1- (@ loc 0)) (@ loc 1)))))) (+ head (if (@ loc 0) "" "?") new-param-string tail)) url)) (defun set-url-parameters (url obj) "Return a copy of url with the keys in obj set as parameters. Overwrite parameters in url when names are shared, but retain other parameters from url." (let ((existing (url-parameters url))) (do-keyvalue (k v obj) (setf (getprop existing k) v)) (replace-url-parameters url (url-parameter-string-from-object existing)))) (defun update-url-parameter (url param value) (let* ((parts (chain url (split "#"))) (base (getprop parts 0)) (anchor (getprop parts 1)) (parts (chain base (split "?"))) (base (getprop parts 0)) (params (if (getprop parts 1) (chain (getprop parts 1) (split "&")) (list))) (parstring (+ param "=" value)) (found nil) (params (mapcar (lambda (par) (let ((kv (chain par (split "=")))) (if (equal (getprop kv 0) param) (progn (setf found t) parstring) par))) params)) (params (if found params (chain params (concat (list parstring)))))) (+ base "?" (chain params (join "&")) (if anchor (+ "#" anchor) "")))) (defun http-url-p (item) (let ((url nil)) (try (setf url (new (-u-r-l item))) (:catch (_) (return-from http-url-p nil))) (or (eq (@ url protocol) "http:") (eq (@ url protocol) "https:")))) (defun not-empty (itm) (and itm (< 0 (if (eq undefined (@ itm length)) (chain -object (keys itm) length) (@ itm length))))) (defun first-match (predicate input-list) (let ((res nil) (sig nil)) (dolist (x input-list) (when (funcall predicate x) (setf res x) (setf sig t) (break))) (values res sig))) (defun array-equal (arr1 arr2) (when (eq (@ arr1 length) (@ arr2 length)) (dotimes (i (@ arr1 length)) (unless (eq (getprop arr1 i) (getprop arr2 i)) (return-from array-equal nil))) t)) (defun boolify (val) (when val (if (member val '(0 "false" "False" "NIL" "nil" "null" "Null" "No" "no")) nil t))) (defun identity (x) x) (defun funcall (func &rest params) (apply func params)) (defun relative-to-range (start end num) "Returns a value indicating where num is positioned relative to start and end. If num lies between start and end, the return value will be between 0.0 and 1.0." (/ (- num start) (- end start))) (defun as-in-range (start end num) "Complement of relative-of-range function. Treats num as if it were a fraction of the range specified by start and end. Returns the absolute number that results." (+ start (* num (- end start)))) (let ((counter 0)) (defun unique-id () (incf counter))) (defun list-last (list-obj) (when (and (chain list-obj (has-own-property 'length)) (< 0 (@ list-obj length))) (@ list-obj (- (@ list-obj length) 1)))) (defun create-from-list (keys-and-values) (let ((res (create))) (do-window ((k v) keys-and-values :step 2) (setf (getprop res k) v)) res)) (defun json-promise (url) (new (-promise (lambda (resolve reject) (let ((req (new (-x-m-l-http-request)))) (chain req (open "GET" url)) (setf (@ req onload) (lambda () (if (eql 200 (@ req status)) (funcall resolve (chain -j-s-o-n (parse (@ req response)))) (funcall reject (-error (@ req status-text)))))) (setf (@ req onerror) (lambda () (funcall reject (-error "Network Error")))) (chain req (send))))))) (defun is-superset (set subset) (paren6:for-of (itm subset) (unless (chain set (has itm)) (return nil))) t) (defun union (x y) (let ((res (new (-set x)))) (paren6:for-of (itm y) (chain res (add itm))) res)) (defun intersection (x y) (let ((res (new (-set)))) (paren6:for-of (itm y) (when (chain x (has itm)) (chain res (add itm)))) res)) (defun difference (x y) (let ((res (new (-set x)))) (paren6:for-of (itm y) (chain res (delete itm))) res)) (defun set-xor (x y) (let ((res (new (-set x)))) (paren6:for-of (itm y) (if (chain res (has itm)) (chain res (delete itm)) (chain res (add itm)))) res)) (defun shallow-copy (obj) (let ((res (create))) (do-keyvalue (k v obj) (setf (aref res k) v)) res)) (defun copy-merge-objects (base addition) "Makes a copy of base, overwrites key values in base with those found in addition. Silently ignores extra keys in addition." (let ((res (create))) (do-keyvalue (k v base) (setf (getprop res k) (if (chain addition (has-own-property k)) (getprop addition k) (getprop base k)))) res)) (defun copy-merge-all (&rest objects) (let ((res (create))) (dolist (ob objects) (when ob (do-keyvalue (k v ob) (setf (getprop res k) v)))) res)) (defun copy-remove-keys (obj keys) (let ((res (shallow-copy obj))) (dolist (k keys) (delete (getprop res k))) res)) (defun safe-set-copy (arr &rest key/values) "Creates copy of arr, setting keys to values in the copy only if they exist in the original." (let ((res (create))) (do-window ((k v) key/values :step 2) (unless (chain arr (has-own-property k)) (throw "Tried to set non-existent key in safe-set-copy")) (setf (getprop res k) v)) (copy-merge-objects arr res))) (defun set-copy (arr &rest key/values) "Creates copy of arr, setting key to value in the copy regardless of whether it exists in the original." (let ((res (shallow-copy arr))) (do-window ((k v) key/values :step 2) (setf (getprop res k) v)) res)) (defun copy-updates (orig changes) "Creates a copy of changes that only contains things that are different from orig." (let ((res (create))) (do-keyvalue (k v changes) (if (chain orig (has-own-property k)) (unless (equal (getprop orig k) v) (setf (getprop res k) v)) (setf (getprop res k) v))) res)) (defun incf-copy (arr key &optional (value 1)) (safe-set-copy arr key (+ (getprop arr key) value))) (defun decf-copy (arr key &optional (value 1)) (safe-set-copy arr key (- (getprop arr key) value))) (defun inc-or-set-copy (arr key &optional (value 1)) (if (chain arr (has-own-property key)) (incf-copy arr key value) (set-copy arr key value))) (defun get-path (arr path) (if (> 1 (chain path (length))) (get-path (getprop arr (car path)) (cdr path)) (getprop arr (car path)))) (defun deep-set-copy (arr path value) (case (@ path length) (0 (throw "Shouldn't have zero length path")) (1 (safe-set-copy arr (elt path 0) value)) (otherwise (safe-set-copy arr (elt path 0) (deep-set-copy (getprop arr (elt path 0)) (chain path (slice 1)) value))))) (defun push-copy (alist val) (collecting (collect val) (dolist (itm (ensure-array alist)) (collect itm)))) (defvar *tree-leaf-p* nil "Is the node being processed a leaf or a branch?") (defvar *tree-stack* nil "Pointers to the parentage of the current node. Includes current node.") (defvar *tree-index-stack* nil "Indices that lead to the address of the current node.") (defvar *tree-process-branches* t) (defvar *tree-process-leaves* t) (defvar *tree-breadth-first* nil) (defvar *tree-leaf-test* nil) (defvar *tree-branch-filter* nil) (defun %proc-branch (branch exec) (collecting (let ((stor nil)) (dotimes (i (@ branch length)) (let* ((*tree-stack* (push-copy *tree-stack* (getprop branch i))) (*tree-index-stack* (push-copy *tree-index-stack* i)) (item (getprop branch i)) (ts *tree-stack*) (tis *tree-index-stack*)) (if (funcall *tree-leaf-test* item) (when *tree-process-leaves* (collect (let ((*tree-leaf-p* t)) (lambda () (let ((*tree-stack* ts) (*tree-index-stack* tis)) (funcall exec item) nil))))) (progn (when *tree-process-branches* (collect (let ((*tree-leaf-p* nil)) (lambda () (let ((*tree-stack* ts) (*tree-index-stack* tis)) (funcall exec item) nil))))) FIXME : prev will want to be able to effect how and if of (let ((sub (lambda () (let ((*tree-stack* ts) (*tree-index-stack* tis)) (let ((res (%proc-branch (funcall (or *tree-branch-filter* #'identity) item) exec))) (mapcar #'funcall (chain res (slice 0 -1))) (getprop res -1)))))) (if *tree-breadth-first* (collect stor)))) FIXME : Does n't support switching between depth and breadth first mid - tree . (defun %handle-proc-branch-tail (tail) (cl-utilities:collecting (dolist (item tail) (dolist (res (funcall item)) (when (functionp res) (cl-utilities:collect res)))))) (defun call-with-tree (func tree &key (order :depth) (proc-branch t) proc-leaf branch-filter leaf-test) (unless (member order '(:depth :breadth)) (error "Order must be :depth or :breadth")) (let ((*tree-process-branches* proc-branch) (*tree-process-leaves* proc-leaf) (*tree-breadth-first* (eq order :breadth)) (*tree-leaf-test* (or leaf-test #'atom)) (*tree-branch-filter* branch-filter)) (let ((res (%proc-branch (funcall (or *tree-branch-filter* #'identity) tree) func))) (mapcar #'funcall (chain res (slice 0 -1))) (loop with items = (getprop res -1) while items do (setf items (%handle-proc-branch-tail items)))))) (defun alist->ps-object-code (alist &key (wrap t)) (let ((res (cl-utilities:collecting (dolist (item alist) (cl-utilities:collect (car item)) (cl-utilities:collect (cdr item)))))) (if wrap (cons 'ps:create res) res)))
3508dbbbb3e9107ca2f14177584fabad6e059072b922e2987e0a0e905bb20a06
aleator/CV
Hough.hs
{-#LANGUAGE ParallelListComp,ScopedTypeVariables#-} module Main where import CV.Image import CV.ImageOp import CV.Drawing import CV.ColourUtils import CV.HoughTransform import CV.Matrix main = do Just x <- loadImage "houghtest2.png" let hough = houghLinesStandard (unsafeImageTo8Bit x) 100 1 (pi/180) 100 hough2 = houghLinesProbabilistic (unsafeImageTo8Bit x) 100 1 (pi/180) 100 10 40 hough3 = houghLinesMultiscale (unsafeImageTo8Bit x) 100 5 (pi/90) 100 4 4 (w,h) = getSize x test = x <## [lineOp 1 2 (0,round y) (w,round $ y + (fromIntegral w)*negate (tan (pi/2-k))) | (y,k) <- toList hough] test2 = x <## [lineOp 1 2 ( x, y) ( u, v) | (x,y,u,v) <- toList hough2] test3 = x <## [lineOp 1 2 (0,round y) (w,round $ y + (fromIntegral w)*negate (tan (pi/2-k))) | (y,k) <- toList hough3] print hough print hough2 print hough3 saveImage "Hough_result.png" test saveImage "Hough_result2.png" test saveImage "Hough_result3.png" test3
null
https://raw.githubusercontent.com/aleator/CV/1e2c9116bcaacdf305044c861a1b36d0d8fb71b7/examples/Hough.hs
haskell
#LANGUAGE ParallelListComp,ScopedTypeVariables#
module Main where import CV.Image import CV.ImageOp import CV.Drawing import CV.ColourUtils import CV.HoughTransform import CV.Matrix main = do Just x <- loadImage "houghtest2.png" let hough = houghLinesStandard (unsafeImageTo8Bit x) 100 1 (pi/180) 100 hough2 = houghLinesProbabilistic (unsafeImageTo8Bit x) 100 1 (pi/180) 100 10 40 hough3 = houghLinesMultiscale (unsafeImageTo8Bit x) 100 5 (pi/90) 100 4 4 (w,h) = getSize x test = x <## [lineOp 1 2 (0,round y) (w,round $ y + (fromIntegral w)*negate (tan (pi/2-k))) | (y,k) <- toList hough] test2 = x <## [lineOp 1 2 ( x, y) ( u, v) | (x,y,u,v) <- toList hough2] test3 = x <## [lineOp 1 2 (0,round y) (w,round $ y + (fromIntegral w)*negate (tan (pi/2-k))) | (y,k) <- toList hough3] print hough print hough2 print hough3 saveImage "Hough_result.png" test saveImage "Hough_result2.png" test saveImage "Hough_result3.png" test3
30e125bacd3e6daea8eed68c9647b92f861a8a1719a98a189c9e455f24ab77a2
spell-music/csound-expression
Fm.hs
| Tools to build Fm synthesis graphs -- -- Example -- -- > f a = fmOut1 $ do > x1 < - fmOsc 1 > x2 < - fmOsc 2 -- > x1 `fmod` [(a, x2)] -- > return x1 module Csound.Air.Fm( -- * Fm graph Fm, FmNode, fmOsc', fmOsc, fmSig, fmod, fmOut, fmOut1, fmOut2, -- * Simplified Fm graph FmSpec(..), FmGraph(..), fmRun, -- ** Specific graphs -- | Algorithms for DX7 fm synth , dx_5 , dx_6 , dx_7 , dx_8 , dx_9 , dx_10 , dx_11 , , dx_13 , dx_14 , dx_15 , dx_16 , dx_17 , dx_18 , dx_19 , dx_20 , dx_21 , dx_22 , dx_23 , dx_24 , dx_25 , dx_26 , dx_27 , dx_28 , , dx_30 , dx_31 , dx_32 dx_9, dx_10, dx_11, dx_12, dx_13, dx_14, dx_15, dx_16, dx_17, dx_18, dx_19, dx_20, dx_21, dx_22, dx_23, dx_24, dx_25, dx_26, dx_27, dx_28, dx_29, dx_30, dx_31, dx_32 -} ) where import qualified Data.IntMap as IM import Control.Monad.Trans.State.Strict import Control.Monad import Csound.Typed import Csound.Air.Wave -- Fm graph rendering type Fm a = State St a newtype FmNode = FmNode Int type FmIdx = (Int, Sig) data Fmod = Fmod (Sig -> SE Sig) Sig [FmIdx] | Fsig Sig data St = St { st'newIdx :: Int , st'units :: [Fmod] , st'links :: IM.IntMap [FmIdx] } defSt :: St defSt = St { st'newIdx = 0 , st'units = [] , st'links = IM.empty } renderGraph :: [Fmod] -> [FmIdx] -> Sig -> SE [Sig] renderGraph units outs cps = do refs <- initUnits (length units) mapM_ (loopUnit refs) (zip [0 .. ] units) mapM (renderIdx refs) outs where initUnits n = mapM (const $ newRef (0 :: Sig)) [1 .. n] loopUnit refs (n, x) = writeRef (refs !! n) =<< case x of Fsig asig -> return asig Fmod wave modFreq subs -> do s <- fmap sum $ mapM (renderModIdx refs) subs wave (cps * modFreq + s) where renderIdx :: [Ref Sig] -> (Int, Sig) -> SE Sig renderIdx refs (idx, amp) = mul amp $ readRef (refs !! idx) renderModIdx :: [Ref Sig] -> (Int, Sig) -> SE Sig renderModIdx refs (idx, amp) = mul (amp * modFreq) $ readRef (refs !! idx) where modFreq = case (units !! idx) of Fmod _ m _ -> m * cps _ -> 1 mkGraph :: St -> [Fmod] mkGraph s = zipWith extractMod (reverse $ st'units s) [0 .. ] where extractMod x n = case x of Fmod alg w _ -> Fmod alg w (maybe [] id $ IM.lookup n (st'links s)) _ -> x toFmIdx :: (Sig, FmNode) -> FmIdx toFmIdx (amp, FmNode n) = (n, amp) --------------------------------------------------------- -- constructors -- | Creates fm node with generic wave. -- -- > fmOsc' wave modFreq fmOsc' :: (Sig -> SE Sig) -> Sig -> Fm FmNode fmOsc' wave idx = newFmod (Fmod wave idx []) -- | Creates fm node with sine wave. -- -- > fmOsc modFreq fmOsc :: Sig -> Fm FmNode fmOsc = fmOsc' rndOsc -- | Creates fm node with signal generator (it's independent from the main frequency). fmSig :: Sig -> Fm FmNode fmSig a = newFmod (Fsig a) newFmod :: Fmod -> Fm FmNode newFmod a = state $ \s -> let n = st'newIdx s s1 = s { st'newIdx = n + 1, st'units = a : st'units s } in (FmNode n, s1) -- modulator fmod :: FmNode -> [(Sig, FmNode)] -> Fm () fmod (FmNode idx) mods = state $ \s -> ((), s { st'links = IM.insertWithKey (\_ a b -> a ++ b) idx (fmap toFmIdx mods) (st'links s) }) -- outputs -- | Renders Fm synth to function. fmOut :: Fm [(Sig, FmNode)] -> Sig -> SE [Sig] fmOut fm = renderGraph (mkGraph s) (fmap toFmIdx outs) where (outs, s) = runState fm defSt -- | Renders mono output. fmOut1 :: Fm FmNode -> Sig -> SE Sig fmOut1 fm cps = fmap head $ fmOut (fmap (\x -> [(1, x)]) fm) cps -- | Renders stereo output. fmOut2 :: Fm (FmNode, FmNode) -> Sig -> SE Sig2 fmOut2 fm cps = fmap (\[a, b] -> (a, b)) $ fmOut (fmap (\(a, b) -> [(1, a), (1, b)]) fm) cps ----------------------------------------------------------------------- data FmSpec = FmSpec { fmWave :: [Sig -> SE Sig] , fmCps :: [Sig] , fmInd :: [Sig] , fmOuts :: [Sig] } data FmGraph = FmGraph { fmGraph :: [(Int, [Int])] , fmGraphOuts :: [Int] } fmRun :: FmGraph -> FmSpec -> Sig -> SE Sig fmRun graph spec' cps = fmap sum $ ($ cps) $ fmOut $ do ops <- zipWithM fmOsc' (fmWave spec) (fmCps spec) mapM_ (mkMod ops (fmInd spec)) (fmGraph graph) return $ zipWith (toOut ops) (fmOuts spec) (fmGraphOuts graph) where spec = addDefaults spec' toOut xs amp n = (amp, xs !! n) mkMod ops ixs (n, ms) = (ops !! n) `fmod` (fmap (\m -> (ixs !! m, ops !! m)) ms) addDefaults :: FmSpec -> FmSpec addDefaults spec = spec { fmWave = fmWave spec ++ repeat rndOsc , fmCps = fmCps spec ++ repeat 1 , fmInd = fmInd spec ++ repeat 1 , fmOuts = fmOuts spec ++ repeat 1 } | > + --+ > 6 | > + --+ > 5 > | > 2 4 > | | > 1 3 > + ---+ > +--+ > 6 | > +--+ > 5 > | > 2 4 > | | > 1 3 > +---+ -} dx_1 :: FmGraph dx_1 = FmGraph { fmGraphOuts = [1, 3] , fmGraph = [ (1, [2]) , (3, [4]) , (4, [5]) , (5, [6]) , (6, [6]) ]} | > 6 > | > 5 > + --+ | > 2 | 4 > + --+ | > 1 3 > + -----+ > 6 > | > 5 > +--+ | > 2 | 4 > +--+ | > 1 3 > +-----+ -} dx_2 :: FmGraph dx_2 = FmGraph { fmGraphOuts = [1, 3] , fmGraph = [ (1, [2]) , (2, [2]) , (3, [4]) , (5, [6]) ]} | > + --+ > 3 6 | > | + --+ > 2 5 > | | > 1 4 > + ---+ > +--+ > 3 6 | > | +--+ > 2 5 > | | > 1 4 > +---+ -} dx_3 :: FmGraph dx_3 = FmGraph { fmGraphOuts = [1, 4] , fmGraph = [ (1, [2]) , (2, [3]) , (4, [5]) , (5, [6]) , (6, [6]) ]} | > + --+ > 3 6 | > | | | > 2 5 | > | | | > 1 4 | > | + --+ > + ---+ > +--+ > 3 6 | > | | | > 2 5 | > | | | > 1 4 | > | +--+ > +---+ -} dx_4 :: FmGraph dx_4 = FmGraph { fmGraphOuts = [1, 4] , fmGraph = [ (1, [2]) , (2, [3]) , (4, [5]) , (5, [6]) , (6, [4]) ]} dx12 = DxGraph { dxGraphOuts = [ 3 , 1 ] , dxGraph = [ ( 3 , [ 4 , 5 , 6 ] ) , ( 1 , [ 2 ] ) , ( 2 , [ 2 ] ) ] } dx12 = DxGraph { dxGraphOuts = [3, 1] , dxGraph = [ (3, [4, 5, 6]) , (1, [2]) , (2, [2]) ]} -}
null
https://raw.githubusercontent.com/spell-music/csound-expression/29c1611172153347b16d0b6b133e4db61a7218d5/csound-expression/src/Csound/Air/Fm.hs
haskell
Example > f a = fmOut1 $ do > x1 `fmod` [(a, x2)] > return x1 * Fm graph * Simplified Fm graph ** Specific graphs | Algorithms for DX7 fm synth Fm graph rendering ------------------------------------------------------- constructors | Creates fm node with generic wave. > fmOsc' wave modFreq | Creates fm node with sine wave. > fmOsc modFreq | Creates fm node with signal generator (it's independent from the main frequency). modulator outputs | Renders Fm synth to function. | Renders mono output. | Renders stereo output. --------------------------------------------------------------------- + + -+ + + -+ + | + | ---+ + | + | ---+ + + -+ + + -+ + + -+ + + -+
| Tools to build Fm synthesis graphs > x1 < - fmOsc 1 > x2 < - fmOsc 2 module Csound.Air.Fm( Fm, FmNode, fmOsc', fmOsc, fmSig, fmod, fmOut, fmOut1, fmOut2, FmSpec(..), FmGraph(..), fmRun, , dx_5 , dx_6 , dx_7 , dx_8 , dx_9 , dx_10 , dx_11 , , dx_13 , dx_14 , dx_15 , dx_16 , dx_17 , dx_18 , dx_19 , dx_20 , dx_21 , dx_22 , dx_23 , dx_24 , dx_25 , dx_26 , dx_27 , dx_28 , , dx_30 , dx_31 , dx_32 dx_9, dx_10, dx_11, dx_12, dx_13, dx_14, dx_15, dx_16, dx_17, dx_18, dx_19, dx_20, dx_21, dx_22, dx_23, dx_24, dx_25, dx_26, dx_27, dx_28, dx_29, dx_30, dx_31, dx_32 -} ) where import qualified Data.IntMap as IM import Control.Monad.Trans.State.Strict import Control.Monad import Csound.Typed import Csound.Air.Wave type Fm a = State St a newtype FmNode = FmNode Int type FmIdx = (Int, Sig) data Fmod = Fmod (Sig -> SE Sig) Sig [FmIdx] | Fsig Sig data St = St { st'newIdx :: Int , st'units :: [Fmod] , st'links :: IM.IntMap [FmIdx] } defSt :: St defSt = St { st'newIdx = 0 , st'units = [] , st'links = IM.empty } renderGraph :: [Fmod] -> [FmIdx] -> Sig -> SE [Sig] renderGraph units outs cps = do refs <- initUnits (length units) mapM_ (loopUnit refs) (zip [0 .. ] units) mapM (renderIdx refs) outs where initUnits n = mapM (const $ newRef (0 :: Sig)) [1 .. n] loopUnit refs (n, x) = writeRef (refs !! n) =<< case x of Fsig asig -> return asig Fmod wave modFreq subs -> do s <- fmap sum $ mapM (renderModIdx refs) subs wave (cps * modFreq + s) where renderIdx :: [Ref Sig] -> (Int, Sig) -> SE Sig renderIdx refs (idx, amp) = mul amp $ readRef (refs !! idx) renderModIdx :: [Ref Sig] -> (Int, Sig) -> SE Sig renderModIdx refs (idx, amp) = mul (amp * modFreq) $ readRef (refs !! idx) where modFreq = case (units !! idx) of Fmod _ m _ -> m * cps _ -> 1 mkGraph :: St -> [Fmod] mkGraph s = zipWith extractMod (reverse $ st'units s) [0 .. ] where extractMod x n = case x of Fmod alg w _ -> Fmod alg w (maybe [] id $ IM.lookup n (st'links s)) _ -> x toFmIdx :: (Sig, FmNode) -> FmIdx toFmIdx (amp, FmNode n) = (n, amp) fmOsc' :: (Sig -> SE Sig) -> Sig -> Fm FmNode fmOsc' wave idx = newFmod (Fmod wave idx []) fmOsc :: Sig -> Fm FmNode fmOsc = fmOsc' rndOsc fmSig :: Sig -> Fm FmNode fmSig a = newFmod (Fsig a) newFmod :: Fmod -> Fm FmNode newFmod a = state $ \s -> let n = st'newIdx s s1 = s { st'newIdx = n + 1, st'units = a : st'units s } in (FmNode n, s1) fmod :: FmNode -> [(Sig, FmNode)] -> Fm () fmod (FmNode idx) mods = state $ \s -> ((), s { st'links = IM.insertWithKey (\_ a b -> a ++ b) idx (fmap toFmIdx mods) (st'links s) }) fmOut :: Fm [(Sig, FmNode)] -> Sig -> SE [Sig] fmOut fm = renderGraph (mkGraph s) (fmap toFmIdx outs) where (outs, s) = runState fm defSt fmOut1 :: Fm FmNode -> Sig -> SE Sig fmOut1 fm cps = fmap head $ fmOut (fmap (\x -> [(1, x)]) fm) cps fmOut2 :: Fm (FmNode, FmNode) -> Sig -> SE Sig2 fmOut2 fm cps = fmap (\[a, b] -> (a, b)) $ fmOut (fmap (\(a, b) -> [(1, a), (1, b)]) fm) cps data FmSpec = FmSpec { fmWave :: [Sig -> SE Sig] , fmCps :: [Sig] , fmInd :: [Sig] , fmOuts :: [Sig] } data FmGraph = FmGraph { fmGraph :: [(Int, [Int])] , fmGraphOuts :: [Int] } fmRun :: FmGraph -> FmSpec -> Sig -> SE Sig fmRun graph spec' cps = fmap sum $ ($ cps) $ fmOut $ do ops <- zipWithM fmOsc' (fmWave spec) (fmCps spec) mapM_ (mkMod ops (fmInd spec)) (fmGraph graph) return $ zipWith (toOut ops) (fmOuts spec) (fmGraphOuts graph) where spec = addDefaults spec' toOut xs amp n = (amp, xs !! n) mkMod ops ixs (n, ms) = (ops !! n) `fmod` (fmap (\m -> (ixs !! m, ops !! m)) ms) addDefaults :: FmSpec -> FmSpec addDefaults spec = spec { fmWave = fmWave spec ++ repeat rndOsc , fmCps = fmCps spec ++ repeat 1 , fmInd = fmInd spec ++ repeat 1 , fmOuts = fmOuts spec ++ repeat 1 } | > 6 | > 5 > | > 2 4 > | | > 1 3 > 6 | > 5 > | > 2 4 > | | > 1 3 -} dx_1 :: FmGraph dx_1 = FmGraph { fmGraphOuts = [1, 3] , fmGraph = [ (1, [2]) , (3, [4]) , (4, [5]) , (5, [6]) , (6, [6]) ]} | > 6 > | > 5 > 2 | 4 > 1 3 > 6 > | > 5 > 2 | 4 > 1 3 -} dx_2 :: FmGraph dx_2 = FmGraph { fmGraphOuts = [1, 3] , fmGraph = [ (1, [2]) , (2, [2]) , (3, [4]) , (5, [6]) ]} | > 3 6 | > 2 5 > | | > 1 4 > 3 6 | > 2 5 > | | > 1 4 -} dx_3 :: FmGraph dx_3 = FmGraph { fmGraphOuts = [1, 4] , fmGraph = [ (1, [2]) , (2, [3]) , (4, [5]) , (5, [6]) , (6, [6]) ]} | > 3 6 | > | | | > 2 5 | > | | | > 1 4 | > 3 6 | > | | | > 2 5 | > | | | > 1 4 | -} dx_4 :: FmGraph dx_4 = FmGraph { fmGraphOuts = [1, 4] , fmGraph = [ (1, [2]) , (2, [3]) , (4, [5]) , (5, [6]) , (6, [4]) ]} dx12 = DxGraph { dxGraphOuts = [ 3 , 1 ] , dxGraph = [ ( 3 , [ 4 , 5 , 6 ] ) , ( 1 , [ 2 ] ) , ( 2 , [ 2 ] ) ] } dx12 = DxGraph { dxGraphOuts = [3, 1] , dxGraph = [ (3, [4, 5, 6]) , (1, [2]) , (2, [2]) ]} -}
90d78d31b76044db07db4cb01dc444c3052851edc57df0276ce1575d7d325f60
helpshift/gulfstream
object_test.clj
(ns gulfstream.object-test (:require [hara.object.util :as util] [hara.object :as object] [hara.reflect :as reflect] [gulfstream.dom :as dom] [gulfstream.graph.ui :as ui] [gulfstream.core :as gs])) (comment ;; Create a Graph (gs/graph {:ui {:title "DOM"} :links {:a #{} :b #{:a :c} :c #{}} :properties {:ui.class {"axis" #{:a :c}}}}) ;; Convert Graph into Data (object/to-data gs/*current-graph*) ;;=> ;; Show Window (gs/display gs/*current-graph*) ;; Convert Viewer into Data (object/to-data gs/*current-viewer*) Access Elements in the (dom/dom gs/*current-graph*) {[:b :a] {}, [:b :c] {}, :c {:attributes {:ui.class "axis"}}, :b {}, :a {:attributes {:ui.class "axis"}}} Update Elements in the (dom/renew gs/*current-graph* {[:b :a] {} [:a :c] {} [:e :d] {:attributes {:label "e->d"}} :c {:attributes {:ui.class "axis" :label "c"}} :b {:attributes {:ui.class "axis" :label "b"}} :a {:attributes {:ui.class "axis" :label "a"}} :d {:attributes {:label "d"}} :e {:attributes {:label "e"}} }) ;; Apply stylesheet (ui/stylesheet gs/*current-graph* [[:node.axis {:fill-color "#00c" :size "20px"}] [:node {:fill-color "green"}] [:node:clicked {:fill-color "red"}] [:edge {:arrow-shape "arrow" :arrow-size "10px, 5px"}]]) ;; hara.object (object/access gs/*current-graph* :attributes {:ui.title "Hello World"}) (object/access gs/*current-graph* :attributes) (object/access (object/access gs/*current-viewer* [:default-view :camera :metrics :high-point])) (object/to-data gs/*current-graph*) (type gs/*current-graph*) (object/access gs/*current-graph* [:attributes]))
null
https://raw.githubusercontent.com/helpshift/gulfstream/f5e3f4159a9335bcf73ccbb750e0e6b17bde8773/candidates/test/gulfstream/object_test.clj
clojure
Create a Graph Convert Graph into Data => Show Window Convert Viewer into Data Apply stylesheet hara.object
(ns gulfstream.object-test (:require [hara.object.util :as util] [hara.object :as object] [hara.reflect :as reflect] [gulfstream.dom :as dom] [gulfstream.graph.ui :as ui] [gulfstream.core :as gs])) (comment (gs/graph {:ui {:title "DOM"} :links {:a #{} :b #{:a :c} :c #{}} :properties {:ui.class {"axis" #{:a :c}}}}) (object/to-data gs/*current-graph*) (gs/display gs/*current-graph*) (object/to-data gs/*current-viewer*) Access Elements in the (dom/dom gs/*current-graph*) {[:b :a] {}, [:b :c] {}, :c {:attributes {:ui.class "axis"}}, :b {}, :a {:attributes {:ui.class "axis"}}} Update Elements in the (dom/renew gs/*current-graph* {[:b :a] {} [:a :c] {} [:e :d] {:attributes {:label "e->d"}} :c {:attributes {:ui.class "axis" :label "c"}} :b {:attributes {:ui.class "axis" :label "b"}} :a {:attributes {:ui.class "axis" :label "a"}} :d {:attributes {:label "d"}} :e {:attributes {:label "e"}} }) (ui/stylesheet gs/*current-graph* [[:node.axis {:fill-color "#00c" :size "20px"}] [:node {:fill-color "green"}] [:node:clicked {:fill-color "red"}] [:edge {:arrow-shape "arrow" :arrow-size "10px, 5px"}]]) (object/access gs/*current-graph* :attributes {:ui.title "Hello World"}) (object/access gs/*current-graph* :attributes) (object/access (object/access gs/*current-viewer* [:default-view :camera :metrics :high-point])) (object/to-data gs/*current-graph*) (type gs/*current-graph*) (object/access gs/*current-graph* [:attributes]))
49b53611595ac5784540e87f99db9620f747387f1046f4a05a2cc4b06950c343
codxse/zenius-material
project.clj
(defproject zenius-material "0.1.1-1" :description "A ClojureScript reagent wrapper for Material-UI v1.x" :url "-material" :license {:name "Eclipse Public License" :url "-v10.html"} :dependencies [[org.clojure/clojure "1.9.0"] [org.clojure/clojurescript "1.10.312"] [reagent "0.8.1" :exclusions [cljsjs/react cljsjs/react-dom]] [cljsjs/material-ui "1.2.1-0"] [cljs-react-material-ui "0.2.50"]])
null
https://raw.githubusercontent.com/codxse/zenius-material/0e5a2c64fd3455f81b8a43ff41f407c7bcdb8ce9/project.clj
clojure
(defproject zenius-material "0.1.1-1" :description "A ClojureScript reagent wrapper for Material-UI v1.x" :url "-material" :license {:name "Eclipse Public License" :url "-v10.html"} :dependencies [[org.clojure/clojure "1.9.0"] [org.clojure/clojurescript "1.10.312"] [reagent "0.8.1" :exclusions [cljsjs/react cljsjs/react-dom]] [cljsjs/material-ui "1.2.1-0"] [cljs-react-material-ui "0.2.50"]])
125ab11851bf4e799848048181def0028546ff3354f97e8c9cbbc421da85b9ff
manuel-serrano/hop
service.scm
;*=====================================================================*/ * serrano / prgm / project / hop / hop / hopscript / service.scm * / ;* ------------------------------------------------------------- */ * Author : * / * Creation : Thu Oct 17 08:19:20 2013 * / * Last change : Fri Nov 18 07:59:39 2022 ( serrano ) * / * Copyright : 2013 - 22 * / ;* ------------------------------------------------------------- */ * HopScript service implementation * / ;*=====================================================================*/ ;*---------------------------------------------------------------------*/ ;* The module */ ;*---------------------------------------------------------------------*/ (module __hopscript_service (library hop js2scheme) (include "types.sch" "stringliteral.sch") (import __hopscript_types __hopscript_arithmetic __hopscript_object __hopscript_error __hopscript_private __hopscript_public __hopscript_property __hopscript_function __hopscript_worker __hopscript_json __hopscript_lib __hopscript_array __hopscript_promise __hopscript_websocket) (export (js-init-service! ::JsGlobalObject) (js-make-hopframe ::JsGlobalObject ::obj ::obj ::obj) (js-create-service::JsService ::JsGlobalObject ::obj ::obj ::obj ::bool ::bool ::WorkerHopThread) (js-make-service::JsService ::JsGlobalObject ::procedure ::bstring ::bool ::bool ::int ::obj ::obj))) ;*---------------------------------------------------------------------*/ ;* &begin! */ ;*---------------------------------------------------------------------*/ (define __js_strings (&begin!)) ;*---------------------------------------------------------------------*/ * object - serializer : : ... * / ;*---------------------------------------------------------------------*/ (register-class-serialization! JsService (lambda (o) (with-access::JsService o (svc) (if svc (with-access::hop-service svc (path resource) (vector path resource)) (vector #t #t)))) (lambda (o ctx) (let* ((path (vector-ref o 0)) (svcp (lambda (this . args) (js-make-hopframe ctx this path args))) (hopsvc (cond ((service-exists? path) (get-service path)) (else (instantiate::hop-service (id (string->symbol path)) (wid (let ((i (string-index path #\?))) (string->symbol (if i (substring path 0 i) path)))) (args '()) (proc (lambda l l)) (javascript "") (path path) (resource (vector-ref o 1))))))) (js-make-service ctx svcp (basename path) #f #f -1 (js-current-worker) hopsvc)))) ;*---------------------------------------------------------------------*/ ;* object-serializer ::JsHopFrame ... */ ;*---------------------------------------------------------------------*/ (register-class-serialization! JsHopFrame (lambda (o) (with-access::JsHopFrame o (srv path args options header path) (vector (unless (isa? srv JsWebSocket) srv) path args options header))) (lambda (o ctx) (if (and (vector? o) (=fx (vector-length o) 5)) (with-access::JsGlobalObject ctx (js-hopframe-prototype) (instantiateJsHopFrame (__proto__ js-hopframe-prototype) (%this ctx) (srv (vector-ref o 0)) (path (vector-ref o 1)) (args (vector-ref o 2)) (options (vector-ref o 3)) (header (vector-ref o 4)))) (error "HopFrame" "wrong frame" o)))) ;*---------------------------------------------------------------------*/ * object - serializer : : ... * / ;*---------------------------------------------------------------------*/ (register-class-serialization! JsServer (lambda (o ctx) (if (isa? ctx JsGlobalObject) (with-access::JsServer o (obj) (with-access::server obj (host port ssl authorization version) (vector host port ssl (if (string? authorization) authorization #f) version (js-jsobject->plist o ctx)))) (error "obj->string ::JsServer" "Not a JavaScript context" ctx))) (lambda (o ctx) (cond ((not (isa? ctx JsGlobalObject)) (error "string->obj ::JsServer" "Not a JavaScript context" ctx)) ((and (vector? o) (=fx (vector-length o) 6)) (with-access::JsGlobalObject ctx (js-server-prototype) (let ((srv (instantiateJsServer (__proto__ js-server-prototype) (obj (instantiate::server (host (vector-ref o 0)) (port (vector-ref o 1)) (ssl (vector-ref o 2)) (ctx ctx) (authorization (vector-ref o 3)) (version (vector-ref o 4))))))) (let loop ((rest (vector-ref o 5))) (if (null? rest) srv (begin (js-put! srv (js-keyword->jsstring (car rest)) (js-obj->jsobject (cadr rest) ctx) #f ctx) (loop (cddr rest)))))))) (else (error "JsServer" "wrong server" o))))) ;*---------------------------------------------------------------------*/ ;* js-tostring ::JsHopFrame ... */ ;*---------------------------------------------------------------------*/ (define-method (js-tostring obj::JsHopFrame %this) (hopframe->string obj %this)) ;*---------------------------------------------------------------------*/ ;* xml-primitive-value ::JsHopFrame ... */ ;*---------------------------------------------------------------------*/ (define-method (xml-primitive-value o::JsHopFrame ctx) (with-access::JsHopFrame o (path) (hopframe->string o ctx))) ;*---------------------------------------------------------------------*/ * js - donate : : ... * / ;*---------------------------------------------------------------------*/ (define-method (js-donate obj::JsService worker::WorkerHopThread %_this) (define (relative-path path) (substring path (string-length (hop-service-base)))) (with-access::WorkerHopThread worker (%this) (with-access::JsService obj (svc info arity) (with-access::hop-service svc (path) (let* ((path (relative-path path)) (proc (js-make-function %this (lambda (this) (js-undefined)) arity (js-function-info :name (vector-ref info 0) :len (vector-ref info 1)) :prototype #f :__proto__ #f :strict 'strict :minlen -1 :alloc js-not-a-constructor-alloc :constrsize 3 :method #f)) (nobj (js-create-service %this proc path #f #f #t worker))) (js-for-in obj (lambda (k %this) (js-put! nobj (js-donate k worker %_this) (js-donate (js-get obj k %_this) worker %_this) #f %this)) %this) nobj))))) ;*---------------------------------------------------------------------*/ * xml - unpack : : ... * / ;*---------------------------------------------------------------------*/ (define-method (xml-unpack o::JsService ctx) o) ;*---------------------------------------------------------------------*/ ;* xml-attribute-encode ::JsHopFrame ... */ ;*---------------------------------------------------------------------*/ (define-method (xml-attribute-encode o::JsHopFrame) (with-access::JsHopFrame o (%this) (hopframe->string o %this))) ;*---------------------------------------------------------------------*/ * hop->javascript : : ... * / ;* ------------------------------------------------------------- */ ;* See runtime/js_comp.scm in the Hop library for the definition */ ;* of the generic. */ ;*---------------------------------------------------------------------*/ (define-method (hop->javascript o::JsService op compile isexpr ctx) (with-access::JsService o (svc) (compile svc op))) ;*---------------------------------------------------------------------*/ ;* hop->javascript ::JsHopFrame ... */ ;*---------------------------------------------------------------------*/ (define-method (hop->javascript o::JsHopFrame op compile isexpr ctx) (display "hop_url_encoded_to_obj('" op) (display (url-path-encode (obj->string o 'hop-client)) op) (display "')" op)) ;*---------------------------------------------------------------------*/ * hop->javascript : : ... * / ;*---------------------------------------------------------------------*/ (define-method (hop->javascript o::JsServer op compile isexpr ctx) (display "hop_url_encoded_to_obj('" op) (display (url-path-encode (obj->string o ctx)) op) (display "')" op)) ;*---------------------------------------------------------------------*/ ;* hop-register-value ::object ... */ ;*---------------------------------------------------------------------*/ (define-method (hop-register-value o::object register::procedure) #t) ;*---------------------------------------------------------------------*/ * json->obj : : ... * / ;*---------------------------------------------------------------------*/ (define-method (json->obj %this::JsObject ip::input-port) (js-json-parser ip #f #f #t %this)) ;*---------------------------------------------------------------------*/ ;* post-multipart->obj ::JsGlobalObject ... */ ;*---------------------------------------------------------------------*/ (define-method (post-multipart->obj %this::JsGlobalObject val enc) (cond ((string=? enc "string") (js-string->jsstring val)) ((string=? enc "integer") (js-string->number val %this)) ((string=? enc "keyword") (js-string->jsstring val)) ((string=? enc "file") val) (else (string->obj val #f %this)))) ;*---------------------------------------------------------------------*/ * j2s - js - literal : : ... * / ;*---------------------------------------------------------------------*/ (define-method (j2s-js-literal o::JsService ctx) (with-access::JsService o (svc) (with-access::hop-service svc (path) (format "HopService( '~a', undefined )" path)))) ;*---------------------------------------------------------------------*/ ;* js-init-service! ... */ ;*---------------------------------------------------------------------*/ (define (js-init-service! %this::JsGlobalObject) (with-access::JsGlobalObject %this (js-function js-service-pcache js-service-prototype js-hopframe-prototype) (let ((js-function-prototype (js-object-proto js-function))) ;; local constant strings initialization (unless (vector? __js_strings) (set! __js_strings (&init!))) service pcache (set! js-service-pcache ((@ js-make-pcache-table __hopscript_property) 1 "service")) ;; service prototype (with-access::JsGlobalObject %this (__proto__) (set! js-service-prototype (instantiateJsService (__proto__ js-function-prototype) (worker (class-nil WorkerHopThread)) (alloc js-not-a-constructor-alloc) (prototype (js-object-proto %this)) (info (js-function-info :name "" :len -1)) (procedure list) (svc #f)))) (js-bind! %this js-service-prototype (& "name") :value (js-ascii->jsstring "service") :writable #f :configurable #f :enumerable #f :hidden-class #t) (js-bind! %this js-service-prototype (& "resource") :value (js-make-function %this (lambda (this file) (js-string->jsstring (service-resource this (js-jsstring->string file)))) (js-function-arity 1 0) (js-function-info :name "resource" :len 1)) :writable #t :configurable #t :enumerable #f :hidden-class #t) (js-bind! %this js-service-prototype (& "unregister") :value (js-make-function %this (lambda (this) (when (isa? this JsService) (with-access::JsService this (svc) (unregister-service! svc))) (js-undefined)) (js-function-arity 0 0) (js-function-info :name "unregister" :len 0)) :writable #t :configurable #t :enumerable #f :hidden-class #t) (js-bind! %this js-service-prototype (& "timeout") :get (js-make-function %this (lambda (this) (with-access::JsService this (svc) (with-access::hop-service svc (timeout) timeout))) (js-function-arity 0 0) (js-function-info :name "timeout" :len 0)) :hidden-class #t) (js-bind! %this js-service-prototype (& "ttl") :get (js-make-function %this (lambda (this) (with-access::JsService this (svc) (with-access::hop-service svc (ttl) ttl))) (js-function-arity 0 0) (js-function-info :name "ttl.get" :len 0)) :set (js-make-function %this (lambda (this v) (with-access::JsService this (svc) (with-access::hop-service svc (ttl) (set! ttl (js-tointeger v %this))))) (js-function-arity 1 0) (js-function-info :name "ttl.set" :len 1)) :hidden-class #t) (js-bind! %this js-service-prototype (& "addURL") :value (js-make-function %this (lambda (this url) (service-add-url! this url %this)) (js-function-arity 1 0) (js-function-info :name "addURL" :len 1)) :hidden-class #t) (js-bind! %this js-service-prototype (& "removeURL") :value (js-make-function %this (lambda (this url) (service-remove-url! this url %this)) (js-function-arity 1 0) (js-function-info :name "removeURL" :len 1)) :hidden-class #t) (js-bind! %this js-service-prototype (& "getURLs") :value (js-make-function %this (lambda (this) (service-get-urls this %this)) (js-function-arity 0 0) (js-function-info :name "getURLs" :len 0)) :hidden-class #t) HopFrame prototype and constructor (set! js-hopframe-prototype (instantiateJsObject (__proto__ (js-object-proto %this)) (elements ($create-vector 8)))) (js-bind! %this js-hopframe-prototype (& "post") :value (js-make-function %this (lambda (this::JsHopFrame success fail-or-opt) (with-access::JsHopFrame this (args) (post this success fail-or-opt %this #t))) (js-function-arity 2 0) (js-function-info :name "post" :len 2)) :hidden-class #t) (js-bind! %this js-hopframe-prototype (& "postSync") :value (js-make-function %this (lambda (this::JsHopFrame opt) (with-access::JsHopFrame this (args) (post this #f opt %this #f))) (js-function-arity 1 0) (js-function-info :name "postSync" :len 2)) :hidden-class #t) (js-bind! %this js-hopframe-prototype (& "call") :value (js-make-function %this (lambda (this::JsHopFrame req opt) (with-access::JsHopFrame this (path args) (let ((svc (get-service path))) (with-access::hop-service svc (proc) (apply proc req args))))) (js-function-arity 2 0) (js-function-info :name "call" :len 2)) :hidden-class #t) (js-bind! %this js-hopframe-prototype (& "toString") :value (js-make-function %this (lambda (this::JsHopFrame) (js-string->jsstring (hopframe->string this %this))) (js-function-arity 0 0) (js-function-info :name "toString" :len 0)) :hidden-class #t) (js-bind! %this js-hopframe-prototype (& "inspect") :value (js-make-function %this (lambda (this::JsHopFrame) (js-string->jsstring (hopframe->string this %this))) (js-function-arity 0 0) (js-function-info :name "inspect" :len 0)) :hidden-class #t) (js-bind! %this js-hopframe-prototype (& "getHeader") :value (js-make-function %this (lambda (this::JsHopFrame) (with-access::JsHopFrame this (header) header)) (js-function-arity 0 0) (js-function-info :name "getHeader" :len 0)) :hidden-class #t) (js-bind! %this js-hopframe-prototype (& "setHeader") :value (js-make-function %this (lambda (this::JsHopFrame hd) (with-access::JsHopFrame this (header) (set! header hd) this)) (js-function-arity 1 0) (js-function-info :name "setHeader" :len 1)) :hidden-class #t) (js-bind! %this js-hopframe-prototype (& "getOptions") :value (js-make-function %this (lambda (this::JsHopFrame opts) opts) (js-function-arity 1 0) (js-function-info :name "getOptions" :len 1)) :hidden-class #t) (js-bind! %this js-hopframe-prototype (& "setOptions") :value (js-make-function %this (lambda (this::JsHopFrame opts) (with-access::JsHopFrame this (options) (set! options opts) this)) (js-function-arity 1 0) (js-function-info :name "setOptions" :len 1)) :hidden-class #t) (define (%js-service this proc path) (js-create-service %this proc (unless (eq? path (js-undefined)) (js-tostring path %this)) #f #t #f (js-current-worker))) (define (%js-hopframe this path args) (js-make-hopframe %this this path args)) (letrec ((js-service (js-make-function %this %js-service (js-function-arity %js-service) (js-function-info :name "Service" :len 2) :__proto__ js-function-prototype :prototype js-service-prototype :size 5 :alloc js-no-alloc)) (js-hopframe (js-make-function %this %js-hopframe (js-function-arity %js-hopframe) (js-function-info :name "HopFrame" :len 1) :__proto__ js-function-prototype :prototype js-hopframe-prototype :alloc js-no-alloc))) (js-bind! %this %this (& "Service") :configurable #f :enumerable #f :value js-service :hidden-class #t) (js-bind! %this %this (& "HopFrame") :configurable #f :enumerable #f :value js-hopframe :hidden-class #t) (js-bind! %this js-service (& "exists") :configurable #f :enumerable #f :value (js-make-function %this (lambda (this svc) (service-exists? (js-tostring svc %this))) (js-function-arity 1 0) (js-function-info :name "exists" :len 1)) :hidden-class #t) (js-bind! %this js-service (& "getService") :configurable #f :enumerable #f :value (js-make-function %this (lambda (this svc) (let* ((name (js-tostring svc %this)) (svc (get-service-from-name name))) (js-make-service %this (lambda (this . args) (with-access::hop-service svc (path) (js-make-hopframe %this this path args))) name #f #f -1 (js-current-worker) svc))) (js-function-arity 1 0) (js-function-info :name "getService" :len 1)) :hidden-class #t) (js-bind! %this js-service (& "getServiceFromPath") :configurable #f :enumerable #f :value (js-make-function %this (lambda (this svc) (let* ((name (js-tostring svc %this)) (svc (get-service name))) (js-make-service %this (lambda (this . args) (with-access::hop-service svc (path) (js-make-hopframe %this this path args))) name #f #f -1 (js-current-worker) svc))) (js-function-arity 1 0) (js-function-info :name "getService" :len 1)) :hidden-class #t) (js-bind! %this js-service (& "allowURL") :configurable #f :enumerable #f :value (js-make-function %this (lambda (this url) (cond ((not (hop-filters-open?)) (js-raise-type-error %this "allowURL must called from within the hoprc.js file" url)) ((not (memq service-url-filter (hop-filters))) (set! *url-redirect* (create-hashtable)) (hop-filter-add! service-url-filter) (add-service-allow-url! url)) (else (add-service-allow-url! url)))) (js-function-arity 1 0) (js-function-info :name "allowURL" :len 1)) :hidden-class #t)) (js-undefined)))) ;*---------------------------------------------------------------------*/ ;* js-make-hopframe ... */ ;*---------------------------------------------------------------------*/ (define (js-make-hopframe %this::JsGlobalObject srv path args) (with-access::JsGlobalObject %this (js-hopframe-prototype js-object js-server) (instantiateJsHopFrame (__proto__ js-hopframe-prototype) (%this %this) (srv srv) (path path) (args args)))) ;*---------------------------------------------------------------------*/ ;* hopframe->string ... */ ;*---------------------------------------------------------------------*/ (define (hopframe->string::bstring frame::JsHopFrame %this) (with-access::JsHopFrame frame (srv path args) (let ((sans-srv (cond ((not (pair? args)) path) (else (hop-apply-url path args %this))))) (if (isa? srv JsServer) (with-access::JsServer srv (obj) (with-access::server obj (ssl host port authorization) (let ((scheme (if ssl "https" "http"))) (if authorization (format "~a://~a:~a:~a~a" scheme authorization host port sans-srv) (format "~a://~a:~a~a" scheme host port sans-srv))))) sans-srv)))) ;*---------------------------------------------------------------------*/ ;* post ... */ ;*---------------------------------------------------------------------*/ (define (post this::JsHopFrame success fail-or-opt %this async) (define (multipart-form-arg val) (cond ((string? val) `("string" ,val "hop-encoding: string")) ((js-jsstring? val) `("string" ,(js-jsstring->string val) "hop-encoding: string")) ((integer? val) `("integer" ,val "hop-encoding: integer")) ((keyword? val) `("keyword" ,(keyword->string val) "hop-encoding: keyword")) (else `("hop" ,(obj->string val %this) "hop-encoding: hop")))) (define (scheme->js val) (js-obj->jsobject val %this)) (define (js-get-string opt key) (let ((v (js-get opt key %this))) (unless (eq? v (js-undefined)) (js-tostring v %this)))) (define (post-request-thread name %this callback fail scheme host port auth) (with-access::JsHopFrame this (path args header options) (let ((user (js-get-string options (& "user"))) (password (js-get-string options (& "password"))) (header (when header (js-jsobject->alist header %this))) (args (map multipart-form-arg args)) (receiver (lambda (ctx thunk) (with-access::JsGlobalObject ctx (worker) (js-worker-exec worker path #t thunk))))) (thread-start! (instantiate::hopthread (name name) (body (lambda () (with-handler (lambda (e) (exception-notify e) (with-access::JsGlobalObject %this (worker) (js-worker-exec worker path #t (lambda () (fail e))))) (with-hop-remote path callback fail :scheme scheme :host host :port port :user user :password password :authorization auth :header header :ctx %this :receiver receiver :json-parser json-parser :x-javascript-parser x-javascript-parser :connection-timeout (hop-connection-timeout) :args args)))))) (js-undefined)))) (define (post-server-promise this %this host port auth scheme) (with-access::JsGlobalObject %this (js-promise) (letrec* ((callback (lambda (x) (js-promise-async p (lambda () (js-promise-resolve p x))))) (fail (lambda (x) (js-promise-async p (lambda () (js-promise-reject p x))))) (p (js-new %this js-promise (js-make-function %this (lambda (_ resolve reject) (post-request-thread "post-server-promise" %this callback fail scheme host port auth)) (js-function-arity 2 0) (js-function-info :name "executor" :len 2))))) p))) (define (post-server-async this success failure %this host port auth scheme) (with-access::JsHopFrame this (path) (with-access::JsGlobalObject %this (worker) (let ((callback (when (js-procedure? success) (lambda (x) (js-call1 %this success %this x)))) (fail (if (js-procedure? failure) (lambda (obj) (js-call1 %this failure %this obj)) exception-notify))) (post-request-thread "post-async" %this callback fail scheme host port auth))))) (define (post-server-sync this %this host port auth scheme) (with-access::JsHopFrame this (path args header options) (let ((receiver (lambda (ctx thunk) (with-access::JsGlobalObject ctx (worker) (js-worker-exec worker path #t thunk))))) (with-hop-remote path (lambda (x) x) #f :scheme scheme :host host :port port :user (js-get-string options (& "user")) :password (js-get-string options (& "password")) :authorization auth :header (when header (js-jsobject->alist header %this)) :ctx %this :receiver receiver :json-parser json-parser :x-javascript-parser x-javascript-parser :args (map multipart-form-arg args))))) (define (post-server this success failure %this async host port auth scheme) (cond ((not async) (post-server-sync this %this host port auth scheme)) ((or (js-procedure? success) (js-procedure? failure)) (post-server-async this success failure %this host port auth scheme)) (else (post-server-promise this %this host port auth scheme)))) (define (post-websocket-promise this::JsHopFrame srv::JsWebSocket) (with-access::JsWebSocket srv (recvqueue) (with-access::JsGlobalObject %this (js-promise) (let ((frameid (get-frame-id))) (letrec ((p (js-new %this js-promise (js-make-function %this (lambda (_ resolve reject) (js-websocket-post srv this frameid)) (js-function-arity 2 0) (js-function-info :name "executor" :len 2))))) (cell-set! recvqueue (cons (cons frameid p) (cell-ref recvqueue))) p))))) (define (post-websocket-async this::JsHopFrame srv::JsWebSocket success failure) (with-access::JsHopFrame this (path) (let ((callback (when (js-procedure? success) (lambda (x) (js-worker-push-thunk! (js-current-worker) path (lambda () (js-call1 %this success %this x)))))) (fail (when (js-procedure? failure) (lambda (obj) (js-worker-push-thunk! (js-current-worker) path (lambda () (js-call1 %this failure %this obj))))))) (with-access::JsWebSocket srv (ws recvqueue) (with-access::websocket ws (%mutex) (let ((frameid (get-frame-id))) (js-websocket-post srv this frameid) (cell-set! recvqueue (cons (cons frameid (cons callback fail)) (cell-ref recvqueue))))))))) (define (post-websocket-sync this::JsHopFrame srv::JsWebSocket) (with-access::JsHopFrame this (path) (with-access::JsWebSocket srv (ws recvqueue) (with-access::websocket ws (%mutex %socket) (if (socket? %socket) (let* ((frameid (get-frame-id)) (cv (make-condition-variable)) (cell (cons cv %mutex))) (js-websocket-post srv this frameid) (cell-set! recvqueue (cons (cons frameid cell) (cell-ref recvqueue))) (condition-variable-wait! cv %mutex) (or (car cell) (raise (cdr cell)))) (js-raise-type-error %this "not connected ~s" srv)))))) (define (post-websocket this::JsHopFrame success failure %this async srv::JsWebSocket) (with-access::JsWebSocket srv (ws) (with-access::websocket ws (%mutex) (synchronize %mutex (cond ((not async) (post-websocket-sync this srv)) ((or (js-procedure? success) (js-procedure? failure)) (post-websocket-async this srv success failure)) (else (post-websocket-promise this srv))))))) (with-access::JsHopFrame this (srv) (cond ((isa? srv JsServer) (with-access::JsServer srv (obj) (with-access::server obj (host port authorization ssl) (post-server this success fail-or-opt %this async host port authorization (if ssl 'https 'http))))) ((isa? srv JsWebSocket) (post-websocket this success fail-or-opt %this async srv)) ((or (js-procedure? fail-or-opt) (not (js-object? fail-or-opt))) (post-server this success fail-or-opt %this async "localhost" (hop-default-port) #f (hop-default-scheme))) (else (with-access::JsHopFrame this (path args) (post-options-deprecated path (map multipart-form-arg args) success fail-or-opt %this async)))))) ;*---------------------------------------------------------------------*/ ;* get-frame-id ... */ ;*---------------------------------------------------------------------*/ (define (get-frame-id) (let ((v frame-id)) (set! frame-id (+fx 1 frame-id)) v)) (define frame-id 0) ;*---------------------------------------------------------------------*/ ;* post-options-deprecated ... */ ;*---------------------------------------------------------------------*/ (define (post-options-deprecated svc::bstring args success opt %this async) (let ((host "localhost") (port (hop-default-port)) (user #f) (password #f) (authorization #f) (fail #f) (failjs #f) (asynchronous async) (header #f) (scheme 'http) (worker (js-current-worker))) (cond ((js-procedure? opt) (set! fail (if asynchronous (lambda (obj) (js-worker-push-thunk! worker svc (lambda () (js-call1 %this opt %this obj)))) (lambda (obj) (js-call1 %this opt %this obj))))) ((not (eq? opt (js-undefined))) (let* ((v (js-get opt (& "server") %this)) (o (if (eq? v (js-undefined)) opt v)) (a (js-get o (& "authorization") %this)) (h (js-get o (& "host") %this)) (p (js-get o (& "port") %this)) (u (js-get opt (& "user") %this)) (w (js-get opt (& "password") %this)) (f (js-get opt (& "fail") %this)) (y (js-get opt (& "asynchronous") %this)) (s (js-get opt (& "scheme") %this)) (c (js-get opt (& "ssl") %this)) (r (js-get opt (& "header") %this))) (unless (eq? h (js-undefined)) (set! host (js-tostring h %this))) (unless (eq? p (js-undefined)) (set! port (js-tointeger p %this))) (unless (eq? u (js-undefined)) (set! user (js-tostring u %this))) (unless (eq? w (js-undefined)) (set! password (js-tostring w %this))) (unless (eq? a (js-undefined)) (set! authorization (js-tostring a %this))) (unless (js-totest y) (when (js-in? opt (& "asynchronous") %this) (set! asynchronous #f))) (when (js-totest c) (set! scheme 'https)) (unless (eq? s (js-undefined)) (set! scheme (string->symbol (js-tostring s %this)))) (when (js-procedure? f) (set! failjs f) (set! fail (lambda (obj) (if asynchronous (js-worker-push-thunk! worker svc (lambda () (js-call1 %this f %this obj))) (js-call1 %this f %this obj))))) (when (js-object? r) (set! header (js-jsobject->alist r %this)))))) (define (scheme->js val) (js-obj->jsobject val %this)) (define (post-request callback) (let ((receiver (lambda (ctx thunk) (with-access::JsGlobalObject ctx (worker) (js-worker-exec worker svc #t thunk))))) (with-hop-remote svc callback fail :scheme scheme :host host :port port :user user :password password :authorization authorization :header header :ctx %this :receiver receiver :json-parser json-parser :x-javascript-parser x-javascript-parser :args args))) (define (spawn-thread) (thread-start! (instantiate::hopthread (name "spawn-thread-deprecated") (body (lambda () (with-handler (lambda (e) (exception-notify e) (if failjs (js-worker-push-thunk! worker svc (lambda () (js-call1 %this failjs %this e))) (begin (exception-notify e) (display "This error has been notified because no error\n" (current-error-port)) (display "handler was provided for the post invocation.\n" (current-error-port))))) (post-request (lambda (x) (js-call1 %this success %this (scheme->js x))))))))) (js-undefined)) (define (spawn-promise) (with-access::JsGlobalObject %this (js-promise) (js-new %this js-promise (js-make-function %this (lambda (this resolve reject) (set! fail (lambda (obj) (js-call1 %this reject %this obj))) (thread-start! (instantiate::hopthread (name "spawn-promise-deprecated") (body (lambda () (with-handler (lambda (e) (js-call1 %this reject %this e)) (post-request (lambda (x) (js-call1 %this resolve %this (scheme->js x)))))))))) (js-function-arity 2 0) (js-function-info :name "executor" :len 2))))) (if asynchronous (if (js-procedure? success) (spawn-thread) (spawn-promise)) (post-request (if (js-procedure? success) (lambda (x) (js-call1 %this success %this (scheme->js x))) scheme->js))))) ;*---------------------------------------------------------------------*/ ;* js-create-service ... */ ;* ------------------------------------------------------------- */ * This function is called when the HopScript constructor * / ;* Service is directly invoked from user programs. The role */ ;* of this function is to build an internal hop-service that */ * merely calls the HopScript function passed as argument . * / ;* The complexity of this function comes when the optional */ ;* "args" arguments is an object, in which case, the function */ ;* builds a service with optional named arguments. */ ;*---------------------------------------------------------------------*/ (define (js-create-service %this::JsGlobalObject proc path loc register import worker::WorkerHopThread) (define (source::bstring proc) (if (js-function? proc) (or (js-function-path proc) (pwd)) (pwd))) (define (fix-args len) (map (lambda (i) (string->symbol (format "a~a" i))) (iota len))) (define (service-debug id::symbol proc) (if (>fx (bigloo-debug) 0) (lambda () (js-service/debug id loc proc)) proc)) (define (js-service-parse-request svc req) (with-access::http-request req (path abspath) (let ((args (service-parse-request svc req))) (js-obj->jsobject args %this)))) (when (and (eq? proc (js-undefined)) (not (eq? path (js-undefined)))) (set! path (js-tostring proc %this))) (let* ((path (or path (gen-service-url :public #t))) (hoppath (make-hop-url-name path)) (src (source proc))) (multiple-value-bind (id wid) (service-path->ids path) (letrec* ((svcp (lambda (this . vals) (with-access::JsService svcjs (svc) (with-access::hop-service svc (path) (js-make-hopframe %this this path vals))))) (svcjs (js-make-service %this svcp (symbol->string! id) register import (js-function-arity svcp) worker (instantiate::hop-service (ctx %this) (proc (if (js-procedure? proc) (lambda (this . args) (js-apply %this proc this args)) (lambda (this . args) (js-undefined)))) (handler (lambda (svc req) (js-worker-exec worker (symbol->string! id) #f (service-debug id (lambda () (service-invoke svc req (js-service-parse-request svc req))))))) (javascript "HopService( ~s, ~s )") (path hoppath) (id id) (wid wid) (args (fix-args (js-get proc (& "length") %this))) (resource (dirname src)) (source src))))) svcjs)))) ;*---------------------------------------------------------------------*/ ;* service-path->ids ... */ ;*---------------------------------------------------------------------*/ (define (service-path->ids path) (let* ((id (string->symbol path)) (wid (let ((j (string-index path #\/))) (if j (string->symbol (substring path 0 j)) id)))) (values id wid))) ;*---------------------------------------------------------------------*/ ;* service-pack-cgi-arguments ... */ ;*---------------------------------------------------------------------*/ (define-method (service-pack-cgi-arguments ctx::JsGlobalObject svc vals) (with-access::JsGlobalObject ctx (js-object worker) (with-access::hop-service svc (args id) (cond ((null? vals) '()) ((and (pair? args) (eq? (car args) #!key)) ;; old dsssl protocol (<=rc7) args) (else ;; hop-encoding:hop, new varargs protocol (let ((obj (js-new0 ctx js-object)) (vecks '())) first step (for-each (lambda (arg) (let ((k (js-string->name (car arg))) (val (js-string->jsstring (cdr arg)))) (cond ((not (js-in? obj k ctx)) (js-put! obj k val #f ctx)) (else (let ((old (js-get obj k ctx))) (if (pair? old) (set-cdr! (last-pair old) val) (begin (set! vecks (cons k vecks)) (js-put! obj k (list val) #f ctx)))))))) vals) second step , patch the multi - files arguments (for-each (lambda (k) (let ((old (js-get obj k ctx))) (js-put! obj k (js-vector->jsarray (list->vector (reverse! old)) ctx) #f ctx))) vecks) obj)))))) ;*---------------------------------------------------------------------*/ ;* js-make-service ... */ ;*---------------------------------------------------------------------*/ (define (js-make-service %this proc name register import arity worker svc) (define (default-service) (instantiate::hop-service (id (string->symbol name)) (wid (let ((i (string-index name #\?))) (string->symbol (if i (substring name 0 i) name)))) (args '()) (proc (lambda l l)) (javascript "") (path (hop-service-base)) (resource "/"))) (define (set-service-path! o p) (with-access::JsService o (svc) (when svc (when register (unregister-service! svc)) (with-access::hop-service svc (path id wid) (set! path p) (when (string=? (dirname p) (hop-service-base)) (let ((apath (substring path (+fx 1 (string-length (hop-service-base)))))) (multiple-value-bind (i w) (service-path->ids apath) (set! id i) (set! wid w))))) (when register (register-service! svc))))) ;; register only if there is an implementation (when svc (when (and register (>=fx (hop-default-port) 0)) (register-service! svc)) (unless import (with-access::WorkerHopThread worker (services) (set! services (cons svc services))))) (define (get-path o) (with-access::JsService o (svc) (when svc (with-access::hop-service svc (path) (js-string->jsstring path))))) (define (set-path o v) (set-service-path! o (js-tostring v %this)) v) (define (get-name o) (with-access::JsService o (svc) (when svc (with-access::hop-service svc (id) (js-string->jsstring (symbol->string! id)))))) (define (set-name o v) (set-service-path! o (make-file-name (hop-service-base) (js-tostring v %this))) v) (with-access::JsGlobalObject %this (js-service-prototype) (instantiateJsService (procedure proc) (info (js-function-info :name name :len arity)) (arity (js-function-arity proc)) (worker worker) (prototype (js-object-proto %this)) (__proto__ js-service-prototype) (alloc js-not-a-constructor-alloc) (svc (or svc (default-service))) (elements (vector (instantiate::JsValueDescriptor (name (& "length")) (value 0)) (instantiate::JsAccessorDescriptor (name (& "path")) (get (js-make-function %this get-path (js-function-arity get-path) (js-function-info :name "path" :len 1))) (set (js-make-function %this set-path (js-function-arity set-path) (js-function-info :name "path" :len 2))) (%get get-path) (%set set-path)) (instantiate::JsAccessorDescriptor (name (& "name")) (get (js-make-function %this get-name (js-function-arity get-name) (js-function-info :name "name" :len 1))) (set (js-make-function %this set-name (js-function-arity set-name) (js-function-info :name "name" :len 2))) (%get get-name) (%set set-name))))))) ;*---------------------------------------------------------------------*/ * service ? : : ... * / ;*---------------------------------------------------------------------*/ (define-method (service? obj::JsService) #t) ;*---------------------------------------------------------------------*/ * service->hop - service : : ... * / ;*---------------------------------------------------------------------*/ (define-method (service->hop-service obj::JsService) (with-access::JsService obj (svc) svc)) ;*---------------------------------------------------------------------*/ ;* js-tostring ::hop-service ... */ ;*---------------------------------------------------------------------*/ (define-method (js-tostring obj::hop-service %this) (with-access::hop-service obj (path) (format "[Service ~a]" path))) ;*---------------------------------------------------------------------*/ ;* *allow-urls* ... */ ;*---------------------------------------------------------------------*/ (define *allow-urls* '()) (define *url-redirect* #f) ;*---------------------------------------------------------------------*/ ;* add-service-allow-url! ... */ ;*---------------------------------------------------------------------*/ (define (add-service-allow-url! url) (set! *allow-urls* (cons (js-jsstring->string url) *allow-urls*))) ;*---------------------------------------------------------------------*/ ;* service-add-url! ... */ ;*---------------------------------------------------------------------*/ (define (service-add-url! svc url %this) (let ((u (js-jsstring->string url))) (cond ((not (isa? svc JsService)) (js-raise-type-error %this "Not a service ~s" (js-tostring svc %this))) ((not (member u *allow-urls*)) (js-raise-type-error %this "URL not allowed for redirection ~s (see Service.allowURL)" u)) ((string-prefix? (hop-service-base) u) (js-raise-type-error %this (format "Illegal URL prefix ~~s (must not be a prefix of ~s)" (hop-service-base)) u)) (else (with-access::JsService svc (svc) (with-access::hop-service svc (path) (let ((old (hashtable-get *url-redirect* u))) (when old (js-raise-type-error %this (format "URL ~s already bound to ~~s" u) old)) (hashtable-put! *url-redirect* u path)))))))) ;*---------------------------------------------------------------------*/ ;* service-remove-url! ... */ ;*---------------------------------------------------------------------*/ (define (service-remove-url! svc url %this) (let ((u (js-jsstring->string url))) (cond ((not (isa? svc JsService)) (js-raise-type-error %this "Not a service ~s" (js-tostring svc %this))) ((not (member u *allow-urls*)) (js-raise-type-error %this "URL not allowed for redirection ~s (see Service.allowURL)" u)) (else (with-access::JsService svc (svc) (with-access::hop-service svc (path) (let ((old (hashtable-get *url-redirect* u))) (cond ((not old) (js-raise-type-error %this "unbound URL ~s" u)) ((not (string=? path old)) (js-raise-type-error %this "URL ~s bound to another service" u)) (else (hashtable-remove! *url-redirect* u)))))))))) ;*---------------------------------------------------------------------*/ ;* service-get-urls ... */ ;*---------------------------------------------------------------------*/ (define (service-get-urls svc %this) (if (isa? svc JsService) (with-access::JsService svc (svc) (with-access::hop-service svc (path) (let ((res '())) (hashtable-for-each *url-redirect* (lambda (k v) (when (string=? v path) (set! res (cons (js-string->jsstring k) res))))) (js-vector->jsarray (list->vector res) %this)))) (js-raise-type-error %this "Not a service ~s" (js-tostring svc %this)))) ;*---------------------------------------------------------------------*/ ;* service-url-filter ... */ ;*---------------------------------------------------------------------*/ (define (service-url-filter req::http-request) (when (isa? req http-server-request) (with-access::http-server-request req (abspath path) (let ((alias (hashtable-get *url-redirect* abspath))) (when alias (set! abspath alias)))) req)) ;*---------------------------------------------------------------------*/ ;* &end! */ ;*---------------------------------------------------------------------*/ (&end!)
null
https://raw.githubusercontent.com/manuel-serrano/hop/2f687a900e00b527d6661d72e4a8522467718913/hopscript/service.scm
scheme
*=====================================================================*/ * ------------------------------------------------------------- */ * ------------------------------------------------------------- */ *=====================================================================*/ *---------------------------------------------------------------------*/ * The module */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * &begin! */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * object-serializer ::JsHopFrame ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * js-tostring ::JsHopFrame ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * xml-primitive-value ::JsHopFrame ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * xml-attribute-encode ::JsHopFrame ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * ------------------------------------------------------------- */ * See runtime/js_comp.scm in the Hop library for the definition */ * of the generic. */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * hop->javascript ::JsHopFrame ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * hop-register-value ::object ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * post-multipart->obj ::JsGlobalObject ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * js-init-service! ... */ *---------------------------------------------------------------------*/ local constant strings initialization service prototype *---------------------------------------------------------------------*/ * js-make-hopframe ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * hopframe->string ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * post ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * get-frame-id ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * post-options-deprecated ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * js-create-service ... */ * ------------------------------------------------------------- */ * Service is directly invoked from user programs. The role */ * of this function is to build an internal hop-service that */ * The complexity of this function comes when the optional */ * "args" arguments is an object, in which case, the function */ * builds a service with optional named arguments. */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * service-path->ids ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * service-pack-cgi-arguments ... */ *---------------------------------------------------------------------*/ old dsssl protocol (<=rc7) hop-encoding:hop, new varargs protocol *---------------------------------------------------------------------*/ * js-make-service ... */ *---------------------------------------------------------------------*/ register only if there is an implementation *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * js-tostring ::hop-service ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * *allow-urls* ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * add-service-allow-url! ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * service-add-url! ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * service-remove-url! ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * service-get-urls ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * service-url-filter ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * &end! */ *---------------------------------------------------------------------*/
* serrano / prgm / project / hop / hop / hopscript / service.scm * / * Author : * / * Creation : Thu Oct 17 08:19:20 2013 * / * Last change : Fri Nov 18 07:59:39 2022 ( serrano ) * / * Copyright : 2013 - 22 * / * HopScript service implementation * / (module __hopscript_service (library hop js2scheme) (include "types.sch" "stringliteral.sch") (import __hopscript_types __hopscript_arithmetic __hopscript_object __hopscript_error __hopscript_private __hopscript_public __hopscript_property __hopscript_function __hopscript_worker __hopscript_json __hopscript_lib __hopscript_array __hopscript_promise __hopscript_websocket) (export (js-init-service! ::JsGlobalObject) (js-make-hopframe ::JsGlobalObject ::obj ::obj ::obj) (js-create-service::JsService ::JsGlobalObject ::obj ::obj ::obj ::bool ::bool ::WorkerHopThread) (js-make-service::JsService ::JsGlobalObject ::procedure ::bstring ::bool ::bool ::int ::obj ::obj))) (define __js_strings (&begin!)) * object - serializer : : ... * / (register-class-serialization! JsService (lambda (o) (with-access::JsService o (svc) (if svc (with-access::hop-service svc (path resource) (vector path resource)) (vector #t #t)))) (lambda (o ctx) (let* ((path (vector-ref o 0)) (svcp (lambda (this . args) (js-make-hopframe ctx this path args))) (hopsvc (cond ((service-exists? path) (get-service path)) (else (instantiate::hop-service (id (string->symbol path)) (wid (let ((i (string-index path #\?))) (string->symbol (if i (substring path 0 i) path)))) (args '()) (proc (lambda l l)) (javascript "") (path path) (resource (vector-ref o 1))))))) (js-make-service ctx svcp (basename path) #f #f -1 (js-current-worker) hopsvc)))) (register-class-serialization! JsHopFrame (lambda (o) (with-access::JsHopFrame o (srv path args options header path) (vector (unless (isa? srv JsWebSocket) srv) path args options header))) (lambda (o ctx) (if (and (vector? o) (=fx (vector-length o) 5)) (with-access::JsGlobalObject ctx (js-hopframe-prototype) (instantiateJsHopFrame (__proto__ js-hopframe-prototype) (%this ctx) (srv (vector-ref o 0)) (path (vector-ref o 1)) (args (vector-ref o 2)) (options (vector-ref o 3)) (header (vector-ref o 4)))) (error "HopFrame" "wrong frame" o)))) * object - serializer : : ... * / (register-class-serialization! JsServer (lambda (o ctx) (if (isa? ctx JsGlobalObject) (with-access::JsServer o (obj) (with-access::server obj (host port ssl authorization version) (vector host port ssl (if (string? authorization) authorization #f) version (js-jsobject->plist o ctx)))) (error "obj->string ::JsServer" "Not a JavaScript context" ctx))) (lambda (o ctx) (cond ((not (isa? ctx JsGlobalObject)) (error "string->obj ::JsServer" "Not a JavaScript context" ctx)) ((and (vector? o) (=fx (vector-length o) 6)) (with-access::JsGlobalObject ctx (js-server-prototype) (let ((srv (instantiateJsServer (__proto__ js-server-prototype) (obj (instantiate::server (host (vector-ref o 0)) (port (vector-ref o 1)) (ssl (vector-ref o 2)) (ctx ctx) (authorization (vector-ref o 3)) (version (vector-ref o 4))))))) (let loop ((rest (vector-ref o 5))) (if (null? rest) srv (begin (js-put! srv (js-keyword->jsstring (car rest)) (js-obj->jsobject (cadr rest) ctx) #f ctx) (loop (cddr rest)))))))) (else (error "JsServer" "wrong server" o))))) (define-method (js-tostring obj::JsHopFrame %this) (hopframe->string obj %this)) (define-method (xml-primitive-value o::JsHopFrame ctx) (with-access::JsHopFrame o (path) (hopframe->string o ctx))) * js - donate : : ... * / (define-method (js-donate obj::JsService worker::WorkerHopThread %_this) (define (relative-path path) (substring path (string-length (hop-service-base)))) (with-access::WorkerHopThread worker (%this) (with-access::JsService obj (svc info arity) (with-access::hop-service svc (path) (let* ((path (relative-path path)) (proc (js-make-function %this (lambda (this) (js-undefined)) arity (js-function-info :name (vector-ref info 0) :len (vector-ref info 1)) :prototype #f :__proto__ #f :strict 'strict :minlen -1 :alloc js-not-a-constructor-alloc :constrsize 3 :method #f)) (nobj (js-create-service %this proc path #f #f #t worker))) (js-for-in obj (lambda (k %this) (js-put! nobj (js-donate k worker %_this) (js-donate (js-get obj k %_this) worker %_this) #f %this)) %this) nobj))))) * xml - unpack : : ... * / (define-method (xml-unpack o::JsService ctx) o) (define-method (xml-attribute-encode o::JsHopFrame) (with-access::JsHopFrame o (%this) (hopframe->string o %this))) * hop->javascript : : ... * / (define-method (hop->javascript o::JsService op compile isexpr ctx) (with-access::JsService o (svc) (compile svc op))) (define-method (hop->javascript o::JsHopFrame op compile isexpr ctx) (display "hop_url_encoded_to_obj('" op) (display (url-path-encode (obj->string o 'hop-client)) op) (display "')" op)) * hop->javascript : : ... * / (define-method (hop->javascript o::JsServer op compile isexpr ctx) (display "hop_url_encoded_to_obj('" op) (display (url-path-encode (obj->string o ctx)) op) (display "')" op)) (define-method (hop-register-value o::object register::procedure) #t) * json->obj : : ... * / (define-method (json->obj %this::JsObject ip::input-port) (js-json-parser ip #f #f #t %this)) (define-method (post-multipart->obj %this::JsGlobalObject val enc) (cond ((string=? enc "string") (js-string->jsstring val)) ((string=? enc "integer") (js-string->number val %this)) ((string=? enc "keyword") (js-string->jsstring val)) ((string=? enc "file") val) (else (string->obj val #f %this)))) * j2s - js - literal : : ... * / (define-method (j2s-js-literal o::JsService ctx) (with-access::JsService o (svc) (with-access::hop-service svc (path) (format "HopService( '~a', undefined )" path)))) (define (js-init-service! %this::JsGlobalObject) (with-access::JsGlobalObject %this (js-function js-service-pcache js-service-prototype js-hopframe-prototype) (let ((js-function-prototype (js-object-proto js-function))) (unless (vector? __js_strings) (set! __js_strings (&init!))) service pcache (set! js-service-pcache ((@ js-make-pcache-table __hopscript_property) 1 "service")) (with-access::JsGlobalObject %this (__proto__) (set! js-service-prototype (instantiateJsService (__proto__ js-function-prototype) (worker (class-nil WorkerHopThread)) (alloc js-not-a-constructor-alloc) (prototype (js-object-proto %this)) (info (js-function-info :name "" :len -1)) (procedure list) (svc #f)))) (js-bind! %this js-service-prototype (& "name") :value (js-ascii->jsstring "service") :writable #f :configurable #f :enumerable #f :hidden-class #t) (js-bind! %this js-service-prototype (& "resource") :value (js-make-function %this (lambda (this file) (js-string->jsstring (service-resource this (js-jsstring->string file)))) (js-function-arity 1 0) (js-function-info :name "resource" :len 1)) :writable #t :configurable #t :enumerable #f :hidden-class #t) (js-bind! %this js-service-prototype (& "unregister") :value (js-make-function %this (lambda (this) (when (isa? this JsService) (with-access::JsService this (svc) (unregister-service! svc))) (js-undefined)) (js-function-arity 0 0) (js-function-info :name "unregister" :len 0)) :writable #t :configurable #t :enumerable #f :hidden-class #t) (js-bind! %this js-service-prototype (& "timeout") :get (js-make-function %this (lambda (this) (with-access::JsService this (svc) (with-access::hop-service svc (timeout) timeout))) (js-function-arity 0 0) (js-function-info :name "timeout" :len 0)) :hidden-class #t) (js-bind! %this js-service-prototype (& "ttl") :get (js-make-function %this (lambda (this) (with-access::JsService this (svc) (with-access::hop-service svc (ttl) ttl))) (js-function-arity 0 0) (js-function-info :name "ttl.get" :len 0)) :set (js-make-function %this (lambda (this v) (with-access::JsService this (svc) (with-access::hop-service svc (ttl) (set! ttl (js-tointeger v %this))))) (js-function-arity 1 0) (js-function-info :name "ttl.set" :len 1)) :hidden-class #t) (js-bind! %this js-service-prototype (& "addURL") :value (js-make-function %this (lambda (this url) (service-add-url! this url %this)) (js-function-arity 1 0) (js-function-info :name "addURL" :len 1)) :hidden-class #t) (js-bind! %this js-service-prototype (& "removeURL") :value (js-make-function %this (lambda (this url) (service-remove-url! this url %this)) (js-function-arity 1 0) (js-function-info :name "removeURL" :len 1)) :hidden-class #t) (js-bind! %this js-service-prototype (& "getURLs") :value (js-make-function %this (lambda (this) (service-get-urls this %this)) (js-function-arity 0 0) (js-function-info :name "getURLs" :len 0)) :hidden-class #t) HopFrame prototype and constructor (set! js-hopframe-prototype (instantiateJsObject (__proto__ (js-object-proto %this)) (elements ($create-vector 8)))) (js-bind! %this js-hopframe-prototype (& "post") :value (js-make-function %this (lambda (this::JsHopFrame success fail-or-opt) (with-access::JsHopFrame this (args) (post this success fail-or-opt %this #t))) (js-function-arity 2 0) (js-function-info :name "post" :len 2)) :hidden-class #t) (js-bind! %this js-hopframe-prototype (& "postSync") :value (js-make-function %this (lambda (this::JsHopFrame opt) (with-access::JsHopFrame this (args) (post this #f opt %this #f))) (js-function-arity 1 0) (js-function-info :name "postSync" :len 2)) :hidden-class #t) (js-bind! %this js-hopframe-prototype (& "call") :value (js-make-function %this (lambda (this::JsHopFrame req opt) (with-access::JsHopFrame this (path args) (let ((svc (get-service path))) (with-access::hop-service svc (proc) (apply proc req args))))) (js-function-arity 2 0) (js-function-info :name "call" :len 2)) :hidden-class #t) (js-bind! %this js-hopframe-prototype (& "toString") :value (js-make-function %this (lambda (this::JsHopFrame) (js-string->jsstring (hopframe->string this %this))) (js-function-arity 0 0) (js-function-info :name "toString" :len 0)) :hidden-class #t) (js-bind! %this js-hopframe-prototype (& "inspect") :value (js-make-function %this (lambda (this::JsHopFrame) (js-string->jsstring (hopframe->string this %this))) (js-function-arity 0 0) (js-function-info :name "inspect" :len 0)) :hidden-class #t) (js-bind! %this js-hopframe-prototype (& "getHeader") :value (js-make-function %this (lambda (this::JsHopFrame) (with-access::JsHopFrame this (header) header)) (js-function-arity 0 0) (js-function-info :name "getHeader" :len 0)) :hidden-class #t) (js-bind! %this js-hopframe-prototype (& "setHeader") :value (js-make-function %this (lambda (this::JsHopFrame hd) (with-access::JsHopFrame this (header) (set! header hd) this)) (js-function-arity 1 0) (js-function-info :name "setHeader" :len 1)) :hidden-class #t) (js-bind! %this js-hopframe-prototype (& "getOptions") :value (js-make-function %this (lambda (this::JsHopFrame opts) opts) (js-function-arity 1 0) (js-function-info :name "getOptions" :len 1)) :hidden-class #t) (js-bind! %this js-hopframe-prototype (& "setOptions") :value (js-make-function %this (lambda (this::JsHopFrame opts) (with-access::JsHopFrame this (options) (set! options opts) this)) (js-function-arity 1 0) (js-function-info :name "setOptions" :len 1)) :hidden-class #t) (define (%js-service this proc path) (js-create-service %this proc (unless (eq? path (js-undefined)) (js-tostring path %this)) #f #t #f (js-current-worker))) (define (%js-hopframe this path args) (js-make-hopframe %this this path args)) (letrec ((js-service (js-make-function %this %js-service (js-function-arity %js-service) (js-function-info :name "Service" :len 2) :__proto__ js-function-prototype :prototype js-service-prototype :size 5 :alloc js-no-alloc)) (js-hopframe (js-make-function %this %js-hopframe (js-function-arity %js-hopframe) (js-function-info :name "HopFrame" :len 1) :__proto__ js-function-prototype :prototype js-hopframe-prototype :alloc js-no-alloc))) (js-bind! %this %this (& "Service") :configurable #f :enumerable #f :value js-service :hidden-class #t) (js-bind! %this %this (& "HopFrame") :configurable #f :enumerable #f :value js-hopframe :hidden-class #t) (js-bind! %this js-service (& "exists") :configurable #f :enumerable #f :value (js-make-function %this (lambda (this svc) (service-exists? (js-tostring svc %this))) (js-function-arity 1 0) (js-function-info :name "exists" :len 1)) :hidden-class #t) (js-bind! %this js-service (& "getService") :configurable #f :enumerable #f :value (js-make-function %this (lambda (this svc) (let* ((name (js-tostring svc %this)) (svc (get-service-from-name name))) (js-make-service %this (lambda (this . args) (with-access::hop-service svc (path) (js-make-hopframe %this this path args))) name #f #f -1 (js-current-worker) svc))) (js-function-arity 1 0) (js-function-info :name "getService" :len 1)) :hidden-class #t) (js-bind! %this js-service (& "getServiceFromPath") :configurable #f :enumerable #f :value (js-make-function %this (lambda (this svc) (let* ((name (js-tostring svc %this)) (svc (get-service name))) (js-make-service %this (lambda (this . args) (with-access::hop-service svc (path) (js-make-hopframe %this this path args))) name #f #f -1 (js-current-worker) svc))) (js-function-arity 1 0) (js-function-info :name "getService" :len 1)) :hidden-class #t) (js-bind! %this js-service (& "allowURL") :configurable #f :enumerable #f :value (js-make-function %this (lambda (this url) (cond ((not (hop-filters-open?)) (js-raise-type-error %this "allowURL must called from within the hoprc.js file" url)) ((not (memq service-url-filter (hop-filters))) (set! *url-redirect* (create-hashtable)) (hop-filter-add! service-url-filter) (add-service-allow-url! url)) (else (add-service-allow-url! url)))) (js-function-arity 1 0) (js-function-info :name "allowURL" :len 1)) :hidden-class #t)) (js-undefined)))) (define (js-make-hopframe %this::JsGlobalObject srv path args) (with-access::JsGlobalObject %this (js-hopframe-prototype js-object js-server) (instantiateJsHopFrame (__proto__ js-hopframe-prototype) (%this %this) (srv srv) (path path) (args args)))) (define (hopframe->string::bstring frame::JsHopFrame %this) (with-access::JsHopFrame frame (srv path args) (let ((sans-srv (cond ((not (pair? args)) path) (else (hop-apply-url path args %this))))) (if (isa? srv JsServer) (with-access::JsServer srv (obj) (with-access::server obj (ssl host port authorization) (let ((scheme (if ssl "https" "http"))) (if authorization (format "~a://~a:~a:~a~a" scheme authorization host port sans-srv) (format "~a://~a:~a~a" scheme host port sans-srv))))) sans-srv)))) (define (post this::JsHopFrame success fail-or-opt %this async) (define (multipart-form-arg val) (cond ((string? val) `("string" ,val "hop-encoding: string")) ((js-jsstring? val) `("string" ,(js-jsstring->string val) "hop-encoding: string")) ((integer? val) `("integer" ,val "hop-encoding: integer")) ((keyword? val) `("keyword" ,(keyword->string val) "hop-encoding: keyword")) (else `("hop" ,(obj->string val %this) "hop-encoding: hop")))) (define (scheme->js val) (js-obj->jsobject val %this)) (define (js-get-string opt key) (let ((v (js-get opt key %this))) (unless (eq? v (js-undefined)) (js-tostring v %this)))) (define (post-request-thread name %this callback fail scheme host port auth) (with-access::JsHopFrame this (path args header options) (let ((user (js-get-string options (& "user"))) (password (js-get-string options (& "password"))) (header (when header (js-jsobject->alist header %this))) (args (map multipart-form-arg args)) (receiver (lambda (ctx thunk) (with-access::JsGlobalObject ctx (worker) (js-worker-exec worker path #t thunk))))) (thread-start! (instantiate::hopthread (name name) (body (lambda () (with-handler (lambda (e) (exception-notify e) (with-access::JsGlobalObject %this (worker) (js-worker-exec worker path #t (lambda () (fail e))))) (with-hop-remote path callback fail :scheme scheme :host host :port port :user user :password password :authorization auth :header header :ctx %this :receiver receiver :json-parser json-parser :x-javascript-parser x-javascript-parser :connection-timeout (hop-connection-timeout) :args args)))))) (js-undefined)))) (define (post-server-promise this %this host port auth scheme) (with-access::JsGlobalObject %this (js-promise) (letrec* ((callback (lambda (x) (js-promise-async p (lambda () (js-promise-resolve p x))))) (fail (lambda (x) (js-promise-async p (lambda () (js-promise-reject p x))))) (p (js-new %this js-promise (js-make-function %this (lambda (_ resolve reject) (post-request-thread "post-server-promise" %this callback fail scheme host port auth)) (js-function-arity 2 0) (js-function-info :name "executor" :len 2))))) p))) (define (post-server-async this success failure %this host port auth scheme) (with-access::JsHopFrame this (path) (with-access::JsGlobalObject %this (worker) (let ((callback (when (js-procedure? success) (lambda (x) (js-call1 %this success %this x)))) (fail (if (js-procedure? failure) (lambda (obj) (js-call1 %this failure %this obj)) exception-notify))) (post-request-thread "post-async" %this callback fail scheme host port auth))))) (define (post-server-sync this %this host port auth scheme) (with-access::JsHopFrame this (path args header options) (let ((receiver (lambda (ctx thunk) (with-access::JsGlobalObject ctx (worker) (js-worker-exec worker path #t thunk))))) (with-hop-remote path (lambda (x) x) #f :scheme scheme :host host :port port :user (js-get-string options (& "user")) :password (js-get-string options (& "password")) :authorization auth :header (when header (js-jsobject->alist header %this)) :ctx %this :receiver receiver :json-parser json-parser :x-javascript-parser x-javascript-parser :args (map multipart-form-arg args))))) (define (post-server this success failure %this async host port auth scheme) (cond ((not async) (post-server-sync this %this host port auth scheme)) ((or (js-procedure? success) (js-procedure? failure)) (post-server-async this success failure %this host port auth scheme)) (else (post-server-promise this %this host port auth scheme)))) (define (post-websocket-promise this::JsHopFrame srv::JsWebSocket) (with-access::JsWebSocket srv (recvqueue) (with-access::JsGlobalObject %this (js-promise) (let ((frameid (get-frame-id))) (letrec ((p (js-new %this js-promise (js-make-function %this (lambda (_ resolve reject) (js-websocket-post srv this frameid)) (js-function-arity 2 0) (js-function-info :name "executor" :len 2))))) (cell-set! recvqueue (cons (cons frameid p) (cell-ref recvqueue))) p))))) (define (post-websocket-async this::JsHopFrame srv::JsWebSocket success failure) (with-access::JsHopFrame this (path) (let ((callback (when (js-procedure? success) (lambda (x) (js-worker-push-thunk! (js-current-worker) path (lambda () (js-call1 %this success %this x)))))) (fail (when (js-procedure? failure) (lambda (obj) (js-worker-push-thunk! (js-current-worker) path (lambda () (js-call1 %this failure %this obj))))))) (with-access::JsWebSocket srv (ws recvqueue) (with-access::websocket ws (%mutex) (let ((frameid (get-frame-id))) (js-websocket-post srv this frameid) (cell-set! recvqueue (cons (cons frameid (cons callback fail)) (cell-ref recvqueue))))))))) (define (post-websocket-sync this::JsHopFrame srv::JsWebSocket) (with-access::JsHopFrame this (path) (with-access::JsWebSocket srv (ws recvqueue) (with-access::websocket ws (%mutex %socket) (if (socket? %socket) (let* ((frameid (get-frame-id)) (cv (make-condition-variable)) (cell (cons cv %mutex))) (js-websocket-post srv this frameid) (cell-set! recvqueue (cons (cons frameid cell) (cell-ref recvqueue))) (condition-variable-wait! cv %mutex) (or (car cell) (raise (cdr cell)))) (js-raise-type-error %this "not connected ~s" srv)))))) (define (post-websocket this::JsHopFrame success failure %this async srv::JsWebSocket) (with-access::JsWebSocket srv (ws) (with-access::websocket ws (%mutex) (synchronize %mutex (cond ((not async) (post-websocket-sync this srv)) ((or (js-procedure? success) (js-procedure? failure)) (post-websocket-async this srv success failure)) (else (post-websocket-promise this srv))))))) (with-access::JsHopFrame this (srv) (cond ((isa? srv JsServer) (with-access::JsServer srv (obj) (with-access::server obj (host port authorization ssl) (post-server this success fail-or-opt %this async host port authorization (if ssl 'https 'http))))) ((isa? srv JsWebSocket) (post-websocket this success fail-or-opt %this async srv)) ((or (js-procedure? fail-or-opt) (not (js-object? fail-or-opt))) (post-server this success fail-or-opt %this async "localhost" (hop-default-port) #f (hop-default-scheme))) (else (with-access::JsHopFrame this (path args) (post-options-deprecated path (map multipart-form-arg args) success fail-or-opt %this async)))))) (define (get-frame-id) (let ((v frame-id)) (set! frame-id (+fx 1 frame-id)) v)) (define frame-id 0) (define (post-options-deprecated svc::bstring args success opt %this async) (let ((host "localhost") (port (hop-default-port)) (user #f) (password #f) (authorization #f) (fail #f) (failjs #f) (asynchronous async) (header #f) (scheme 'http) (worker (js-current-worker))) (cond ((js-procedure? opt) (set! fail (if asynchronous (lambda (obj) (js-worker-push-thunk! worker svc (lambda () (js-call1 %this opt %this obj)))) (lambda (obj) (js-call1 %this opt %this obj))))) ((not (eq? opt (js-undefined))) (let* ((v (js-get opt (& "server") %this)) (o (if (eq? v (js-undefined)) opt v)) (a (js-get o (& "authorization") %this)) (h (js-get o (& "host") %this)) (p (js-get o (& "port") %this)) (u (js-get opt (& "user") %this)) (w (js-get opt (& "password") %this)) (f (js-get opt (& "fail") %this)) (y (js-get opt (& "asynchronous") %this)) (s (js-get opt (& "scheme") %this)) (c (js-get opt (& "ssl") %this)) (r (js-get opt (& "header") %this))) (unless (eq? h (js-undefined)) (set! host (js-tostring h %this))) (unless (eq? p (js-undefined)) (set! port (js-tointeger p %this))) (unless (eq? u (js-undefined)) (set! user (js-tostring u %this))) (unless (eq? w (js-undefined)) (set! password (js-tostring w %this))) (unless (eq? a (js-undefined)) (set! authorization (js-tostring a %this))) (unless (js-totest y) (when (js-in? opt (& "asynchronous") %this) (set! asynchronous #f))) (when (js-totest c) (set! scheme 'https)) (unless (eq? s (js-undefined)) (set! scheme (string->symbol (js-tostring s %this)))) (when (js-procedure? f) (set! failjs f) (set! fail (lambda (obj) (if asynchronous (js-worker-push-thunk! worker svc (lambda () (js-call1 %this f %this obj))) (js-call1 %this f %this obj))))) (when (js-object? r) (set! header (js-jsobject->alist r %this)))))) (define (scheme->js val) (js-obj->jsobject val %this)) (define (post-request callback) (let ((receiver (lambda (ctx thunk) (with-access::JsGlobalObject ctx (worker) (js-worker-exec worker svc #t thunk))))) (with-hop-remote svc callback fail :scheme scheme :host host :port port :user user :password password :authorization authorization :header header :ctx %this :receiver receiver :json-parser json-parser :x-javascript-parser x-javascript-parser :args args))) (define (spawn-thread) (thread-start! (instantiate::hopthread (name "spawn-thread-deprecated") (body (lambda () (with-handler (lambda (e) (exception-notify e) (if failjs (js-worker-push-thunk! worker svc (lambda () (js-call1 %this failjs %this e))) (begin (exception-notify e) (display "This error has been notified because no error\n" (current-error-port)) (display "handler was provided for the post invocation.\n" (current-error-port))))) (post-request (lambda (x) (js-call1 %this success %this (scheme->js x))))))))) (js-undefined)) (define (spawn-promise) (with-access::JsGlobalObject %this (js-promise) (js-new %this js-promise (js-make-function %this (lambda (this resolve reject) (set! fail (lambda (obj) (js-call1 %this reject %this obj))) (thread-start! (instantiate::hopthread (name "spawn-promise-deprecated") (body (lambda () (with-handler (lambda (e) (js-call1 %this reject %this e)) (post-request (lambda (x) (js-call1 %this resolve %this (scheme->js x)))))))))) (js-function-arity 2 0) (js-function-info :name "executor" :len 2))))) (if asynchronous (if (js-procedure? success) (spawn-thread) (spawn-promise)) (post-request (if (js-procedure? success) (lambda (x) (js-call1 %this success %this (scheme->js x))) scheme->js))))) * This function is called when the HopScript constructor * / * merely calls the HopScript function passed as argument . * / (define (js-create-service %this::JsGlobalObject proc path loc register import worker::WorkerHopThread) (define (source::bstring proc) (if (js-function? proc) (or (js-function-path proc) (pwd)) (pwd))) (define (fix-args len) (map (lambda (i) (string->symbol (format "a~a" i))) (iota len))) (define (service-debug id::symbol proc) (if (>fx (bigloo-debug) 0) (lambda () (js-service/debug id loc proc)) proc)) (define (js-service-parse-request svc req) (with-access::http-request req (path abspath) (let ((args (service-parse-request svc req))) (js-obj->jsobject args %this)))) (when (and (eq? proc (js-undefined)) (not (eq? path (js-undefined)))) (set! path (js-tostring proc %this))) (let* ((path (or path (gen-service-url :public #t))) (hoppath (make-hop-url-name path)) (src (source proc))) (multiple-value-bind (id wid) (service-path->ids path) (letrec* ((svcp (lambda (this . vals) (with-access::JsService svcjs (svc) (with-access::hop-service svc (path) (js-make-hopframe %this this path vals))))) (svcjs (js-make-service %this svcp (symbol->string! id) register import (js-function-arity svcp) worker (instantiate::hop-service (ctx %this) (proc (if (js-procedure? proc) (lambda (this . args) (js-apply %this proc this args)) (lambda (this . args) (js-undefined)))) (handler (lambda (svc req) (js-worker-exec worker (symbol->string! id) #f (service-debug id (lambda () (service-invoke svc req (js-service-parse-request svc req))))))) (javascript "HopService( ~s, ~s )") (path hoppath) (id id) (wid wid) (args (fix-args (js-get proc (& "length") %this))) (resource (dirname src)) (source src))))) svcjs)))) (define (service-path->ids path) (let* ((id (string->symbol path)) (wid (let ((j (string-index path #\/))) (if j (string->symbol (substring path 0 j)) id)))) (values id wid))) (define-method (service-pack-cgi-arguments ctx::JsGlobalObject svc vals) (with-access::JsGlobalObject ctx (js-object worker) (with-access::hop-service svc (args id) (cond ((null? vals) '()) ((and (pair? args) (eq? (car args) #!key)) args) (else (let ((obj (js-new0 ctx js-object)) (vecks '())) first step (for-each (lambda (arg) (let ((k (js-string->name (car arg))) (val (js-string->jsstring (cdr arg)))) (cond ((not (js-in? obj k ctx)) (js-put! obj k val #f ctx)) (else (let ((old (js-get obj k ctx))) (if (pair? old) (set-cdr! (last-pair old) val) (begin (set! vecks (cons k vecks)) (js-put! obj k (list val) #f ctx)))))))) vals) second step , patch the multi - files arguments (for-each (lambda (k) (let ((old (js-get obj k ctx))) (js-put! obj k (js-vector->jsarray (list->vector (reverse! old)) ctx) #f ctx))) vecks) obj)))))) (define (js-make-service %this proc name register import arity worker svc) (define (default-service) (instantiate::hop-service (id (string->symbol name)) (wid (let ((i (string-index name #\?))) (string->symbol (if i (substring name 0 i) name)))) (args '()) (proc (lambda l l)) (javascript "") (path (hop-service-base)) (resource "/"))) (define (set-service-path! o p) (with-access::JsService o (svc) (when svc (when register (unregister-service! svc)) (with-access::hop-service svc (path id wid) (set! path p) (when (string=? (dirname p) (hop-service-base)) (let ((apath (substring path (+fx 1 (string-length (hop-service-base)))))) (multiple-value-bind (i w) (service-path->ids apath) (set! id i) (set! wid w))))) (when register (register-service! svc))))) (when svc (when (and register (>=fx (hop-default-port) 0)) (register-service! svc)) (unless import (with-access::WorkerHopThread worker (services) (set! services (cons svc services))))) (define (get-path o) (with-access::JsService o (svc) (when svc (with-access::hop-service svc (path) (js-string->jsstring path))))) (define (set-path o v) (set-service-path! o (js-tostring v %this)) v) (define (get-name o) (with-access::JsService o (svc) (when svc (with-access::hop-service svc (id) (js-string->jsstring (symbol->string! id)))))) (define (set-name o v) (set-service-path! o (make-file-name (hop-service-base) (js-tostring v %this))) v) (with-access::JsGlobalObject %this (js-service-prototype) (instantiateJsService (procedure proc) (info (js-function-info :name name :len arity)) (arity (js-function-arity proc)) (worker worker) (prototype (js-object-proto %this)) (__proto__ js-service-prototype) (alloc js-not-a-constructor-alloc) (svc (or svc (default-service))) (elements (vector (instantiate::JsValueDescriptor (name (& "length")) (value 0)) (instantiate::JsAccessorDescriptor (name (& "path")) (get (js-make-function %this get-path (js-function-arity get-path) (js-function-info :name "path" :len 1))) (set (js-make-function %this set-path (js-function-arity set-path) (js-function-info :name "path" :len 2))) (%get get-path) (%set set-path)) (instantiate::JsAccessorDescriptor (name (& "name")) (get (js-make-function %this get-name (js-function-arity get-name) (js-function-info :name "name" :len 1))) (set (js-make-function %this set-name (js-function-arity set-name) (js-function-info :name "name" :len 2))) (%get get-name) (%set set-name))))))) * service ? : : ... * / (define-method (service? obj::JsService) #t) * service->hop - service : : ... * / (define-method (service->hop-service obj::JsService) (with-access::JsService obj (svc) svc)) (define-method (js-tostring obj::hop-service %this) (with-access::hop-service obj (path) (format "[Service ~a]" path))) (define *allow-urls* '()) (define *url-redirect* #f) (define (add-service-allow-url! url) (set! *allow-urls* (cons (js-jsstring->string url) *allow-urls*))) (define (service-add-url! svc url %this) (let ((u (js-jsstring->string url))) (cond ((not (isa? svc JsService)) (js-raise-type-error %this "Not a service ~s" (js-tostring svc %this))) ((not (member u *allow-urls*)) (js-raise-type-error %this "URL not allowed for redirection ~s (see Service.allowURL)" u)) ((string-prefix? (hop-service-base) u) (js-raise-type-error %this (format "Illegal URL prefix ~~s (must not be a prefix of ~s)" (hop-service-base)) u)) (else (with-access::JsService svc (svc) (with-access::hop-service svc (path) (let ((old (hashtable-get *url-redirect* u))) (when old (js-raise-type-error %this (format "URL ~s already bound to ~~s" u) old)) (hashtable-put! *url-redirect* u path)))))))) (define (service-remove-url! svc url %this) (let ((u (js-jsstring->string url))) (cond ((not (isa? svc JsService)) (js-raise-type-error %this "Not a service ~s" (js-tostring svc %this))) ((not (member u *allow-urls*)) (js-raise-type-error %this "URL not allowed for redirection ~s (see Service.allowURL)" u)) (else (with-access::JsService svc (svc) (with-access::hop-service svc (path) (let ((old (hashtable-get *url-redirect* u))) (cond ((not old) (js-raise-type-error %this "unbound URL ~s" u)) ((not (string=? path old)) (js-raise-type-error %this "URL ~s bound to another service" u)) (else (hashtable-remove! *url-redirect* u)))))))))) (define (service-get-urls svc %this) (if (isa? svc JsService) (with-access::JsService svc (svc) (with-access::hop-service svc (path) (let ((res '())) (hashtable-for-each *url-redirect* (lambda (k v) (when (string=? v path) (set! res (cons (js-string->jsstring k) res))))) (js-vector->jsarray (list->vector res) %this)))) (js-raise-type-error %this "Not a service ~s" (js-tostring svc %this)))) (define (service-url-filter req::http-request) (when (isa? req http-server-request) (with-access::http-server-request req (abspath path) (let ((alias (hashtable-get *url-redirect* abspath))) (when alias (set! abspath alias)))) req)) (&end!)
901ab2a3b5e3b5f24f3b106dc1a3ff15c6d75eab84ad7b266e134c9a14ac2a87
xapi-project/xen-api
cohttp_unbuffered_io.ml
* Copyright ( c ) 2012 Citrix Inc * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * * Copyright (c) 2012 Citrix Inc * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * *) type 'a t = 'a Lwt.t let iter fn x = Lwt_list.iter_s fn x let return = Lwt.return let ( >>= ) = Lwt.bind let ( >> ) m n = m >>= fun _ -> n (** Use as few really_{read,write} calls as we can (for efficiency) without explicitly buffering the stream beyond the HTTP headers. This will allow us to consume the headers and then pass the file descriptor safely to another process *) type ic = { mutable header_buffer: string option (** buffered headers *) ; mutable header_buffer_idx: int (** next char within the buffered headers *) ; c: Data_channel.t } let make_input c = let header_buffer = None in let header_buffer_idx = 0 in {header_buffer; header_buffer_idx; c} type oc = Data_channel.t type conn = Data_channel.t let really_read_into c buf ofs len = let tmp = Cstruct.create len in c.Data_channel.really_read tmp >>= fun () -> Cstruct.blit_to_bytes tmp 0 buf ofs len ; return () let read_http_headers c = let buf = Buffer.create 128 in (* We can safely read everything up to this marker: *) let end_of_headers = "\r\n\r\n" in let tmp = Bytes.make (String.length end_of_headers) '\000' in let module Scanner = struct type t = {marker: string; mutable i: int} let make x = {marker= x; i= 0} let input x c = if c = String.get x.marker x.i then x.i <- x.i + 1 else x.i <- 0 let remaining x = String.length x.marker - x.i let matched x = x.i = String.length x.marker (* let to_string x = Printf.sprintf "%d" x.i *) end in let marker = Scanner.make end_of_headers in let rec loop () = if not (Scanner.matched marker) then ( We may be part way through reading the end of header marker , so be pessimistic and only read enough bytes to read until the end of the marker . be pessimistic and only read enough bytes to read until the end of the marker. *) let safe_to_read = Scanner.remaining marker in really_read_into c tmp 0 safe_to_read >>= fun () -> for j = 0 to safe_to_read - 1 do Scanner.input marker (Bytes.get tmp j) ; Buffer.add_char buf (Bytes.get tmp j) done ; loop () ) else return () in loop () >>= fun () -> return (Buffer.contents buf) (* We assume read_line is only used to read the HTTP header *) let rec read_line ic = match (ic.header_buffer, ic.header_buffer_idx) with | None, _ -> read_http_headers ic.c >>= fun str -> ic.header_buffer <- Some str ; read_line ic | Some buf, i when i < String.length buf -> ( match Astring.String.find_sub ~start:i ~sub:"\r\n" buf with | Some eol -> let line = String.sub buf i (eol - i) in ic.header_buffer_idx <- eol + 2 ; return (Some line) | None -> return (Some "") ) | Some _, _ -> return (Some "") let read_into_exactly ic buf ofs len = really_read_into ic.c buf ofs len >>= fun () -> return true let read_exactly ic len = let buf = Bytes.create len in read_into_exactly ic buf 0 len >>= function | true -> return (Some buf) | false -> return None let read ic n = let buf = Bytes.make n '\000' in really_read_into ic.c buf 0 n >>= fun () -> return (Bytes.unsafe_to_string buf) let write oc x = let buf = Cstruct.create (String.length x) in Cstruct.blit_from_string x 0 buf 0 (String.length x) ; oc.Data_channel.really_write buf let flush _oc = return ()
null
https://raw.githubusercontent.com/xapi-project/xen-api/997a7d8d4de560f9b4da9f45ac6d64088d1e58be/ocaml/xen-api-client/lwt/cohttp_unbuffered_io.ml
ocaml
* Use as few really_{read,write} calls as we can (for efficiency) without explicitly buffering the stream beyond the HTTP headers. This will allow us to consume the headers and then pass the file descriptor safely to another process * buffered headers * next char within the buffered headers We can safely read everything up to this marker: let to_string x = Printf.sprintf "%d" x.i We assume read_line is only used to read the HTTP header
* Copyright ( c ) 2012 Citrix Inc * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * * Copyright (c) 2012 Citrix Inc * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * *) type 'a t = 'a Lwt.t let iter fn x = Lwt_list.iter_s fn x let return = Lwt.return let ( >>= ) = Lwt.bind let ( >> ) m n = m >>= fun _ -> n type ic = { ; c: Data_channel.t } let make_input c = let header_buffer = None in let header_buffer_idx = 0 in {header_buffer; header_buffer_idx; c} type oc = Data_channel.t type conn = Data_channel.t let really_read_into c buf ofs len = let tmp = Cstruct.create len in c.Data_channel.really_read tmp >>= fun () -> Cstruct.blit_to_bytes tmp 0 buf ofs len ; return () let read_http_headers c = let buf = Buffer.create 128 in let end_of_headers = "\r\n\r\n" in let tmp = Bytes.make (String.length end_of_headers) '\000' in let module Scanner = struct type t = {marker: string; mutable i: int} let make x = {marker= x; i= 0} let input x c = if c = String.get x.marker x.i then x.i <- x.i + 1 else x.i <- 0 let remaining x = String.length x.marker - x.i let matched x = x.i = String.length x.marker end in let marker = Scanner.make end_of_headers in let rec loop () = if not (Scanner.matched marker) then ( We may be part way through reading the end of header marker , so be pessimistic and only read enough bytes to read until the end of the marker . be pessimistic and only read enough bytes to read until the end of the marker. *) let safe_to_read = Scanner.remaining marker in really_read_into c tmp 0 safe_to_read >>= fun () -> for j = 0 to safe_to_read - 1 do Scanner.input marker (Bytes.get tmp j) ; Buffer.add_char buf (Bytes.get tmp j) done ; loop () ) else return () in loop () >>= fun () -> return (Buffer.contents buf) let rec read_line ic = match (ic.header_buffer, ic.header_buffer_idx) with | None, _ -> read_http_headers ic.c >>= fun str -> ic.header_buffer <- Some str ; read_line ic | Some buf, i when i < String.length buf -> ( match Astring.String.find_sub ~start:i ~sub:"\r\n" buf with | Some eol -> let line = String.sub buf i (eol - i) in ic.header_buffer_idx <- eol + 2 ; return (Some line) | None -> return (Some "") ) | Some _, _ -> return (Some "") let read_into_exactly ic buf ofs len = really_read_into ic.c buf ofs len >>= fun () -> return true let read_exactly ic len = let buf = Bytes.create len in read_into_exactly ic buf 0 len >>= function | true -> return (Some buf) | false -> return None let read ic n = let buf = Bytes.make n '\000' in really_read_into ic.c buf 0 n >>= fun () -> return (Bytes.unsafe_to_string buf) let write oc x = let buf = Cstruct.create (String.length x) in Cstruct.blit_from_string x 0 buf 0 (String.length x) ; oc.Data_channel.really_write buf let flush _oc = return ()
10aa39c52d1c2c1ac0472475d058d7e53fe99668829a6c8a5c4902112b6ff990
thephoeron/quipper-language
QFT.hs
This file is part of Quipper . Copyright ( C ) 2011 - 2014 . Please see the -- file COPYRIGHT for a list of authors, copyright holders, licensing, -- and other details. All rights reserved. -- -- ====================================================================== | This module implements the Quantum Fourier Transform . module QuipperLib.QFT ( qft_little_endian, qft_big_endian, qft_rev, qft_int ) where import Quipper import QuipperLib.Arith import Libraries.Auxiliary (mmap) -- ---------------------------------------------------------------------- -- * Low-level implementation -- | Like 'qft_rev', but without the comments and labels. -- -- Apply the Quantum Fourier Transform to a list of /n/ qubits. -- The input is little-endian and the output is big-endian. -- Unlike ' qft_little_endian ' and ' qft_big_endian ' , this function can be used in imperative style , i.e. , it modifies its arguments -- place\". qft_internal :: [Qubit] -> Circ [Qubit] qft_internal [] = return [] qft_internal [x] = do hadamard x return [x] qft_internal (x:xs) = do xs' <- qft_internal xs xs'' <- rotations x xs' (length xs') x' <- hadamard x return (x':xs'') where -- Auxiliary function used by 'qft'. rotations :: Qubit -> [Qubit] -> Int -> Circ [Qubit] rotations _ [] _ = return [] rotations c (q:qs) n = do qs' <- rotations c qs n q' <- rGate ((n + 1) - length qs) q `controlled` c return (q':qs') -- ---------------------------------------------------------------------- -- * Wrappers -- | Apply the Quantum Fourier Transform to a list of /n/ qubits. -- Both the input and output qubit lists are little-endian, i.e., the -- leftmost qubit (head of the list) is the least significant one. -- -- Note that this function cannot be used in imperative style, i.e., it does not update its arguments place\ " . The output qubits -- are in different physical locations than the input ones. qft_little_endian :: [Qubit] -> Circ [Qubit] qft_little_endian qs = do comment_with_label "ENTER: qft_little_endian" qs "qs" qs' <- qft_internal qs let qs = reverse qs' comment_with_label "EXIT: qft_little_endian" qs "qs" return qs -- | Apply the Quantum Fourier Transform to a list of /n/ qubits. -- Both the input and output qubit lists are big-endian, i.e., the -- leftmost qubit (head of the list) is the most significant one. -- -- Note that this function cannot be used in imperative style, i.e., it does not update its arguments place\ " . The output qubits -- are in different physical locations than the input ones. qft_big_endian :: [Qubit] -> Circ [Qubit] qft_big_endian qs = do comment_with_label "ENTER: qft_big_endian" qs "qs" qs <- qft_internal (reverse qs) comment_with_label "EXIT: qft_big_endian" qs "qs" return qs -- | Apply the Quantum Fourier Transform to a list of /n/ qubits. -- The input is little-endian and the output is big-endian. -- Unlike ' qft_little_endian ' and ' qft_big_endian ' , this function can -- be used in imperative style, i.e., it modifies its arguments -- \"in place\". qft_rev :: [Qubit] -> Circ [Qubit] qft_rev qs = do comment_with_label "ENTER: qft_rev" qs "qs" qs <- qft_internal qs comment_with_label "EXIT: qft_rev" qs "qs" return qs | Apply the Quantum Fourier Transform to a ' QDInt ' . -- -- Note that this function cannot be used in imperative style, i.e., it does not update its arguments place\ " . The output qubits -- are in different physical locations than the input ones. qft_int :: QDInt -> Circ QDInt qft_int x = do comment_with_label "ENTER: qft_int" x "x" x <- mmap qdint_of_qulist_bh $ qft_big_endian $ qulist_of_qdint_bh x comment_with_label "ENTER: qft_int" x "x" return x -- ---------------------------------------------------------------------- -- * Testing -- | A simple test. test :: Int -> IO () test n = print_generic Preview qft_little_endian (replicate n qubit)
null
https://raw.githubusercontent.com/thephoeron/quipper-language/15e555343a15c07b9aa97aced1ada22414f04af6/QuipperLib/QFT.hs
haskell
file COPYRIGHT for a list of authors, copyright holders, licensing, and other details. All rights reserved. ====================================================================== ---------------------------------------------------------------------- * Low-level implementation | Like 'qft_rev', but without the comments and labels. Apply the Quantum Fourier Transform to a list of /n/ qubits. The input is little-endian and the output is big-endian. place\". Auxiliary function used by 'qft'. ---------------------------------------------------------------------- * Wrappers | Apply the Quantum Fourier Transform to a list of /n/ qubits. Both the input and output qubit lists are little-endian, i.e., the leftmost qubit (head of the list) is the least significant one. Note that this function cannot be used in imperative style, i.e., are in different physical locations than the input ones. | Apply the Quantum Fourier Transform to a list of /n/ qubits. Both the input and output qubit lists are big-endian, i.e., the leftmost qubit (head of the list) is the most significant one. Note that this function cannot be used in imperative style, i.e., are in different physical locations than the input ones. | Apply the Quantum Fourier Transform to a list of /n/ qubits. The input is little-endian and the output is big-endian. be used in imperative style, i.e., it modifies its arguments \"in place\". Note that this function cannot be used in imperative style, i.e., are in different physical locations than the input ones. ---------------------------------------------------------------------- * Testing | A simple test.
This file is part of Quipper . Copyright ( C ) 2011 - 2014 . Please see the | This module implements the Quantum Fourier Transform . module QuipperLib.QFT ( qft_little_endian, qft_big_endian, qft_rev, qft_int ) where import Quipper import QuipperLib.Arith import Libraries.Auxiliary (mmap) Unlike ' qft_little_endian ' and ' qft_big_endian ' , this function can be used in imperative style , i.e. , it modifies its arguments qft_internal :: [Qubit] -> Circ [Qubit] qft_internal [] = return [] qft_internal [x] = do hadamard x return [x] qft_internal (x:xs) = do xs' <- qft_internal xs xs'' <- rotations x xs' (length xs') x' <- hadamard x return (x':xs'') where rotations :: Qubit -> [Qubit] -> Int -> Circ [Qubit] rotations _ [] _ = return [] rotations c (q:qs) n = do qs' <- rotations c qs n q' <- rGate ((n + 1) - length qs) q `controlled` c return (q':qs') it does not update its arguments place\ " . The output qubits qft_little_endian :: [Qubit] -> Circ [Qubit] qft_little_endian qs = do comment_with_label "ENTER: qft_little_endian" qs "qs" qs' <- qft_internal qs let qs = reverse qs' comment_with_label "EXIT: qft_little_endian" qs "qs" return qs it does not update its arguments place\ " . The output qubits qft_big_endian :: [Qubit] -> Circ [Qubit] qft_big_endian qs = do comment_with_label "ENTER: qft_big_endian" qs "qs" qs <- qft_internal (reverse qs) comment_with_label "EXIT: qft_big_endian" qs "qs" return qs Unlike ' qft_little_endian ' and ' qft_big_endian ' , this function can qft_rev :: [Qubit] -> Circ [Qubit] qft_rev qs = do comment_with_label "ENTER: qft_rev" qs "qs" qs <- qft_internal qs comment_with_label "EXIT: qft_rev" qs "qs" return qs | Apply the Quantum Fourier Transform to a ' QDInt ' . it does not update its arguments place\ " . The output qubits qft_int :: QDInt -> Circ QDInt qft_int x = do comment_with_label "ENTER: qft_int" x "x" x <- mmap qdint_of_qulist_bh $ qft_big_endian $ qulist_of_qdint_bh x comment_with_label "ENTER: qft_int" x "x" return x test :: Int -> IO () test n = print_generic Preview qft_little_endian (replicate n qubit)
2c37d405f17a903ed503b7fce8cc7cd106159b298923c9757fe457078c7cbbcc
futurice/fum2github
Fum.hs
{-# LANGUAGE OverloadedStrings #-} ---------------------------------------------------------------------------- -- | Module : Fum2GitHub . Fum Copyright : ( C ) 2015 Futurice -- License : BSD-3-Clause (see the file LICENSE) -- Maintainer : < > -- ---------------------------------------------------------------------------- module Fum2GitHub.Fum ( -- * Methods getAllUsers -- * Types , AuthToken(..) , User(..) , UsersResult(..) ) where import Control.Applicative import Control.Monad import Control.Monad.Catch import Control.Monad.Logger import Data.Aeson.Extra import qualified Data.ByteString.Lazy as LBS import qualified Data.Text as T import qualified Data.Text.Encoding as E import Network.HTTP.Client.Fxtra import Fum2GitHub.Types (URL(..)) newtype AuthToken = AuthToken { getAuthToken :: String } deriving (Eq, Show) data User = User { userName :: !String , userGithub :: !(Maybe String) , userEmail :: !(Maybe String) -- can be empty? } deriving (Eq, Show) instance FromJSON User where parseJSON = withObject "User object" $ \v -> User <$> v .: "username" <*> (emptyToNothing <$> v .: "github") <*> v .: "email" emptyToNothing :: [a] -> Maybe [a] emptyToNothing [] = Nothing emptyToNothing x = Just x data UsersResult = UsersResult { urUsers :: ![User] , urNext :: !(Maybe URL) } deriving (Eq, Show) instance FromJSON UsersResult where parseJSON = withObject "FUM users result object" p where p v = UsersResult <$> v .: "results" <*> v .: "next" | Get all users from the FUM API . getAllUsers :: (MonadThrow m, MonadHTTP m, MonadLogger m) => AuthToken -- ^ FUM authentication token -> URL -- ^ Initial url -> m [User] getAllUsers token url = concat `liftM` getPaginatedResponses (reqBuilder token) resParser url reqBuilder :: MonadThrow m => AuthToken -> URL -> m Request reqBuilder token url = do baseReq <- parseUrl $ getURL url let authHeader = ("Authorization", E.encodeUtf8 . T.pack $ "Token " ++ getAuthToken token) return $ baseReq { requestHeaders = authHeader : requestHeaders baseReq } resParser :: MonadThrow m => Response LBS.ByteString -> m (Maybe URL, [User]) resParser res = do UsersResult { urNext = next, urUsers = users } <- decode' $ responseBody res return (next, users)
null
https://raw.githubusercontent.com/futurice/fum2github/60e5ed8f0f8c06011b4c1b540ba16979eebb50f6/fum2github/library/Fum2GitHub/Fum.hs
haskell
# LANGUAGE OverloadedStrings # -------------------------------------------------------------------------- | License : BSD-3-Clause (see the file LICENSE) -------------------------------------------------------------------------- * Methods * Types can be empty? ^ FUM authentication token ^ Initial url
Module : Fum2GitHub . Fum Copyright : ( C ) 2015 Futurice Maintainer : < > module Fum2GitHub.Fum ( getAllUsers , AuthToken(..) , User(..) , UsersResult(..) ) where import Control.Applicative import Control.Monad import Control.Monad.Catch import Control.Monad.Logger import Data.Aeson.Extra import qualified Data.ByteString.Lazy as LBS import qualified Data.Text as T import qualified Data.Text.Encoding as E import Network.HTTP.Client.Fxtra import Fum2GitHub.Types (URL(..)) newtype AuthToken = AuthToken { getAuthToken :: String } deriving (Eq, Show) data User = User { userName :: !String , userGithub :: !(Maybe String) } deriving (Eq, Show) instance FromJSON User where parseJSON = withObject "User object" $ \v -> User <$> v .: "username" <*> (emptyToNothing <$> v .: "github") <*> v .: "email" emptyToNothing :: [a] -> Maybe [a] emptyToNothing [] = Nothing emptyToNothing x = Just x data UsersResult = UsersResult { urUsers :: ![User] , urNext :: !(Maybe URL) } deriving (Eq, Show) instance FromJSON UsersResult where parseJSON = withObject "FUM users result object" p where p v = UsersResult <$> v .: "results" <*> v .: "next" | Get all users from the FUM API . getAllUsers :: (MonadThrow m, MonadHTTP m, MonadLogger m) -> m [User] getAllUsers token url = concat `liftM` getPaginatedResponses (reqBuilder token) resParser url reqBuilder :: MonadThrow m => AuthToken -> URL -> m Request reqBuilder token url = do baseReq <- parseUrl $ getURL url let authHeader = ("Authorization", E.encodeUtf8 . T.pack $ "Token " ++ getAuthToken token) return $ baseReq { requestHeaders = authHeader : requestHeaders baseReq } resParser :: MonadThrow m => Response LBS.ByteString -> m (Maybe URL, [User]) resParser res = do UsersResult { urNext = next, urUsers = users } <- decode' $ responseBody res return (next, users)
b400e4bf844411a358c4d4e080122e3c69e43acf7f4d39bfeec0fca19c10005f
NicklasBoto/funQ
Deutsch.hs
| The Deustch Oracle algorithm module Deutsch where import FunQ type Oracle = (QBit, QBit) -> QM (QBit, QBit) -- | An oracle with a constant function constant :: Oracle constant (x,y) = do z <- new 0 swap (z, x) cnot (x, y) swap (z, x) return (x, y) -- | An oracle with a balanced function balanced :: Oracle balanced (x,y) = do pauliX x cnot (x,y) pauliX x return (x, y) | Will return a 1 if balanced and 0 if constant . deutsch :: Oracle -> QM Bit deutsch oracle = do x <- new 0 y <- new 1 hadamard x hadamard y oracle (x, y) hadamard x measure x
null
https://raw.githubusercontent.com/NicklasBoto/funQ/9444da05273be215a66044b976d031229d8832fc/examples/Deutsch.hs
haskell
| An oracle with a constant function | An oracle with a balanced function
| The Deustch Oracle algorithm module Deutsch where import FunQ type Oracle = (QBit, QBit) -> QM (QBit, QBit) constant :: Oracle constant (x,y) = do z <- new 0 swap (z, x) cnot (x, y) swap (z, x) return (x, y) balanced :: Oracle balanced (x,y) = do pauliX x cnot (x,y) pauliX x return (x, y) | Will return a 1 if balanced and 0 if constant . deutsch :: Oracle -> QM Bit deutsch oracle = do x <- new 0 y <- new 1 hadamard x hadamard y oracle (x, y) hadamard x measure x
ecc1a98339007b60bbb04c3f093d90e3fb8d158649bf2dbc2e83ceab6d72eb6e
dizengrong/erlang_game
gerl_center_srv_sup.erl
-module(gerl_center_srv_sup). -behaviour(supervisor). %% API -export([start_link/0]). %% Supervisor callbacks -export([init/1]). %% Helper macro for declaring children of supervisor -define(CHILD(I, Type), {I, {I, start_link, []}, permanent, 5000, Type, [I]}). %% =================================================================== %% API functions %% =================================================================== start_link() -> supervisor:start_link({local, ?MODULE}, ?MODULE, []). %% =================================================================== %% Supervisor callbacks %% =================================================================== init([]) -> {ok, {{one_for_one, 10, 10}, [ ?CHILD(account_srv, worker), ?CHILD(online_srv, worker), ?CHILD(map_dispatch, worker) ] } }.
null
https://raw.githubusercontent.com/dizengrong/erlang_game/4598f97daa9ca5eecff292ac401dd8f903eea867/gerl/src/center_srv/gerl_center_srv_sup.erl
erlang
API Supervisor callbacks Helper macro for declaring children of supervisor =================================================================== API functions =================================================================== =================================================================== Supervisor callbacks ===================================================================
-module(gerl_center_srv_sup). -behaviour(supervisor). -export([start_link/0]). -export([init/1]). -define(CHILD(I, Type), {I, {I, start_link, []}, permanent, 5000, Type, [I]}). start_link() -> supervisor:start_link({local, ?MODULE}, ?MODULE, []). init([]) -> {ok, {{one_for_one, 10, 10}, [ ?CHILD(account_srv, worker), ?CHILD(online_srv, worker), ?CHILD(map_dispatch, worker) ] } }.
2c5dfb7ad09c34d881d204a4ffa2f45560865b3b874e310528230407c5678a51
bruz/hotframeworks
main.clj
(ns hotframeworks.views.main (:require [clojure.data.json :as json] [compojure.route :as route] [hotframeworks.views.layout :as layout] [hotframeworks.models.db :as db] [hotframeworks.models.graphs :as graphs] [hotframeworks.models.framework :as framework])) (defn- framework-link [framework] (str "/frameworks/" (:url_identifier framework))) (defn- mini-ranking [frameworks] [:table {:class "table table-striped"} [:thead [:tr [:th "Framework"] [:th.score "Score"]]] [:tbody (map (fn [framework] [:tr [:td [:a {:href (framework-link framework)} (:name framework)]] [:td.score (:latest_score framework)]]) frameworks)]]) (defn- full-rankings [] (let [frameworks (framework/latest-scores)] [:table {:class "table table-striped"} [:thead [:tr [:th "Framework"] [:th.score "Github Score"] [:th.score "Stack Overflow Score"] [:th.score "Overall Score"]]] [:tbody (map (fn [framework] [:tr [:td.score [:a {:href (framework-link framework)} (:name framework)]] [:td.score (:github framework)] [:td.score (:stackoverflow framework)] [:td.score (:combined framework)]]) frameworks)]])) (defn- top-data-json [] (json/write-str (graphs/most-popular 10 30))) (defn- language-data-json [language] (json/write-str (graphs/for-language language 30))) (defn- framework-data-json [framework] (json/write-str (graphs/for-framework framework 30))) (defn home [] (layout/common [:div [:div#top-frameworks.row [:div#about.col-md-12.page-header [:h1 "Find your new favorite web framework" [:br] [:small "Measuring web framework popularity so you can find interesting frameworks to check out"]]]] [:div.row [:div.col-md-12 [:div#graph-container [:canvas#graph]]]] [:div#rankings.row [:div.col-md-12.page-header [:h1 "Rankings"] (full-rankings)]]] (format "var data = %s; Hotframeworks.graph(data);" (top-data-json)))) (defn language [identifier] (let [language (db/language-for-url-identifier identifier)] (if language (layout/common [:div.row [:h1 (:name language)] [:div.col-md-4 (mini-ranking (db/frameworks-for-language language))] [:div.col-md-6 [:div#graph-container [:canvas#graph]]] [:div.col-md-2 [:div#legend]]] (format "var data = %s; Hotframeworks.graph(data);" (language-data-json language))) (route/not-found "Not Found")))) (defn framework [identifier] (let [framework (db/framework-for-url-identifier identifier) github (framework/latest-score-for-framework framework "github") stackoverflow (framework/latest-score-for-framework framework "stackoverflow") combined (framework/latest-score-for-framework framework "combined") language (db/language-for-id (:language_id framework)) language-link (str "/languages/" (:url_identifier language)) github-link (str "/" (:github_owner framework) "/" (:github_repo framework)) stackoverflow-link (str "/" (:stackoverflow_tag framework))] (if framework (layout/common [:div#framework.row [:h1 (:name framework)] [:br] [:div.col-md-6. [:div.col-md-4 [:div.panel.panel-primary [:div.panel-heading "GitHub"] [:div.panel-body (or github "N/A")]]] [:div.col-md-4 [:div.panel.panel-primary [:div.panel-heading "Stack Overflow"] [:div.panel-body (or stackoverflow "N/A")]]] [:div.col-md-4 [:div.panel.panel-primary [:div.panel-heading "Combined"] [:div.panel-body (or combined "N/A")]]] (when (:description framework) [:p "Description: " (:description framework)]) [:p "Language: " [:a {:href language-link} (:name language)]] [:p "Framework Link: " [:a {:href (:site_url framework)} (:site_url framework)]] (when (:github_repo framework) [:p "GitHub Link: " [:a {:href github-link} github-link]]) (when (:stackoverflow_tag framework) [:p "Stack Overflow Questions: " [:a {:href stackoverflow-link} stackoverflow-link]])] [:div.col-md-4 [:div#graph-container [:canvas#graph]]] [:div.col-md-2 [:div#legend]]] (format "var data = %s; Hotframeworks.graph(data);" (framework-data-json framework))) (route/not-found "Not Found")))) (defn faq [] (layout/common [:div [:div#faq [:h1 "Frequently Asked Questions"] [:h3 "How are the different frameworks scored?"] [:p "Each framework is scored by two separate measures, and these are simply averaged. The two measures are:"] [:ol [:li "GitHub score: Based on the number of stars the git repository for a framework has on GitHub. Since Hotframeworks can't measure this for frameworks not on GitHub, you'll see 'N/A' for those."] [:li "Stack Overflow score: Based on the number of questions on Stack Overflow that are tagged with the name of the framework. Some frameworks don't have an unambiguous Stack Overflow tag, and have an 'N/A'."]] [:p "Since these two measures of popularity are on different scales the final scores normalized to a scale of 0-100. The scores are on a log scale since the measures cover such a large range, so for instance a framework with a score of 90 for Stack Overflow may have thousands of questions while a framework with a score of 10-20 might just have a handful."] [:h3 " Why does my favorite framework have such a low score? "] [:p " Since scores are simply calculated as an average of the two measures described in the previous question, you can investigate the individual scores as compared to other frameworks to see why your framework places where it does. With Github scores for instance, you can look at how many stars your framework has and compare it to frameworks with higher scores. If you still think something is wrong with the score after doing some investigation, please " [:a {:href "#suggestion"} "let us know."]] [:h3 "Why isn't my favorite framework listed? It's so cool!"] [:p "I'd love to hear about it. Just " [:a {:href "#suggestion"} "send a suggestion"] "."] [:h3 "What are the criteria for deciding if something is a \"web framework\"?"] [:p "As a rough guide, if you can finish the sentence \"I just built this sweet new web application with [insert name of framework here]\", then it'd probably be considered a web framework. Note that frameworks don't have to be \"full-stack\", they can be client-side only (like " [:a {:href ""} "GWT"] " ) or server-side only and qualify. Hotframeworks doesn't include JavaScript libraries like jQuery and MooTools though since these are typically used to enhance web applications that are built using another framework."]]] ""))
null
https://raw.githubusercontent.com/bruz/hotframeworks/629aa8f3cd7556479ea5cd7720d8b06ee4926ae4/src/hotframeworks/views/main.clj
clojure
" " "
(ns hotframeworks.views.main (:require [clojure.data.json :as json] [compojure.route :as route] [hotframeworks.views.layout :as layout] [hotframeworks.models.db :as db] [hotframeworks.models.graphs :as graphs] [hotframeworks.models.framework :as framework])) (defn- framework-link [framework] (str "/frameworks/" (:url_identifier framework))) (defn- mini-ranking [frameworks] [:table {:class "table table-striped"} [:thead [:tr [:th "Framework"] [:th.score "Score"]]] [:tbody (map (fn [framework] [:tr [:td [:a {:href (framework-link framework)} (:name framework)]] [:td.score (:latest_score framework)]]) frameworks)]]) (defn- full-rankings [] (let [frameworks (framework/latest-scores)] [:table {:class "table table-striped"} [:thead [:tr [:th "Framework"] [:th.score "Github Score"] [:th.score "Stack Overflow Score"] [:th.score "Overall Score"]]] [:tbody (map (fn [framework] [:tr [:td.score [:a {:href (framework-link framework)} (:name framework)]] [:td.score (:github framework)] [:td.score (:stackoverflow framework)] [:td.score (:combined framework)]]) frameworks)]])) (defn- top-data-json [] (json/write-str (graphs/most-popular 10 30))) (defn- language-data-json [language] (json/write-str (graphs/for-language language 30))) (defn- framework-data-json [framework] (json/write-str (graphs/for-framework framework 30))) (defn home [] (layout/common [:div [:div#top-frameworks.row [:div#about.col-md-12.page-header [:h1 "Find your new favorite web framework" [:br] [:small "Measuring web framework popularity so you can find interesting frameworks to check out"]]]] [:div.row [:div.col-md-12 [:div#graph-container [:canvas#graph]]]] [:div#rankings.row [:div.col-md-12.page-header [:h1 "Rankings"] (full-rankings)]]] (top-data-json)))) (defn language [identifier] (let [language (db/language-for-url-identifier identifier)] (if language (layout/common [:div.row [:h1 (:name language)] [:div.col-md-4 (mini-ranking (db/frameworks-for-language language))] [:div.col-md-6 [:div#graph-container [:canvas#graph]]] [:div.col-md-2 [:div#legend]]] (language-data-json language))) (route/not-found "Not Found")))) (defn framework [identifier] (let [framework (db/framework-for-url-identifier identifier) github (framework/latest-score-for-framework framework "github") stackoverflow (framework/latest-score-for-framework framework "stackoverflow") combined (framework/latest-score-for-framework framework "combined") language (db/language-for-id (:language_id framework)) language-link (str "/languages/" (:url_identifier language)) github-link (str "/" (:github_owner framework) "/" (:github_repo framework)) stackoverflow-link (str "/" (:stackoverflow_tag framework))] (if framework (layout/common [:div#framework.row [:h1 (:name framework)] [:br] [:div.col-md-6. [:div.col-md-4 [:div.panel.panel-primary [:div.panel-heading "GitHub"] [:div.panel-body (or github "N/A")]]] [:div.col-md-4 [:div.panel.panel-primary [:div.panel-heading "Stack Overflow"] [:div.panel-body (or stackoverflow "N/A")]]] [:div.col-md-4 [:div.panel.panel-primary [:div.panel-heading "Combined"] [:div.panel-body (or combined "N/A")]]] (when (:description framework) [:p "Description: " (:description framework)]) [:p "Language: " [:a {:href language-link} (:name language)]] [:p "Framework Link: " [:a {:href (:site_url framework)} (:site_url framework)]] (when (:github_repo framework) [:p "GitHub Link: " [:a {:href github-link} github-link]]) (when (:stackoverflow_tag framework) [:p "Stack Overflow Questions: " [:a {:href stackoverflow-link} stackoverflow-link]])] [:div.col-md-4 [:div#graph-container [:canvas#graph]]] [:div.col-md-2 [:div#legend]]] (framework-data-json framework))) (route/not-found "Not Found")))) (defn faq [] (layout/common [:div [:div#faq [:h1 "Frequently Asked Questions"] [:h3 "How are the different frameworks scored?"] [:p "Each framework is scored by two separate measures, and these are simply averaged. The two measures are:"] [:ol [:li "GitHub score: Based on the number of stars the git repository for a framework has on GitHub. Since Hotframeworks can't measure this for frameworks not on GitHub, you'll see 'N/A' for those."] [:li "Stack Overflow score: Based on the number of questions on Stack Overflow that are tagged with the name of the framework. Some frameworks don't have an unambiguous Stack Overflow tag, and have an 'N/A'."]] [:p "Since these two measures of popularity are on different scales the final scores normalized to a scale of 0-100. The scores are on a log scale since the measures cover such a large range, so for instance a framework with a score of 90 for Stack Overflow may have thousands of questions while a framework with a score of 10-20 might just have a handful."] [:h3 " Why does my favorite framework have such a low score? "] [:p " Since scores are simply calculated as an average of the two measures described in the previous question, you can investigate the individual scores as compared to other frameworks to see why your framework places where it does. With Github scores for instance, you can look at how many stars your framework has and compare it to frameworks with higher scores. If you still think something is wrong with the score after doing some investigation, please " [:a {:href "#suggestion"} "let us know."]] [:h3 "Why isn't my favorite framework listed? It's so cool!"] [:p "I'd love to hear about it. Just " [:a {:href "#suggestion"} "send a suggestion"] "."] [:h3 "What are the criteria for deciding if something is a \"web framework\"?"] [:p "As a rough guide, if you can finish the sentence \"I just built this sweet new web application with [insert name of framework here]\", then it'd probably be considered a web framework. Note that frameworks don't have to be \"full-stack\", they can be client-side only (like " [:a {:href ""} "GWT"] " ) or server-side only and qualify. Hotframeworks doesn't include JavaScript libraries like jQuery and MooTools though since these are typically used to enhance web applications that are built using another framework."]]] ""))
f780d5c7c8c9b2a6ac575e6e36f5f9a4a115e03bb34cf6f9521cf5df2fd6d59c
bhauman/advent-of-clojure
day12.clj
(ns advent-2017.day12 (:require [clojure.java.io :as io] [clojure.set :as st])) (def data (->> (io/resource "2017/day12") io/reader line-seq (map #(format "[%s]" %)) (map read-string))) (defn index [data'] (reduce (fn [accum [node _ & direct-connect]] (as-> (set direct-connect) x (disj x node) (assoc accum node x))) {} data')) ;; find group without cycles (defn group [idx root] (into #{} (tree-seq (let [seen (atom #{})] (fn [x] (when-not (@seen x) (swap! seen conj x)))) idx root))) part 1 #_(let [idx (index data)] (time (count (group idx 0)))) = > 113 part 2 ;; not worth optimizing for problem space #_(let [idx (index data)] (->> (map #(group idx %) (keys idx)) (into #{}) count)) = > 202
null
https://raw.githubusercontent.com/bhauman/advent-of-clojure/856763baf45bf7bf452ffd304dc1b89f9bc879a6/src/advent-2017/day12.clj
clojure
find group without cycles not worth optimizing for problem space
(ns advent-2017.day12 (:require [clojure.java.io :as io] [clojure.set :as st])) (def data (->> (io/resource "2017/day12") io/reader line-seq (map #(format "[%s]" %)) (map read-string))) (defn index [data'] (reduce (fn [accum [node _ & direct-connect]] (as-> (set direct-connect) x (disj x node) (assoc accum node x))) {} data')) (defn group [idx root] (into #{} (tree-seq (let [seen (atom #{})] (fn [x] (when-not (@seen x) (swap! seen conj x)))) idx root))) part 1 #_(let [idx (index data)] (time (count (group idx 0)))) = > 113 part 2 #_(let [idx (index data)] (->> (map #(group idx %) (keys idx)) (into #{}) count)) = > 202
431b5b40cdad55909622eefef0fd73d53abddaa6f61116f8a47a21905d746bac
nvim-treesitter/nvim-treesitter
indents.scm
[ (module) (program) (subroutine) (function) ; (interface) (if_statement) (do_loop_statement) (where_statement) (derived_type_definition) (enum) ] @indent [ (end_module_statement) (end_program_statement) (end_subroutine_statement) (end_function_statement) ; (end_interface_statement) (end_if_statement) (end_do_loop_statement) (else_clause) (elseif_clause) (end_type_statement) (end_enum_statement) (end_where_statement) ] @branch
null
https://raw.githubusercontent.com/nvim-treesitter/nvim-treesitter/a1b0e9ebb56f1042bc51e94252902ef14f688aaf/queries/fortran/indents.scm
scheme
(interface) (end_interface_statement)
[ (module) (program) (subroutine) (function) (if_statement) (do_loop_statement) (where_statement) (derived_type_definition) (enum) ] @indent [ (end_module_statement) (end_program_statement) (end_subroutine_statement) (end_function_statement) (end_if_statement) (end_do_loop_statement) (else_clause) (elseif_clause) (end_type_statement) (end_enum_statement) (end_where_statement) ] @branch
27f4c79c2822790002dfe4586be3e7e9cbe524f032387875d95c78212d3028b8
evolutics/haskell-formatter
Splitter.hs
{-| Description : Splitting lists on sublists -} module Language.Haskell.Formatter.Toolkit.Splitter (separate) where import qualified Control.Applicative as Applicative import qualified Data.List as List import qualified Data.Monoid as Monoid import qualified Language.Haskell.Formatter.Toolkit.ListTool as ListTool import qualified Language.Haskell.Formatter.Toolkit.Visit as Visit {-| Strategy to split a list on sublists. -} data Splitter a = Splitter{delimiterPolicy :: DelimiterPolicy, delimiterQueue :: [[a]]} deriving (Eq, Ord, Show) {-| What to do with the delimiters? -} data DelimiterPolicy = Drop | Separate | MergeLeft | MergeRight deriving (Eq, Ord, Show) {-| @separate d l@ splits @l@ on the delimiters @d@, which are matched in the given order. The delimiters are not kept. >>> separate ["pineapple", "pine"] "0pineapple1" ["0","1"] >>> separate ["pine", "pineapple"] "0pineapple1" ["0","apple1"] -} separate :: Eq a => [[a]] -> [a] -> [[a]] separate = split . createSplitter Drop where createSplitter rawDelimiterPolicy rawDelimiterQueue = Splitter{delimiterPolicy = rawDelimiterPolicy, delimiterQueue = rawDelimiterQueue} | s l@ splits @l@ according to the strategy @s@. split :: Eq a => Splitter a -> [a] -> [[a]] split splitter list = case delimiterPolicy splitter of Drop -> ListTool.takeEvery period parts Separate -> parts MergeLeft -> ListTool.concatenateRuns period parts MergeRight -> ListTool.concatenateShiftedRuns period shift parts where shift = 1 where period = 2 parts = rawSplit (delimiterQueue splitter) list | @rawSplit s l@ splits @l@ on the sublists @s@ , keeping the separators . prop > odd . length $ separate [ " apple " , " pine " ] l prop> odd . length $ separate ["apple", "pine"] l -} rawSplit :: Eq a => [[a]] -> [a] -> [[a]] rawSplit delimiters = move [] [] where move parts left [] = Monoid.mappend parts [left] move parts left right@(first : rest) = case stripFirstPrefix delimiters right of Nothing -> move parts (Monoid.mappend left [first]) rest Just (delimiter, suffix) -> move (Monoid.mappend parts [left, delimiter]) [] suffix | @stripFirstPrefix p l@ returns the first element of @p@ which is a prefix of @l@ and the rest of @l@. It returns ' Nothing ' if there is no such element . > > > stripFirstPrefix [ " \LF " , " \CR\LF " , " \CR " ] " \CR\LFpine " Just ( " \r\n","pine " ) > > > stripFirstPrefix [ " apple " ] " pineapple " Nothing @l@ and the rest of @l@. It returns 'Nothing' if there is no such element. >>> stripFirstPrefix ["\LF", "\CR\LF", "\CR"] "\CR\LFpine" Just ("\r\n","pine") >>> stripFirstPrefix ["apple"] "pineapple" Nothing -} stripFirstPrefix :: Eq a => [[a]] -> [a] -> Maybe ([a], [a]) stripFirstPrefix prefixes list = Visit.findJust strip prefixes where strip prefix = (,) prefix Applicative.<$> List.stripPrefix prefix list
null
https://raw.githubusercontent.com/evolutics/haskell-formatter/3919428e312db62b305de4dd1c84887e6cfa9478/src/library/Language/Haskell/Formatter/Toolkit/Splitter.hs
haskell
| Description : Splitting lists on sublists | Strategy to split a list on sublists. | What to do with the delimiters? | @separate d l@ splits @l@ on the delimiters @d@, which are matched in the given order. The delimiters are not kept. >>> separate ["pineapple", "pine"] "0pineapple1" ["0","1"] >>> separate ["pine", "pineapple"] "0pineapple1" ["0","apple1"]
module Language.Haskell.Formatter.Toolkit.Splitter (separate) where import qualified Control.Applicative as Applicative import qualified Data.List as List import qualified Data.Monoid as Monoid import qualified Language.Haskell.Formatter.Toolkit.ListTool as ListTool import qualified Language.Haskell.Formatter.Toolkit.Visit as Visit data Splitter a = Splitter{delimiterPolicy :: DelimiterPolicy, delimiterQueue :: [[a]]} deriving (Eq, Ord, Show) data DelimiterPolicy = Drop | Separate | MergeLeft | MergeRight deriving (Eq, Ord, Show) separate :: Eq a => [[a]] -> [a] -> [[a]] separate = split . createSplitter Drop where createSplitter rawDelimiterPolicy rawDelimiterQueue = Splitter{delimiterPolicy = rawDelimiterPolicy, delimiterQueue = rawDelimiterQueue} | s l@ splits @l@ according to the strategy @s@. split :: Eq a => Splitter a -> [a] -> [[a]] split splitter list = case delimiterPolicy splitter of Drop -> ListTool.takeEvery period parts Separate -> parts MergeLeft -> ListTool.concatenateRuns period parts MergeRight -> ListTool.concatenateShiftedRuns period shift parts where shift = 1 where period = 2 parts = rawSplit (delimiterQueue splitter) list | @rawSplit s l@ splits @l@ on the sublists @s@ , keeping the separators . prop > odd . length $ separate [ " apple " , " pine " ] l prop> odd . length $ separate ["apple", "pine"] l -} rawSplit :: Eq a => [[a]] -> [a] -> [[a]] rawSplit delimiters = move [] [] where move parts left [] = Monoid.mappend parts [left] move parts left right@(first : rest) = case stripFirstPrefix delimiters right of Nothing -> move parts (Monoid.mappend left [first]) rest Just (delimiter, suffix) -> move (Monoid.mappend parts [left, delimiter]) [] suffix | @stripFirstPrefix p l@ returns the first element of @p@ which is a prefix of @l@ and the rest of @l@. It returns ' Nothing ' if there is no such element . > > > stripFirstPrefix [ " \LF " , " \CR\LF " , " \CR " ] " \CR\LFpine " Just ( " \r\n","pine " ) > > > stripFirstPrefix [ " apple " ] " pineapple " Nothing @l@ and the rest of @l@. It returns 'Nothing' if there is no such element. >>> stripFirstPrefix ["\LF", "\CR\LF", "\CR"] "\CR\LFpine" Just ("\r\n","pine") >>> stripFirstPrefix ["apple"] "pineapple" Nothing -} stripFirstPrefix :: Eq a => [[a]] -> [a] -> Maybe ([a], [a]) stripFirstPrefix prefixes list = Visit.findJust strip prefixes where strip prefix = (,) prefix Applicative.<$> List.stripPrefix prefix list
cc641828905d7a254bc403df832926d2cc035806ed12317009512330a3624982
psibi/yesod-rest
StaticFiles.hs
# LANGUAGE NoImplicitPrelude # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE TemplateHaskell # module Settings.StaticFiles where import Settings (appStaticDir, compileTimeAppSettings) import Yesod.Static (staticFilesList) -- This generates easy references to files in the static directory at compile time, -- giving you compile-time verification that referenced files exist. -- Warning: any files added to your static directory during run-time can't be accessed this way . You 'll have to use their FilePath or URL to access them . -- -- For example, to refer to @static/js/script.js@ via an identifier, you'd use: -- js_script_js -- -- If the identifier is not available, you may use: -- StaticFile [ " js " , " script.js " ] [ ] staticFilesList "static" ["css/bootstrap.css", "builds/bundle.js"] -- If you prefer to updating the references by force -- especially when you are devloping like ` stack exec -- yesod devel ` -- -- you can update references by chaning file stamp. -- -- On linux or Unix-like system, you can use -- shell> touch /Path/To/Settings/StaticFiles.hs -- -- or save without changes on your favorite editor. so yesod devel will re - compile automatically and generate the refereces -- including new one. -- -- In this way you can use on your shakespearean template(s) -- Let's say you have image on "yourStaticDir/img/background-1.jpg" -- you can use the reference of the file on shakespearean templates like bellow -- -- /* note: `-' becomes '_' as well */ -- @{StaticR img_background_1_jpg}
null
https://raw.githubusercontent.com/psibi/yesod-rest/01deecd92e10378926085e418a35bdc09e8e0b18/src/Settings/StaticFiles.hs
haskell
# LANGUAGE OverloadedStrings # This generates easy references to files in the static directory at compile time, giving you compile-time verification that referenced files exist. Warning: any files added to your static directory during run-time can't be For example, to refer to @static/js/script.js@ via an identifier, you'd use: If the identifier is not available, you may use: If you prefer to updating the references by force especially when you are devloping like ` stack exec -- yesod devel ` -- you can update references by chaning file stamp. On linux or Unix-like system, you can use shell> touch /Path/To/Settings/StaticFiles.hs or save without changes on your favorite editor. including new one. In this way you can use on your shakespearean template(s) Let's say you have image on "yourStaticDir/img/background-1.jpg" you can use the reference of the file on shakespearean templates like bellow /* note: `-' becomes '_' as well */ @{StaticR img_background_1_jpg}
# LANGUAGE NoImplicitPrelude # # LANGUAGE TemplateHaskell # module Settings.StaticFiles where import Settings (appStaticDir, compileTimeAppSettings) import Yesod.Static (staticFilesList) accessed this way . You 'll have to use their FilePath or URL to access them . js_script_js StaticFile [ " js " , " script.js " ] [ ] staticFilesList "static" ["css/bootstrap.css", "builds/bundle.js"] so yesod devel will re - compile automatically and generate the refereces
14aa1a92554b661a1555e7b6b486f9bdc1a76d85691daab994a4a74db6fdaae0
fogfish/serverless
serverless.erl
%% Copyright ( C ) 2018 %% %% This file may be modified and distributed under the terms of the MIT license . See the LICENSE file for details . %% %% -module(serverless). -compile({parse_transform, category}). -export([ spawn/2, %% logger api emergency/1, alert/1, critical/1, error/1, warning/1, notice/1, info/1, debug/1, %% mock lambda runtime mock/2, mock/3 ]). %%%------------------------------------------------------------------ %%% %%% api %%% %%%------------------------------------------------------------------ spawn(Lambda, ["-f", File]) -> application:set_env(serverless, crlf, <<$\n>>), {ok, _} = application:ensure_all_started(serverless, permanent), application:start(serverless, permanent), {ok, Event} = file:read_file(File), {ok, Reply} = Lambda(jsx:decode(Event, [return_maps])), serverless:notice($-), serverless:notice(Reply); spawn(Lambda, _Opts) -> {ok, _} = application:ensure_all_started(serverless, permanent), {ok, _} = serverless_sup:spawn(Lambda), spawn_loop(). spawn_loop() -> receive _ -> spawn_loop() end. %%%------------------------------------------------------------------ %%% %%% error logger %%% %%%------------------------------------------------------------------ %% %% system us unusable emergency(Msg) -> serverless_logger:log(emergency, self(), Msg). %% %% action must be taken immediately alert(Msg) -> serverless_logger:log(alert, self(), Msg). %% %% critical(Msg) -> serverless_logger:log(critical, self(), Msg). %% %% error(Msg) -> serverless_logger:log(error, self(), Msg). %% %% warning(Msg) -> serverless_logger:log(warning, self(), Msg). %% %% normal but significant conditions notice(Msg) -> serverless_logger:log(notice, self(), Msg). %% %% informational messages info(Msg) -> serverless_logger:log(info, self(), Msg). %% %% debug-level messages debug(Msg) -> serverless_logger:log(debug, self(), Msg). %%%------------------------------------------------------------------ %%% %%% lambda runtime mock api %%% %%%------------------------------------------------------------------ mock(Lambda, Mock) -> serverless_mock:test(Lambda, Mock, 5000). mock(Lambda, Mock, Timeout) -> serverless_mock:test(Lambda, Mock, Timeout).
null
https://raw.githubusercontent.com/fogfish/serverless/c804e510e9c473941b1b457ba175f537f1939f39/src/serverless.erl
erlang
This file may be modified and distributed under the terms logger api mock lambda runtime ------------------------------------------------------------------ api ------------------------------------------------------------------ ------------------------------------------------------------------ error logger ------------------------------------------------------------------ system us unusable action must be taken immediately normal but significant conditions informational messages debug-level messages ------------------------------------------------------------------ lambda runtime mock api ------------------------------------------------------------------
Copyright ( C ) 2018 of the MIT license . See the LICENSE file for details . -module(serverless). -compile({parse_transform, category}). -export([ spawn/2, emergency/1, alert/1, critical/1, error/1, warning/1, notice/1, info/1, debug/1, mock/2, mock/3 ]). spawn(Lambda, ["-f", File]) -> application:set_env(serverless, crlf, <<$\n>>), {ok, _} = application:ensure_all_started(serverless, permanent), application:start(serverless, permanent), {ok, Event} = file:read_file(File), {ok, Reply} = Lambda(jsx:decode(Event, [return_maps])), serverless:notice($-), serverless:notice(Reply); spawn(Lambda, _Opts) -> {ok, _} = application:ensure_all_started(serverless, permanent), {ok, _} = serverless_sup:spawn(Lambda), spawn_loop(). spawn_loop() -> receive _ -> spawn_loop() end. emergency(Msg) -> serverless_logger:log(emergency, self(), Msg). alert(Msg) -> serverless_logger:log(alert, self(), Msg). critical(Msg) -> serverless_logger:log(critical, self(), Msg). error(Msg) -> serverless_logger:log(error, self(), Msg). warning(Msg) -> serverless_logger:log(warning, self(), Msg). notice(Msg) -> serverless_logger:log(notice, self(), Msg). info(Msg) -> serverless_logger:log(info, self(), Msg). debug(Msg) -> serverless_logger:log(debug, self(), Msg). mock(Lambda, Mock) -> serverless_mock:test(Lambda, Mock, 5000). mock(Lambda, Mock, Timeout) -> serverless_mock:test(Lambda, Mock, Timeout).
883e23976ac321a64cfebd4f01b846e5f5eab10451a8514aa2f4ca33f4c120df
SimulaVR/godot-haskell
InputEventAction.hs
# LANGUAGE DerivingStrategies , GeneralizedNewtypeDeriving , TypeFamilies , TypeOperators , FlexibleContexts , DataKinds , MultiParamTypeClasses # TypeFamilies, TypeOperators, FlexibleContexts, DataKinds, MultiParamTypeClasses #-} module Godot.Core.InputEventAction (Godot.Core.InputEventAction.is_pressed, Godot.Core.InputEventAction.get_action, Godot.Core.InputEventAction.get_strength, Godot.Core.InputEventAction.set_action, Godot.Core.InputEventAction.set_pressed, Godot.Core.InputEventAction.set_strength) where import Data.Coerce import Foreign.C import Godot.Internal.Dispatch import qualified Data.Vector as V import Linear(V2(..),V3(..),M22) import Data.Colour(withOpacity) import Data.Colour.SRGB(sRGB) import System.IO.Unsafe import Godot.Gdnative.Internal import Godot.Api.Types import Godot.Core.InputEvent() instance NodeProperty InputEventAction "action" GodotString 'False where nodeProperty = (get_action, wrapDroppingSetter set_action, Nothing) # NOINLINE bindInputEventAction_is_pressed # | If @true@ , the action 's state is pressed . If @false@ , the action 's state is released . bindInputEventAction_is_pressed :: MethodBind bindInputEventAction_is_pressed = unsafePerformIO $ withCString "InputEventAction" $ \ clsNamePtr -> withCString "is_pressed" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | If @true@ , the action 's state is pressed . If @false@ , the action 's state is released . is_pressed :: (InputEventAction :< cls, Object :< cls) => cls -> IO Bool is_pressed cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindInputEventAction_is_pressed (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod InputEventAction "is_pressed" '[] (IO Bool) where nodeMethod = Godot.Core.InputEventAction.is_pressed instance NodeProperty InputEventAction "pressed" Bool 'False where nodeProperty = (is_pressed, wrapDroppingSetter set_pressed, Nothing) instance NodeProperty InputEventAction "strength" Float 'False where nodeProperty = (get_strength, wrapDroppingSetter set_strength, Nothing) # NOINLINE bindInputEventAction_get_action # | The action 's name . Actions are accessed via this @String@. bindInputEventAction_get_action :: MethodBind bindInputEventAction_get_action = unsafePerformIO $ withCString "InputEventAction" $ \ clsNamePtr -> withCString "get_action" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | The action 's name . Actions are accessed via this @String@. get_action :: (InputEventAction :< cls, Object :< cls) => cls -> IO GodotString get_action cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindInputEventAction_get_action (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod InputEventAction "get_action" '[] (IO GodotString) where nodeMethod = Godot.Core.InputEventAction.get_action # NOINLINE bindInputEventAction_get_strength # | The action 's strength between 0 and 1 . This value is considered as equal to 0 if pressed is @false@. The event strength allows faking analog joypad motion events , by precising how strongly is the joypad axis bent or pressed . bindInputEventAction_get_strength :: MethodBind bindInputEventAction_get_strength = unsafePerformIO $ withCString "InputEventAction" $ \ clsNamePtr -> withCString "get_strength" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | The action 's strength between 0 and 1 . This value is considered as equal to 0 if pressed is @false@. The event strength allows faking analog joypad motion events , by precising how strongly is the joypad axis bent or pressed . get_strength :: (InputEventAction :< cls, Object :< cls) => cls -> IO Float get_strength cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindInputEventAction_get_strength (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod InputEventAction "get_strength" '[] (IO Float) where nodeMethod = Godot.Core.InputEventAction.get_strength # NOINLINE bindInputEventAction_set_action # | The action 's name . Actions are accessed via this @String@. bindInputEventAction_set_action :: MethodBind bindInputEventAction_set_action = unsafePerformIO $ withCString "InputEventAction" $ \ clsNamePtr -> withCString "set_action" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | The action 's name . Actions are accessed via this @String@. set_action :: (InputEventAction :< cls, Object :< cls) => cls -> GodotString -> IO () set_action cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindInputEventAction_set_action (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod InputEventAction "set_action" '[GodotString] (IO ()) where nodeMethod = Godot.Core.InputEventAction.set_action # NOINLINE bindInputEventAction_set_pressed # | If @true@ , the action 's state is pressed . If @false@ , the action 's state is released . bindInputEventAction_set_pressed :: MethodBind bindInputEventAction_set_pressed = unsafePerformIO $ withCString "InputEventAction" $ \ clsNamePtr -> withCString "set_pressed" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | If @true@ , the action 's state is pressed . If @false@ , the action 's state is released . set_pressed :: (InputEventAction :< cls, Object :< cls) => cls -> Bool -> IO () set_pressed cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindInputEventAction_set_pressed (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod InputEventAction "set_pressed" '[Bool] (IO ()) where nodeMethod = Godot.Core.InputEventAction.set_pressed # NOINLINE bindInputEventAction_set_strength # | The action 's strength between 0 and 1 . This value is considered as equal to 0 if pressed is @false@. The event strength allows faking analog joypad motion events , by precising how strongly is the joypad axis bent or pressed . bindInputEventAction_set_strength :: MethodBind bindInputEventAction_set_strength = unsafePerformIO $ withCString "InputEventAction" $ \ clsNamePtr -> withCString "set_strength" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | The action 's strength between 0 and 1 . This value is considered as equal to 0 if pressed is @false@. The event strength allows faking analog joypad motion events , by precising how strongly is the joypad axis bent or pressed . set_strength :: (InputEventAction :< cls, Object :< cls) => cls -> Float -> IO () set_strength cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindInputEventAction_set_strength (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod InputEventAction "set_strength" '[Float] (IO ()) where nodeMethod = Godot.Core.InputEventAction.set_strength
null
https://raw.githubusercontent.com/SimulaVR/godot-haskell/e8f2c45f1b9cc2f0586ebdc9ec6002c8c2d384ae/src/Godot/Core/InputEventAction.hs
haskell
# LANGUAGE DerivingStrategies , GeneralizedNewtypeDeriving , TypeFamilies , TypeOperators , FlexibleContexts , DataKinds , MultiParamTypeClasses # TypeFamilies, TypeOperators, FlexibleContexts, DataKinds, MultiParamTypeClasses #-} module Godot.Core.InputEventAction (Godot.Core.InputEventAction.is_pressed, Godot.Core.InputEventAction.get_action, Godot.Core.InputEventAction.get_strength, Godot.Core.InputEventAction.set_action, Godot.Core.InputEventAction.set_pressed, Godot.Core.InputEventAction.set_strength) where import Data.Coerce import Foreign.C import Godot.Internal.Dispatch import qualified Data.Vector as V import Linear(V2(..),V3(..),M22) import Data.Colour(withOpacity) import Data.Colour.SRGB(sRGB) import System.IO.Unsafe import Godot.Gdnative.Internal import Godot.Api.Types import Godot.Core.InputEvent() instance NodeProperty InputEventAction "action" GodotString 'False where nodeProperty = (get_action, wrapDroppingSetter set_action, Nothing) # NOINLINE bindInputEventAction_is_pressed # | If @true@ , the action 's state is pressed . If @false@ , the action 's state is released . bindInputEventAction_is_pressed :: MethodBind bindInputEventAction_is_pressed = unsafePerformIO $ withCString "InputEventAction" $ \ clsNamePtr -> withCString "is_pressed" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | If @true@ , the action 's state is pressed . If @false@ , the action 's state is released . is_pressed :: (InputEventAction :< cls, Object :< cls) => cls -> IO Bool is_pressed cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindInputEventAction_is_pressed (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod InputEventAction "is_pressed" '[] (IO Bool) where nodeMethod = Godot.Core.InputEventAction.is_pressed instance NodeProperty InputEventAction "pressed" Bool 'False where nodeProperty = (is_pressed, wrapDroppingSetter set_pressed, Nothing) instance NodeProperty InputEventAction "strength" Float 'False where nodeProperty = (get_strength, wrapDroppingSetter set_strength, Nothing) # NOINLINE bindInputEventAction_get_action # | The action 's name . Actions are accessed via this @String@. bindInputEventAction_get_action :: MethodBind bindInputEventAction_get_action = unsafePerformIO $ withCString "InputEventAction" $ \ clsNamePtr -> withCString "get_action" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | The action 's name . Actions are accessed via this @String@. get_action :: (InputEventAction :< cls, Object :< cls) => cls -> IO GodotString get_action cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindInputEventAction_get_action (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod InputEventAction "get_action" '[] (IO GodotString) where nodeMethod = Godot.Core.InputEventAction.get_action # NOINLINE bindInputEventAction_get_strength # | The action 's strength between 0 and 1 . This value is considered as equal to 0 if pressed is @false@. The event strength allows faking analog joypad motion events , by precising how strongly is the joypad axis bent or pressed . bindInputEventAction_get_strength :: MethodBind bindInputEventAction_get_strength = unsafePerformIO $ withCString "InputEventAction" $ \ clsNamePtr -> withCString "get_strength" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | The action 's strength between 0 and 1 . This value is considered as equal to 0 if pressed is @false@. The event strength allows faking analog joypad motion events , by precising how strongly is the joypad axis bent or pressed . get_strength :: (InputEventAction :< cls, Object :< cls) => cls -> IO Float get_strength cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindInputEventAction_get_strength (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod InputEventAction "get_strength" '[] (IO Float) where nodeMethod = Godot.Core.InputEventAction.get_strength # NOINLINE bindInputEventAction_set_action # | The action 's name . Actions are accessed via this @String@. bindInputEventAction_set_action :: MethodBind bindInputEventAction_set_action = unsafePerformIO $ withCString "InputEventAction" $ \ clsNamePtr -> withCString "set_action" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | The action 's name . Actions are accessed via this @String@. set_action :: (InputEventAction :< cls, Object :< cls) => cls -> GodotString -> IO () set_action cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindInputEventAction_set_action (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod InputEventAction "set_action" '[GodotString] (IO ()) where nodeMethod = Godot.Core.InputEventAction.set_action # NOINLINE bindInputEventAction_set_pressed # | If @true@ , the action 's state is pressed . If @false@ , the action 's state is released . bindInputEventAction_set_pressed :: MethodBind bindInputEventAction_set_pressed = unsafePerformIO $ withCString "InputEventAction" $ \ clsNamePtr -> withCString "set_pressed" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | If @true@ , the action 's state is pressed . If @false@ , the action 's state is released . set_pressed :: (InputEventAction :< cls, Object :< cls) => cls -> Bool -> IO () set_pressed cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindInputEventAction_set_pressed (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod InputEventAction "set_pressed" '[Bool] (IO ()) where nodeMethod = Godot.Core.InputEventAction.set_pressed # NOINLINE bindInputEventAction_set_strength # | The action 's strength between 0 and 1 . This value is considered as equal to 0 if pressed is @false@. The event strength allows faking analog joypad motion events , by precising how strongly is the joypad axis bent or pressed . bindInputEventAction_set_strength :: MethodBind bindInputEventAction_set_strength = unsafePerformIO $ withCString "InputEventAction" $ \ clsNamePtr -> withCString "set_strength" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | The action 's strength between 0 and 1 . This value is considered as equal to 0 if pressed is @false@. The event strength allows faking analog joypad motion events , by precising how strongly is the joypad axis bent or pressed . set_strength :: (InputEventAction :< cls, Object :< cls) => cls -> Float -> IO () set_strength cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindInputEventAction_set_strength (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod InputEventAction "set_strength" '[Float] (IO ()) where nodeMethod = Godot.Core.InputEventAction.set_strength
741166c97153a85bd928a4107e78572550cbeb8fc12c8719f8734abb8a4c99e3
cirfi/sicp-my-solutions
1.24.scm
define runtime for GNU ;;; (define (runtime) (tms:clock (times))) ;;; define runtime for Racket ;;; (define (runtime) (current-milliseconds)) ;;; timed prime, modified (define (timed-prime-test n) (start-prime-test n (runtime))) (define (start-prime-test n start-time) (if (prime? n) (report-prime n (- (runtime) start-time)) #f)) (define (report-prime n elapsed-time) (display n) (display " *** ") (display elapsed-time) (newline)) ;;; prime? (define (square x) (* x x)) (define (expmod base exp m) (cond ((= exp 0) 1) ((even? exp) (remainder (square (expmod base (/ exp 2) m)) m)) (else (remainder (* base (expmod base (- exp 1) m)) m)))) (define (fermat-test n) (define (random-test a) (= (expmod a n n) a)) (random-test (+ (random (- n 1)) 1))) (define (fast-prime? n times) (cond ((= times 0) #t) ((fermat-test n) (fast-prime? n (- times 1))) (else #f))) (define (prime? n) (fast-prime? n 233)) ;;; search-for-primes (define (search-for-primes start) (define (search-iter n count) (cond ((= count 3)) ((timed-prime-test n) (search-iter (+ n 2) (+ count 1))) (else (search-iter (+ n 2) count)))) (cond ((even? start) (search-iter (+ start 1) 0)) (else (search-iter start 0)))) (search-for-primes 1000) 1009 * * * 1.9999999999999574e-2 ;;; 1013 *** .00999999999999801 1019 * * * 1.9999999999999574e-2 (search-for-primes 10000) ;;; 10007 *** 1.0000000000001563e-2 10009 * * * 1.9999999999999574e-2 10037 * * * 1.0000000000001563e-2 (search-for-primes 100000) ;;; 100003 *** .00999999999999801 100019 * * * 1.9999999999999574e-2 100043 * * * 1.0000000000001563e-2 (search-for-primes 1000000) 1000003 * * * .00999999999999801 1000033 * * * 2.0000000000003126e-2 1000037 * * * .00999999999999801 (search-for-primes 1000000000) 1000000007 * * * 1.9999999999999574e-2 1000000009 * * * 1.0000000000001563e-2 1000000021 * * * 1.9999999999999574e-2 (search-for-primes 10000000000) 10000000019 * * * 1.9999999999999574e-2 ;;; 10000000033 *** 1.9999999999999574e-2 ;;; 10000000061 *** 1.9999999999999574e-2 (search-for-primes 100000000000) 100000000003 * * * 1.9999999999999574e-2 100000000019 * * * 1.9999999999999574e-2 100000000057 * * * 2.0000000000003126e-2 (search-for-primes 1000000000000) 1000000000039 * * * 1.9999999999999574e-2 1000000000061 * * * 1.9999999999999574e-2 1000000000063 * * * 1.9999999999999574e-2 (search-for-primes 1000000000000000000) 1000000000000000003 * * * .0799999999999983 1000000000000000009 * * * .05000000000000071 1000000000000000031 * * * .05000000000000071 (search-for-primes 1000000000000000000000000000000000000000000) 1000000000000000000000000000000000000000063 * * * .15000000000000213 1000000000000000000000000000000000000000169 * * * .08999999999999986 1000000000000000000000000000000000000000361 * * * .08999999999999986 (search-for-primes 10000000000000000000000000000000000000000000000000000000000000000000000000000000) 10000000000000000000000000000000000000000000000000000000000000000000000000000049 * * * .25 10000000000000000000000000000000000000000000000000000000000000000000000000000247 * * * .21000000000000085 10000000000000000000000000000000000000000000000000000000000000000000000000000561 * * * .21000000000000085 ;;; O(log(n)) growth
null
https://raw.githubusercontent.com/cirfi/sicp-my-solutions/4b6cc17391aa2c8c033b42b076a663b23aa022de/ch1/1.24.scm
scheme
(define (runtime) (tms:clock (times))) define runtime for Racket (define (runtime) (current-milliseconds)) timed prime, modified prime? search-for-primes 1013 *** .00999999999999801 10007 *** 1.0000000000001563e-2 100003 *** .00999999999999801 10000000033 *** 1.9999999999999574e-2 10000000061 *** 1.9999999999999574e-2 O(log(n)) growth
define runtime for GNU (define (timed-prime-test n) (start-prime-test n (runtime))) (define (start-prime-test n start-time) (if (prime? n) (report-prime n (- (runtime) start-time)) #f)) (define (report-prime n elapsed-time) (display n) (display " *** ") (display elapsed-time) (newline)) (define (square x) (* x x)) (define (expmod base exp m) (cond ((= exp 0) 1) ((even? exp) (remainder (square (expmod base (/ exp 2) m)) m)) (else (remainder (* base (expmod base (- exp 1) m)) m)))) (define (fermat-test n) (define (random-test a) (= (expmod a n n) a)) (random-test (+ (random (- n 1)) 1))) (define (fast-prime? n times) (cond ((= times 0) #t) ((fermat-test n) (fast-prime? n (- times 1))) (else #f))) (define (prime? n) (fast-prime? n 233)) (define (search-for-primes start) (define (search-iter n count) (cond ((= count 3)) ((timed-prime-test n) (search-iter (+ n 2) (+ count 1))) (else (search-iter (+ n 2) count)))) (cond ((even? start) (search-iter (+ start 1) 0)) (else (search-iter start 0)))) (search-for-primes 1000) 1009 * * * 1.9999999999999574e-2 1019 * * * 1.9999999999999574e-2 (search-for-primes 10000) 10009 * * * 1.9999999999999574e-2 10037 * * * 1.0000000000001563e-2 (search-for-primes 100000) 100019 * * * 1.9999999999999574e-2 100043 * * * 1.0000000000001563e-2 (search-for-primes 1000000) 1000003 * * * .00999999999999801 1000033 * * * 2.0000000000003126e-2 1000037 * * * .00999999999999801 (search-for-primes 1000000000) 1000000007 * * * 1.9999999999999574e-2 1000000009 * * * 1.0000000000001563e-2 1000000021 * * * 1.9999999999999574e-2 (search-for-primes 10000000000) 10000000019 * * * 1.9999999999999574e-2 (search-for-primes 100000000000) 100000000003 * * * 1.9999999999999574e-2 100000000019 * * * 1.9999999999999574e-2 100000000057 * * * 2.0000000000003126e-2 (search-for-primes 1000000000000) 1000000000039 * * * 1.9999999999999574e-2 1000000000061 * * * 1.9999999999999574e-2 1000000000063 * * * 1.9999999999999574e-2 (search-for-primes 1000000000000000000) 1000000000000000003 * * * .0799999999999983 1000000000000000009 * * * .05000000000000071 1000000000000000031 * * * .05000000000000071 (search-for-primes 1000000000000000000000000000000000000000000) 1000000000000000000000000000000000000000063 * * * .15000000000000213 1000000000000000000000000000000000000000169 * * * .08999999999999986 1000000000000000000000000000000000000000361 * * * .08999999999999986 (search-for-primes 10000000000000000000000000000000000000000000000000000000000000000000000000000000) 10000000000000000000000000000000000000000000000000000000000000000000000000000049 * * * .25 10000000000000000000000000000000000000000000000000000000000000000000000000000247 * * * .21000000000000085 10000000000000000000000000000000000000000000000000000000000000000000000000000561 * * * .21000000000000085
f27d91644d43219e97db076a98a08d68f0f5b89b8b0bb4a4320de35699c8b6ed
ThomasHintz/keep-the-records
production.scm
(require-extension spiffy) (root-path "~/keep-the-records") (debug-log "~/keep-the-records/logs/debug.log") (error-log "~/keep-the-records/logs/error.log")
null
https://raw.githubusercontent.com/ThomasHintz/keep-the-records/c20e648e831bed2ced3f2f74bfc590dc06b5f076/production.scm
scheme
(require-extension spiffy) (root-path "~/keep-the-records") (debug-log "~/keep-the-records/logs/debug.log") (error-log "~/keep-the-records/logs/error.log")
9c270172b08f38869f9f00551272b01b244e56562e91ce64b2708b458684388b
Flexiana/tiny-rbac
acl.clj
(ns liberator-demo.acl (:require [tiny-rbac.builder :as b] [liberator-demo.models.users :as user-model] [tiny-rbac.core :as acl] [liberator-demo.models.posts :as post-model])) (def role-set (-> {} (b/add-resource [:post :comment]) (b/add-action :post [:read :create :delete :update]) (b/add-action :comment [:create :modify :delete]) (b/add-role [:lurker :poster :only-friends]) (b/add-permission :only-friends :post :read [:own :friends]) (b/add-inheritance :poster :lurker) (b/add-permission :lurker :post :read :public) (b/add-permission :poster :post :read [:own :friends]) (b/add-permission :poster :post :create :own) (b/add-permission :poster :post :delete :own) (b/add-permission :poster :post :update :own) (b/add-permission :poster :comment :create :friends) (b/add-permission :poster :comment :modify :own) (b/add-permission :poster :comment :delete :own))) (defn acl-post [user action] {:resource :post :action action :role (:role user)}) (defn owned-post [user action post-id] (let [user-id (:id user) acl (acl-post user action) permissions (acl/permissions role-set acl) friends (user-model/get-friends-ids user-id)] (first (post-model/fetch-posts permissions user-id friends post-id)))) (defn owned-posts [user action] (let [user-id (:id user) acl (acl-post user action) permissions (acl/permissions role-set acl) friends (user-model/get-friends-ids user-id)] (post-model/fetch-posts permissions user-id friends)))
null
https://raw.githubusercontent.com/Flexiana/tiny-rbac/92627a605e94d97a2396aea004312962361cb8a8/examples/liberator-demo/src/liberator_demo/acl.clj
clojure
(ns liberator-demo.acl (:require [tiny-rbac.builder :as b] [liberator-demo.models.users :as user-model] [tiny-rbac.core :as acl] [liberator-demo.models.posts :as post-model])) (def role-set (-> {} (b/add-resource [:post :comment]) (b/add-action :post [:read :create :delete :update]) (b/add-action :comment [:create :modify :delete]) (b/add-role [:lurker :poster :only-friends]) (b/add-permission :only-friends :post :read [:own :friends]) (b/add-inheritance :poster :lurker) (b/add-permission :lurker :post :read :public) (b/add-permission :poster :post :read [:own :friends]) (b/add-permission :poster :post :create :own) (b/add-permission :poster :post :delete :own) (b/add-permission :poster :post :update :own) (b/add-permission :poster :comment :create :friends) (b/add-permission :poster :comment :modify :own) (b/add-permission :poster :comment :delete :own))) (defn acl-post [user action] {:resource :post :action action :role (:role user)}) (defn owned-post [user action post-id] (let [user-id (:id user) acl (acl-post user action) permissions (acl/permissions role-set acl) friends (user-model/get-friends-ids user-id)] (first (post-model/fetch-posts permissions user-id friends post-id)))) (defn owned-posts [user action] (let [user-id (:id user) acl (acl-post user action) permissions (acl/permissions role-set acl) friends (user-model/get-friends-ids user-id)] (post-model/fetch-posts permissions user-id friends)))
6048024f3faedb5446c014e74243469ba0860ed39111d9b63c692b3a0cf7d209
ocaml-multicore/tezos
test_proxy.ml
(*****************************************************************************) (* *) (* Open Source License *) Copyright ( c ) 2021 Nomadic Labs < > (* *) (* 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. *) (* *) (*****************************************************************************) (** Testing ------- Component: Client Invocation: dune build @src/proto_alpha/lib_client/runtest Subject: Test of --mode proxy and tezos-proxy-server heuristic *) let proxy_mode_gen = QCheck2.Gen.oneofl Tezos_proxy.Proxy.[Client; Server] let key_gen : string list QCheck2.Gen.t = (* Segments taken from the implementation of split_key in src/proto_alpha/lib_client/proxy.ml *) let keys = QCheck2.Gen.oneofl [ "big_maps"; "index"; "contents"; "contracts"; "cycle"; "cycle"; "rolls"; "owner"; "snapshot"; "v1"; ] |> QCheck2.Gen.list in QCheck2.Gen.frequency QCheck2.Gen.[(9, keys); (1, list string)] (** Whether [t1] is a prefix of [t2] *) let rec is_prefix t1 t2 = match (t1, t2) with | ([], _) -> true | (_, []) -> false | (x1 :: rest1, x2 :: rest2) when x1 = x2 -> is_prefix rest1 rest2 | _ -> false let test_split_key = let fmt = let pp_sep fmt () = Format.fprintf fmt "/" in Format.pp_print_list ~pp_sep Format.pp_print_string in QCheck2.Test.make ~name:"[fst (split_key s)] is a prefix of [s]" QCheck2.Gen.(pair proxy_mode_gen key_gen) @@ fun (mode, key) -> match Proxy.ProtoRpc.split_key mode key with | None -> true | Some (shorter, _) -> if is_prefix shorter key then true else QCheck2.Test.fail_reportf "Expected result of split_key to be a prefix of the input key. But \ %a is not a prefix of %a." fmt shorter fmt key let () = Alcotest.run "tezos-lib-client-proxy" [("proxy", Lib_test.Qcheck_helpers.qcheck_wrap [test_split_key])]
null
https://raw.githubusercontent.com/ocaml-multicore/tezos/e4fd21a1cb02d194b3162ab42d512b7c985ee8a9/src/proto_012_Psithaca/lib_client/test/test_proxy.ml
ocaml
*************************************************************************** Open Source License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), the rights to use, copy, modify, merge, publish, distribute, sublicense, Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *************************************************************************** * Testing ------- Component: Client Invocation: dune build @src/proto_alpha/lib_client/runtest Subject: Test of --mode proxy and tezos-proxy-server heuristic Segments taken from the implementation of split_key in src/proto_alpha/lib_client/proxy.ml * Whether [t1] is a prefix of [t2]
Copyright ( c ) 2021 Nomadic Labs < > to deal in the Software without restriction , including without limitation and/or sell copies of the Software , and to permit persons to whom the THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING let proxy_mode_gen = QCheck2.Gen.oneofl Tezos_proxy.Proxy.[Client; Server] let key_gen : string list QCheck2.Gen.t = let keys = QCheck2.Gen.oneofl [ "big_maps"; "index"; "contents"; "contracts"; "cycle"; "cycle"; "rolls"; "owner"; "snapshot"; "v1"; ] |> QCheck2.Gen.list in QCheck2.Gen.frequency QCheck2.Gen.[(9, keys); (1, list string)] let rec is_prefix t1 t2 = match (t1, t2) with | ([], _) -> true | (_, []) -> false | (x1 :: rest1, x2 :: rest2) when x1 = x2 -> is_prefix rest1 rest2 | _ -> false let test_split_key = let fmt = let pp_sep fmt () = Format.fprintf fmt "/" in Format.pp_print_list ~pp_sep Format.pp_print_string in QCheck2.Test.make ~name:"[fst (split_key s)] is a prefix of [s]" QCheck2.Gen.(pair proxy_mode_gen key_gen) @@ fun (mode, key) -> match Proxy.ProtoRpc.split_key mode key with | None -> true | Some (shorter, _) -> if is_prefix shorter key then true else QCheck2.Test.fail_reportf "Expected result of split_key to be a prefix of the input key. But \ %a is not a prefix of %a." fmt shorter fmt key let () = Alcotest.run "tezos-lib-client-proxy" [("proxy", Lib_test.Qcheck_helpers.qcheck_wrap [test_split_key])]
1c42e7f0d8760ff5188611f2dd0fb2d6d2f25d637f6bd4afb2c978d6e94c8ccd
ocaml-multicore/tezos
alpha_services.ml
(*****************************************************************************) (* *) (* Open Source License *) Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < > Copyright ( c ) 2019 - 2020 Nomadic Labs < > (* *) (* 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. *) (* *) (*****************************************************************************) open Alpha_context let custom_root = RPC_path.open_root module Seed = struct module S = struct open Data_encoding let seed = RPC_service.post_service ~description:"Seed of the cycle to which the block belongs." ~query:RPC_query.empty ~input:empty ~output:Seed.seed_encoding RPC_path.(custom_root / "context" / "seed") end let () = let open Services_registration in register0 ~chunked:false S.seed (fun ctxt () () -> let l = Level.current ctxt in Seed.for_cycle ctxt l.cycle) let get ctxt block = RPC_context.make_call0 S.seed ctxt block () () end module Nonce = struct type info = Revealed of Nonce.t | Missing of Nonce_hash.t | Forgotten let info_encoding = let open Data_encoding in union [ case (Tag 0) ~title:"Revealed" (obj1 (req "nonce" Nonce.encoding)) (function Revealed nonce -> Some nonce | _ -> None) (fun nonce -> Revealed nonce); case (Tag 1) ~title:"Missing" (obj1 (req "hash" Nonce_hash.encoding)) (function Missing nonce -> Some nonce | _ -> None) (fun nonce -> Missing nonce); case (Tag 2) ~title:"Forgotten" empty (function Forgotten -> Some () | _ -> None) (fun () -> Forgotten); ] module S = struct let get = RPC_service.get_service ~description:"Info about the nonce of a previous block." ~query:RPC_query.empty ~output:info_encoding RPC_path.(custom_root / "context" / "nonces" /: Raw_level.rpc_arg) end let register () = let open Services_registration in register1 ~chunked:false S.get (fun ctxt raw_level () () -> let level = Level.from_raw ctxt raw_level in Nonce.get ctxt level >|= function | Ok (Revealed nonce) -> ok (Revealed nonce) | Ok (Unrevealed {nonce_hash; _}) -> ok (Missing nonce_hash) | Error _ -> ok Forgotten) let get ctxt block level = RPC_context.make_call1 S.get ctxt block level () () end module Contract = Contract_services module Constants = Constants_services module Delegate = Delegate_services module Voting = Voting_services module Sapling = Sapling_services module Liquidity_baking = struct module S = struct let get_cpmm_address = RPC_service.get_service ~description:"Liquidity baking CPMM address" ~query:RPC_query.empty ~output:Alpha_context.Contract.encoding RPC_path.(custom_root / "context" / "liquidity_baking" / "cpmm_address") end let register () = let open Services_registration in register0 ~chunked:false S.get_cpmm_address (fun ctxt () () -> Alpha_context.Liquidity_baking.get_cpmm_address ctxt) let get_cpmm_address ctxt block = RPC_context.make_call0 S.get_cpmm_address ctxt block () () end module Cache = struct module S = struct let cached_contracts = RPC_service.get_service ~description:"Return the list of cached contracts" ~query:RPC_query.empty ~output: Data_encoding.(list @@ tup2 Alpha_context.Contract.encoding int31) RPC_path.(custom_root / "context" / "cache" / "contracts" / "all") let contract_cache_size = RPC_service.get_service ~description:"Return the size of the contract cache" ~query:RPC_query.empty ~output:Data_encoding.int31 RPC_path.(custom_root / "context" / "cache" / "contracts" / "size") let contract_cache_size_limit = RPC_service.get_service ~description:"Return the size limit of the contract cache" ~query:RPC_query.empty ~output:Data_encoding.int31 RPC_path.( custom_root / "context" / "cache" / "contracts" / "size_limit") let contract_rank = RPC_service.post_service ~description: "Return the number of cached contracts older than the provided \ contract" ~query:RPC_query.empty ~input:Alpha_context.Contract.encoding ~output:Data_encoding.(option int31) RPC_path.(custom_root / "context" / "cache" / "contracts" / "rank") end let register () = let open Services_registration in register0 ~chunked:true S.cached_contracts (fun ctxt () () -> Script_cache.entries ctxt |> Lwt.return) ; register0 ~chunked:false S.contract_cache_size (fun ctxt () () -> Script_cache.size ctxt |> return) ; register0 ~chunked:false S.contract_cache_size_limit (fun ctxt () () -> Script_cache.size_limit ctxt |> return) ; register0 ~chunked:false S.contract_rank (fun ctxt () contract -> Script_cache.contract_rank ctxt contract |> return) let cached_contracts ctxt block = RPC_context.make_call0 S.cached_contracts ctxt block () () let contract_cache_size ctxt block = RPC_context.make_call0 S.contract_cache_size ctxt block () () let contract_cache_size_limit ctxt block = RPC_context.make_call0 S.contract_cache_size_limit ctxt block () () let contract_rank ctxt block contract = RPC_context.make_call0 S.contract_rank ctxt block () contract end let register () = Contract.register () ; Constants.register () ; Delegate.register () ; Nonce.register () ; Voting.register () ; Sapling.register () ; Liquidity_baking.register () ; Cache.register ()
null
https://raw.githubusercontent.com/ocaml-multicore/tezos/e4fd21a1cb02d194b3162ab42d512b7c985ee8a9/src/proto_012_Psithaca/lib_protocol/alpha_services.ml
ocaml
*************************************************************************** Open Source License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), the rights to use, copy, modify, merge, publish, distribute, sublicense, Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************
Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < > Copyright ( c ) 2019 - 2020 Nomadic Labs < > to deal in the Software without restriction , including without limitation and/or sell copies of the Software , and to permit persons to whom the THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING open Alpha_context let custom_root = RPC_path.open_root module Seed = struct module S = struct open Data_encoding let seed = RPC_service.post_service ~description:"Seed of the cycle to which the block belongs." ~query:RPC_query.empty ~input:empty ~output:Seed.seed_encoding RPC_path.(custom_root / "context" / "seed") end let () = let open Services_registration in register0 ~chunked:false S.seed (fun ctxt () () -> let l = Level.current ctxt in Seed.for_cycle ctxt l.cycle) let get ctxt block = RPC_context.make_call0 S.seed ctxt block () () end module Nonce = struct type info = Revealed of Nonce.t | Missing of Nonce_hash.t | Forgotten let info_encoding = let open Data_encoding in union [ case (Tag 0) ~title:"Revealed" (obj1 (req "nonce" Nonce.encoding)) (function Revealed nonce -> Some nonce | _ -> None) (fun nonce -> Revealed nonce); case (Tag 1) ~title:"Missing" (obj1 (req "hash" Nonce_hash.encoding)) (function Missing nonce -> Some nonce | _ -> None) (fun nonce -> Missing nonce); case (Tag 2) ~title:"Forgotten" empty (function Forgotten -> Some () | _ -> None) (fun () -> Forgotten); ] module S = struct let get = RPC_service.get_service ~description:"Info about the nonce of a previous block." ~query:RPC_query.empty ~output:info_encoding RPC_path.(custom_root / "context" / "nonces" /: Raw_level.rpc_arg) end let register () = let open Services_registration in register1 ~chunked:false S.get (fun ctxt raw_level () () -> let level = Level.from_raw ctxt raw_level in Nonce.get ctxt level >|= function | Ok (Revealed nonce) -> ok (Revealed nonce) | Ok (Unrevealed {nonce_hash; _}) -> ok (Missing nonce_hash) | Error _ -> ok Forgotten) let get ctxt block level = RPC_context.make_call1 S.get ctxt block level () () end module Contract = Contract_services module Constants = Constants_services module Delegate = Delegate_services module Voting = Voting_services module Sapling = Sapling_services module Liquidity_baking = struct module S = struct let get_cpmm_address = RPC_service.get_service ~description:"Liquidity baking CPMM address" ~query:RPC_query.empty ~output:Alpha_context.Contract.encoding RPC_path.(custom_root / "context" / "liquidity_baking" / "cpmm_address") end let register () = let open Services_registration in register0 ~chunked:false S.get_cpmm_address (fun ctxt () () -> Alpha_context.Liquidity_baking.get_cpmm_address ctxt) let get_cpmm_address ctxt block = RPC_context.make_call0 S.get_cpmm_address ctxt block () () end module Cache = struct module S = struct let cached_contracts = RPC_service.get_service ~description:"Return the list of cached contracts" ~query:RPC_query.empty ~output: Data_encoding.(list @@ tup2 Alpha_context.Contract.encoding int31) RPC_path.(custom_root / "context" / "cache" / "contracts" / "all") let contract_cache_size = RPC_service.get_service ~description:"Return the size of the contract cache" ~query:RPC_query.empty ~output:Data_encoding.int31 RPC_path.(custom_root / "context" / "cache" / "contracts" / "size") let contract_cache_size_limit = RPC_service.get_service ~description:"Return the size limit of the contract cache" ~query:RPC_query.empty ~output:Data_encoding.int31 RPC_path.( custom_root / "context" / "cache" / "contracts" / "size_limit") let contract_rank = RPC_service.post_service ~description: "Return the number of cached contracts older than the provided \ contract" ~query:RPC_query.empty ~input:Alpha_context.Contract.encoding ~output:Data_encoding.(option int31) RPC_path.(custom_root / "context" / "cache" / "contracts" / "rank") end let register () = let open Services_registration in register0 ~chunked:true S.cached_contracts (fun ctxt () () -> Script_cache.entries ctxt |> Lwt.return) ; register0 ~chunked:false S.contract_cache_size (fun ctxt () () -> Script_cache.size ctxt |> return) ; register0 ~chunked:false S.contract_cache_size_limit (fun ctxt () () -> Script_cache.size_limit ctxt |> return) ; register0 ~chunked:false S.contract_rank (fun ctxt () contract -> Script_cache.contract_rank ctxt contract |> return) let cached_contracts ctxt block = RPC_context.make_call0 S.cached_contracts ctxt block () () let contract_cache_size ctxt block = RPC_context.make_call0 S.contract_cache_size ctxt block () () let contract_cache_size_limit ctxt block = RPC_context.make_call0 S.contract_cache_size_limit ctxt block () () let contract_rank ctxt block contract = RPC_context.make_call0 S.contract_rank ctxt block () contract end let register () = Contract.register () ; Constants.register () ; Delegate.register () ; Nonce.register () ; Voting.register () ; Sapling.register () ; Liquidity_baking.register () ; Cache.register ()
617e2f52ca2ee3a66b55f27488e2daa7969375913a3a48e8f55f0044a0932454
raaz-crypto/raaz
CPortable.hs
{-# LANGUAGE DataKinds #-} | The portable C - implementation of Poly1305 . module Poly1305.CPortable ( name, primName, description , Prim, Internals, BufferAlignment , BufferPtr , additionalBlocks , processBlocks , processLast , Key(..) ) where import Raaz.Core import Raaz.Core.Types.Internal import Raaz.Core.Transfer.Unsafe import Raaz.Primitive.Poly1305.Internal import Poly1305.Memory import Raaz.Verse.Poly1305.C.Portable name :: String name = "libverse-c" primName :: String primName = "poly1305" description :: String description = "Poly1305 Implementation in C exposed by libverse" type Prim = Poly1305 type Internals = Mem type BufferAlignment = 32 type BufferPtr = AlignedBlockPtr BufferAlignment Prim additionalBlocks :: BlockCount Poly1305 additionalBlocks = blocksOf 1 Proxy -- | Incrementally process poly1305 blocks. processBlocks :: BufferPtr -> BlockCount Poly1305 -> Internals -> IO () processBlocks buf blks = withAccumR $ runWithBlocks verse_poly1305_c_portable_incremental buf blks -- | Process a message that is exactly a multiple of the blocks. blocksMac :: BufferPtr -> BlockCount Poly1305 -> Internals -> IO () blocksMac buf blks = withAccumRS $ runWithBlocks verse_poly1305_c_portable_blockmac buf blks -- | Run an IO action with the pointers to the element, r and s cells. withAccumRS :: ( Ptr Element -> Ptr (Tuple 2 Word64) -> Ptr (Tuple 2 Word64) -> a ) -> Internals -> a withAccumRS func mem = withAccumR func mem $ sKeyPtr mem withAccumR :: ( Ptr Element -> Ptr (Tuple 2 Word64) -> a ) -> Internals -> a withAccumR func mem = func (accumPtr mem) $ rKeyPtr mem runWithBlocks :: ( Ptr a -> Word64 -> b ) -> BufferPtr -> BlockCount Poly1305 -> b runWithBlocks func buf = unsafeWithPointerCast func buf . toEnum . fromEnum -- | Process a message that has its last block incomplete. The total -- blocks argument here is the greatest multiple of the block that is -- less that the message length. partialBlockMac :: BufferPtr -> BlockCount Poly1305 -> Internals -> IO () partialBlockMac buf blks mem = do processBlocks buf blks mem withAccumRS (unsafeWithPointerCast partialMac buf) mem where partialMac bufPtr = verse_poly1305_c_portable_partialmac (bufPtr `movePtr` blks) -- | Process the last bytes. processLast :: BufferPtr -> BYTES Int -> Internals -> IO () processLast buf nBytes mem | blksC == blksF = blocksMac buf blksC mem | otherwise = do unsafeTransfer pad (forgetAlignment buf) partialBlockMac buf blksF mem where blksC = atLeast nBytes :: BlockCount Poly1305 blksF = atMost nBytes :: BlockCount Poly1305 pad = padding nBytes -- | Poly1305 padding. Call this padding function if and only if the -- message is not a multiple of the block length. padding :: BYTES Int -- Data in buffer. -> WriteTo padding mLen = padWrite 0 boundary $ skip mLen `mappend` one where one = writeStorable (1::Word8) boundary = blocksOf 1 (Proxy :: Proxy Poly1305)
null
https://raw.githubusercontent.com/raaz-crypto/raaz/1d17ead6d33c5441a59dbc4ff33197e2bd6eb6ec/implementation/Poly1305/CPortable.hs
haskell
# LANGUAGE DataKinds # | Incrementally process poly1305 blocks. | Process a message that is exactly a multiple of the blocks. | Run an IO action with the pointers to the element, r and s cells. | Process a message that has its last block incomplete. The total blocks argument here is the greatest multiple of the block that is less that the message length. | Process the last bytes. | Poly1305 padding. Call this padding function if and only if the message is not a multiple of the block length. Data in buffer.
| The portable C - implementation of Poly1305 . module Poly1305.CPortable ( name, primName, description , Prim, Internals, BufferAlignment , BufferPtr , additionalBlocks , processBlocks , processLast , Key(..) ) where import Raaz.Core import Raaz.Core.Types.Internal import Raaz.Core.Transfer.Unsafe import Raaz.Primitive.Poly1305.Internal import Poly1305.Memory import Raaz.Verse.Poly1305.C.Portable name :: String name = "libverse-c" primName :: String primName = "poly1305" description :: String description = "Poly1305 Implementation in C exposed by libverse" type Prim = Poly1305 type Internals = Mem type BufferAlignment = 32 type BufferPtr = AlignedBlockPtr BufferAlignment Prim additionalBlocks :: BlockCount Poly1305 additionalBlocks = blocksOf 1 Proxy processBlocks :: BufferPtr -> BlockCount Poly1305 -> Internals -> IO () processBlocks buf blks = withAccumR $ runWithBlocks verse_poly1305_c_portable_incremental buf blks blocksMac :: BufferPtr -> BlockCount Poly1305 -> Internals -> IO () blocksMac buf blks = withAccumRS $ runWithBlocks verse_poly1305_c_portable_blockmac buf blks withAccumRS :: ( Ptr Element -> Ptr (Tuple 2 Word64) -> Ptr (Tuple 2 Word64) -> a ) -> Internals -> a withAccumRS func mem = withAccumR func mem $ sKeyPtr mem withAccumR :: ( Ptr Element -> Ptr (Tuple 2 Word64) -> a ) -> Internals -> a withAccumR func mem = func (accumPtr mem) $ rKeyPtr mem runWithBlocks :: ( Ptr a -> Word64 -> b ) -> BufferPtr -> BlockCount Poly1305 -> b runWithBlocks func buf = unsafeWithPointerCast func buf . toEnum . fromEnum partialBlockMac :: BufferPtr -> BlockCount Poly1305 -> Internals -> IO () partialBlockMac buf blks mem = do processBlocks buf blks mem withAccumRS (unsafeWithPointerCast partialMac buf) mem where partialMac bufPtr = verse_poly1305_c_portable_partialmac (bufPtr `movePtr` blks) processLast :: BufferPtr -> BYTES Int -> Internals -> IO () processLast buf nBytes mem | blksC == blksF = blocksMac buf blksC mem | otherwise = do unsafeTransfer pad (forgetAlignment buf) partialBlockMac buf blksF mem where blksC = atLeast nBytes :: BlockCount Poly1305 blksF = atMost nBytes :: BlockCount Poly1305 pad = padding nBytes -> WriteTo padding mLen = padWrite 0 boundary $ skip mLen `mappend` one where one = writeStorable (1::Word8) boundary = blocksOf 1 (Proxy :: Proxy Poly1305)
526562ab07305e00041e2b455ae815da4f3d2a9c790d1284f73afa0e9ffc01aa
shrdlu68/cl-tls
crypto.lisp
(in-package :cl-tls) P_hash(secret , seed ) = HMAC_hash(secret , A(1 ) + seed ) + ;; HMAC_hash(secret, A(2) + seed) + ;; HMAC_hash(secret, A(3) + seed) + ... ;; A() ;; A(0) = seed ;; A(i) = HMAC_hash(secret, A(i-1)) (defun p-hash (secret data output-length &optional (digest-algorithm :sha256)) (let ((output (make-array output-length :element-type 'octet))) (loop with digest-size = (ironclad:digest-length digest-algorithm) for hmac = (ironclad:make-hmac secret digest-algorithm) then (reinitialize-instance hmac :key secret) for A = (progn (ironclad:update-hmac hmac data) (ironclad:hmac-digest hmac)) then (progn (ironclad:update-hmac hmac A) (ironclad:hmac-digest hmac)) for output-offset = 0 then (+ output-offset digest-size) while (< output-offset output-length) do (setf hmac (reinitialize-instance hmac :key secret)) (ironclad:update-hmac hmac (cat-vectors A data)) (replace output (ironclad:hmac-digest hmac) :start1 output-offset)) output)) (defun prf (secret label seed output-length) (p-hash secret (cat-vectors (ironclad:ascii-string-to-byte-array label) seed) output-length)) ;; master_secret = PRF(pre_master_secret, "master secret", ;; ClientHello.random + ServerHello.random) [ 0 .. 47 ] ; ;; key_block = PRF(SecurityParameters.master_secret, ;; "key expansion", ;; SecurityParameters.server_random + ;; SecurityParameters.client_random); (define-symbol-macro endpoint-encryption-key (if (eql role :client) client-write-key server-write-key)) (define-symbol-macro endpoint-decryption-key (if (eql role :client) server-write-key client-write-key)) (defun gen-key-material (client) "Generate the session keying material" (with-slots (master-secret pre-master-secret client-random server-random mac-key-length enc-key-length role record-iv-length client-write-mac-key server-write-mac-key client-write-key server-write-key client-write-iv server-write-iv cipher-type encryption-algorithm encrypting-cipher-object decrypting-cipher-object) client (setf master-secret (prf pre-master-secret "master secret" (cat-vectors client-random server-random) 48)) Spec recommends this (fill pre-master-secret #x0) (setf pre-master-secret nil) (let ((key-block (prf master-secret "key expansion" (cat-vectors server-random client-random) (* 2 (+ mac-key-length enc-key-length record-iv-length)))) (key-offset 0)) (setf client-write-mac-key (subseq key-block key-offset mac-key-length)) (incf key-offset mac-key-length) (setf server-write-mac-key (subseq key-block key-offset (+ key-offset mac-key-length))) (incf key-offset mac-key-length) (setf client-write-key (subseq key-block key-offset (+ key-offset enc-key-length))) (incf key-offset enc-key-length) (setf server-write-key (subseq key-block key-offset (+ key-offset enc-key-length))) (incf key-offset enc-key-length) (when (eql cipher-type :block) (setf client-write-iv (subseq key-block key-offset (+ key-offset record-iv-length))) (incf key-offset record-iv-length) (setf server-write-iv (subseq key-block key-offset (+ key-offset record-iv-length))))) ;; (format t "~&Client-write-mac-key: ~S~%" client-write-mac-key) ;; (format t "~&Server-write-mac-key: ~S~%" server-write-mac-key) ;; (format t "~&Client-write-key: ~S~%" client-write-key) ;; (format t "~&Server-write-key: ~S~%" server-write-key) ;; (format t "~&Client-write-iv: ~S~%" client-write-iv) ;; (format t "~&Server-write-iv: ~S~%" server-write-iv) ;; Stream ciphers such as RC4 need to store a cipher state (when (eql encryption-algorithm :rc4) (setf encrypting-cipher-object (ironclad:make-cipher :arcfour :key endpoint-encryption-key :mode :stream)) (setf decrypting-cipher-object (ironclad:make-cipher :arcfour :key endpoint-decryption-key :mode :stream))))) ;; struct { ;; SignatureAndHashAlgorithm algorithm; opaque signature<0 .. 2 ^ 16 - 1 > ; } DigitallySigned ; (defun digitally-sign (session data) "Create a digitally-signed-struct" (with-slots (extensions-data authentication-method client-random server-random key-exchange-method priv-key supported-sig-algos certificate) session (let* ((supported-signature-algorithms (supported-signature-algorithms extensions-data)) (algos (or (loop for sig in supported-sig-algos when (eql (second sig) (first (getf (subject-pki (tbs-certificate (x509-decode (first certificate)))) :algorithm-identifier))) return sig) (or (and supported-signature-algorithms (loop for sig in supported-signature-algorithms do (when (eql (second sig) authentication-method) (return sig)))) (cond ((and (member key-exchange-method '(:rsa :dhe :dh :ecdh :ecdhe)) (member authentication-method '(:rsa :psk ))) '(:sha1 :rsa)) ((and (member key-exchange-method '(:dh :dhe)) (eql authentication-method :dsa)) '(:sha1 :dsa)) ((and (member key-exchange-method '(:ecdh :ecdhe)) (eql authentication-method :dsa)) '(:sha1 :ecdsa))))))) (destructuring-bind (hash-algorithm signature-algorithm) algos (fast-io:with-fast-output (out) (fast-io:fast-write-byte (ecase hash-algorithm (:md5 1) (:sha1 2) (:sha224 3) (:sha256 4) (:sha384 5) (:sha512 6)) out) (fast-io:fast-write-byte (case signature-algorithm (:rsa 1) (:dsa 2) (:ecdsa 3)) out) (case signature-algorithm (:dsa (let* ((digest (ironclad:digest-sequence (first algos) data)) (raw-signature (ironclad:destructure-signature :dsa (ironclad:sign-message priv-key digest))) (signature (create-asn-sequence (list (getf raw-signature :r) :integer) (list (getf raw-signature :s) :integer)))) (fast-io:writeu16-be (length signature) out) (fast-io:fast-write-sequence signature out))) (:rsa (let ((signature (rsassa-pkcs1.5-sign priv-key data hash-algorithm))) (fast-io:writeu16-be (length signature) out) (fast-io:fast-write-sequence signature out))) (:ecdsa TODO ))))))) (defun verify-signed-data (session data algorithm signature) (with-slots (pub-key) session (flet ((fail () (return-from verify-signed-data nil))) (let ((hash-alg (case (aref algorithm 0) (1 :md5) (2 :sha1) (3 :sha224) (4 :sha256) (5 :sha384) (6 :sha512) (otherwise (fail)))) (signature-alg (case (aref algorithm 1) (1 :rsa) (2 :dsa) (3 :ecdsa) (otherwise (fail))))) (case signature-alg (:dsa (let ((digest (ironclad:digest-sequence hash-alg data))) (multiple-value-bind (type contents) (parse-der signature) (unless (and (eql type :sequence) (= (length contents) 2) (every (lambda (arg) (asn-type-matches-p :integer arg)) contents)) (fail)) (destructuring-bind (r s) contents (ironclad:verify-signature pub-key digest (ironclad:make-signature :dsa :r (second r) :s (second s))))))) (:rsa (rsassa-pkcs1.5-verify pub-key data signature hash-alg)) (:ecdsa TODO nil)))))) (defun sign-dh-params (session params) (with-slots (client-random server-random) session (let ((data (cat-vectors client-random server-random params))) (digitally-sign session data)))) (defun verify-signed-params (session dh-params algorithm signature) (with-slots (client-random server-random) session (let ((data (cat-vectors client-random server-random dh-params))) (verify-signed-data session data algorithm signature))))
null
https://raw.githubusercontent.com/shrdlu68/cl-tls/dd8d73e9b77d15e3e1a0a9e8ecace83352aac359/src/tls/crypto.lisp
lisp
HMAC_hash(secret, A(2) + seed) + HMAC_hash(secret, A(3) + seed) + ... A() A(0) = seed A(i) = HMAC_hash(secret, A(i-1)) master_secret = PRF(pre_master_secret, "master secret", ClientHello.random + ServerHello.random) key_block = PRF(SecurityParameters.master_secret, "key expansion", SecurityParameters.server_random + SecurityParameters.client_random); (format t "~&Client-write-mac-key: ~S~%" client-write-mac-key) (format t "~&Server-write-mac-key: ~S~%" server-write-mac-key) (format t "~&Client-write-key: ~S~%" client-write-key) (format t "~&Server-write-key: ~S~%" server-write-key) (format t "~&Client-write-iv: ~S~%" client-write-iv) (format t "~&Server-write-iv: ~S~%" server-write-iv) Stream ciphers such as RC4 need to store a cipher state struct { SignatureAndHashAlgorithm algorithm;
(in-package :cl-tls) P_hash(secret , seed ) = HMAC_hash(secret , A(1 ) + seed ) + (defun p-hash (secret data output-length &optional (digest-algorithm :sha256)) (let ((output (make-array output-length :element-type 'octet))) (loop with digest-size = (ironclad:digest-length digest-algorithm) for hmac = (ironclad:make-hmac secret digest-algorithm) then (reinitialize-instance hmac :key secret) for A = (progn (ironclad:update-hmac hmac data) (ironclad:hmac-digest hmac)) then (progn (ironclad:update-hmac hmac A) (ironclad:hmac-digest hmac)) for output-offset = 0 then (+ output-offset digest-size) while (< output-offset output-length) do (setf hmac (reinitialize-instance hmac :key secret)) (ironclad:update-hmac hmac (cat-vectors A data)) (replace output (ironclad:hmac-digest hmac) :start1 output-offset)) output)) (defun prf (secret label seed output-length) (p-hash secret (cat-vectors (ironclad:ascii-string-to-byte-array label) seed) output-length)) (define-symbol-macro endpoint-encryption-key (if (eql role :client) client-write-key server-write-key)) (define-symbol-macro endpoint-decryption-key (if (eql role :client) server-write-key client-write-key)) (defun gen-key-material (client) "Generate the session keying material" (with-slots (master-secret pre-master-secret client-random server-random mac-key-length enc-key-length role record-iv-length client-write-mac-key server-write-mac-key client-write-key server-write-key client-write-iv server-write-iv cipher-type encryption-algorithm encrypting-cipher-object decrypting-cipher-object) client (setf master-secret (prf pre-master-secret "master secret" (cat-vectors client-random server-random) 48)) Spec recommends this (fill pre-master-secret #x0) (setf pre-master-secret nil) (let ((key-block (prf master-secret "key expansion" (cat-vectors server-random client-random) (* 2 (+ mac-key-length enc-key-length record-iv-length)))) (key-offset 0)) (setf client-write-mac-key (subseq key-block key-offset mac-key-length)) (incf key-offset mac-key-length) (setf server-write-mac-key (subseq key-block key-offset (+ key-offset mac-key-length))) (incf key-offset mac-key-length) (setf client-write-key (subseq key-block key-offset (+ key-offset enc-key-length))) (incf key-offset enc-key-length) (setf server-write-key (subseq key-block key-offset (+ key-offset enc-key-length))) (incf key-offset enc-key-length) (when (eql cipher-type :block) (setf client-write-iv (subseq key-block key-offset (+ key-offset record-iv-length))) (incf key-offset record-iv-length) (setf server-write-iv (subseq key-block key-offset (+ key-offset record-iv-length))))) (when (eql encryption-algorithm :rc4) (setf encrypting-cipher-object (ironclad:make-cipher :arcfour :key endpoint-encryption-key :mode :stream)) (setf decrypting-cipher-object (ironclad:make-cipher :arcfour :key endpoint-decryption-key :mode :stream))))) (defun digitally-sign (session data) "Create a digitally-signed-struct" (with-slots (extensions-data authentication-method client-random server-random key-exchange-method priv-key supported-sig-algos certificate) session (let* ((supported-signature-algorithms (supported-signature-algorithms extensions-data)) (algos (or (loop for sig in supported-sig-algos when (eql (second sig) (first (getf (subject-pki (tbs-certificate (x509-decode (first certificate)))) :algorithm-identifier))) return sig) (or (and supported-signature-algorithms (loop for sig in supported-signature-algorithms do (when (eql (second sig) authentication-method) (return sig)))) (cond ((and (member key-exchange-method '(:rsa :dhe :dh :ecdh :ecdhe)) (member authentication-method '(:rsa :psk ))) '(:sha1 :rsa)) ((and (member key-exchange-method '(:dh :dhe)) (eql authentication-method :dsa)) '(:sha1 :dsa)) ((and (member key-exchange-method '(:ecdh :ecdhe)) (eql authentication-method :dsa)) '(:sha1 :ecdsa))))))) (destructuring-bind (hash-algorithm signature-algorithm) algos (fast-io:with-fast-output (out) (fast-io:fast-write-byte (ecase hash-algorithm (:md5 1) (:sha1 2) (:sha224 3) (:sha256 4) (:sha384 5) (:sha512 6)) out) (fast-io:fast-write-byte (case signature-algorithm (:rsa 1) (:dsa 2) (:ecdsa 3)) out) (case signature-algorithm (:dsa (let* ((digest (ironclad:digest-sequence (first algos) data)) (raw-signature (ironclad:destructure-signature :dsa (ironclad:sign-message priv-key digest))) (signature (create-asn-sequence (list (getf raw-signature :r) :integer) (list (getf raw-signature :s) :integer)))) (fast-io:writeu16-be (length signature) out) (fast-io:fast-write-sequence signature out))) (:rsa (let ((signature (rsassa-pkcs1.5-sign priv-key data hash-algorithm))) (fast-io:writeu16-be (length signature) out) (fast-io:fast-write-sequence signature out))) (:ecdsa TODO ))))))) (defun verify-signed-data (session data algorithm signature) (with-slots (pub-key) session (flet ((fail () (return-from verify-signed-data nil))) (let ((hash-alg (case (aref algorithm 0) (1 :md5) (2 :sha1) (3 :sha224) (4 :sha256) (5 :sha384) (6 :sha512) (otherwise (fail)))) (signature-alg (case (aref algorithm 1) (1 :rsa) (2 :dsa) (3 :ecdsa) (otherwise (fail))))) (case signature-alg (:dsa (let ((digest (ironclad:digest-sequence hash-alg data))) (multiple-value-bind (type contents) (parse-der signature) (unless (and (eql type :sequence) (= (length contents) 2) (every (lambda (arg) (asn-type-matches-p :integer arg)) contents)) (fail)) (destructuring-bind (r s) contents (ironclad:verify-signature pub-key digest (ironclad:make-signature :dsa :r (second r) :s (second s))))))) (:rsa (rsassa-pkcs1.5-verify pub-key data signature hash-alg)) (:ecdsa TODO nil)))))) (defun sign-dh-params (session params) (with-slots (client-random server-random) session (let ((data (cat-vectors client-random server-random params))) (digitally-sign session data)))) (defun verify-signed-params (session dh-params algorithm signature) (with-slots (client-random server-random) session (let ((data (cat-vectors client-random server-random dh-params))) (verify-signed-data session data algorithm signature))))
7e099f6855c7da25945b7a3c7d4e12c4517f681f16e1c90c30c12885d4eb7d82
tbsschroeder/clojure-webshop-app
blocks.clj
(ns metro.components.web.blocks (:require [metro.components.db.articles :as article] [ring.util.response :as ring-resp] [hiccup.page :as hp])) (defn base-template [& body] (ring-resp/response (hp/html5 [:head [:title "Webshop"] [:meta {:charset "utf-8"}] [:meta {:http-equiv "X-UA-Compatible" :content "IE=edge"}] [:meta {:name "viewport" :content "width=device-width, initial-scale=1"}] [:link {:rel "icon" :href "img/shopping-cart.svg"}] (hp/include-css "css/bootstrap.min.css") (hp/include-css "css/custom.css") (hp/include-css "css/cat.css")] [:body [:div.container {:style "padding-top: 3rem"} body]]))) (defn- amount-btn [action id class value] [:form.amount-article-form {:action action :method :POST} [:input {:name "id" :value id :hidden true}] [:input {:class (str "btn " class) :type :submit :value value}]]) (defn- amount-input [article] [:div.form-group.count-input [:div.input-group [:div.input-group-prepend (amount-btn "/article/dec" (:id article) "btn-danger" "-")] [:input.form-control.input-number {:value (:count article) :width "3em" :disabled "true"}] [:div.input-group-append (amount-btn "/article/inc" (:id article) "btn-success" "+")]]]) (defn- 🐱 [] [:div.cat [:div.head [:div.face [:div.stripes [:div.top] [:div.left] [:div.right]] [:div.eyes [:div.left] [:div.right]] [:div.nose] [:div.mouth]] [:div.ears [:div.left] [:div.right]]] [:div.suit [:div.collar [:div.top]] [:div.arms [:div.left] [:div.right]] [:div.paws [:div.left] [:div.right]] [:div.body]] [:div.tail] [:div.shadow]]) (defn article->big-cards [] (for [article (sort-by :title (article/query-all))] [:div.card.mb-3 [:h3.card-header (:title article)] [:div.card-body [:h6.card-subtitle.text-muted (:category article)]] [:img.big {:src (:image article) :alt "article image"}] [:div.card-body [:p.card-text (:description article)] [:a.card-link {:href "#"} "More"] (amount-input article)]])) (defn article->small-cards [] (for [article (sort-by :title (article/query-all))] [:div.card.text-white.bg-secondary.mb-3 [:div.card-header [:h4 (:title article)]] [:div.card-body [:p.card-text (:description article)] [:img.small {:src (:image article)}] (amount-input article)]])) (defn article->checkout [] (for [article (sort-by (juxt :category :title) (article/query-all-with-count))] [:tr [:td (:category article)] [:td (:title article)] [:td [:img.co-img {:src (:image article)}]] [:td [:strong {:class "text-warning"} (:count article)]] [:td (amount-btn "/article/rem" (:id article) "btn-warning btn-sm" "✘")]])) (defn checkout-table [] (if (article/has-articles-with-data?) [:table.table.table-striped.table-hover {:font-size ""} [:thead [:tr [:th "Category"] [:th "Article"] [:th "Image"] [:th "Count"] [:th "Remove"]]] (vec (conj (article->checkout) :tbody))] [:div [:h2.text-warning.center "Empty shopping cart! Manager cat is not amused!"] (🐱)])) (defn button->checkout [] [:a.btn.btn-success.co-btn {:type "button" :href "/checkout"} [:img.co-btn-img {:src "img/shopping-cart.svg" :alt "cart"}] (str "Checkout (" (count (article/query-all-with-count)) ")")]) (defn button->buy-more [] [:a.btn.btn-success.buy-more-btn {:type "button" :href "/"} [:img.buy-more-btn-img {:src "img/shopping-cart.svg" :alt "cart"}] "Buy More"]) (defn text->pizza [] [:p.center "Made with \uD83C\uDF55 in Düsseldorf"])
null
https://raw.githubusercontent.com/tbsschroeder/clojure-webshop-app/dc57eecb19e09583cb5f08b65cbe0f01ceb87cf5/src/metro/components/web/blocks.clj
clojure
(ns metro.components.web.blocks (:require [metro.components.db.articles :as article] [ring.util.response :as ring-resp] [hiccup.page :as hp])) (defn base-template [& body] (ring-resp/response (hp/html5 [:head [:title "Webshop"] [:meta {:charset "utf-8"}] [:meta {:http-equiv "X-UA-Compatible" :content "IE=edge"}] [:meta {:name "viewport" :content "width=device-width, initial-scale=1"}] [:link {:rel "icon" :href "img/shopping-cart.svg"}] (hp/include-css "css/bootstrap.min.css") (hp/include-css "css/custom.css") (hp/include-css "css/cat.css")] [:body [:div.container {:style "padding-top: 3rem"} body]]))) (defn- amount-btn [action id class value] [:form.amount-article-form {:action action :method :POST} [:input {:name "id" :value id :hidden true}] [:input {:class (str "btn " class) :type :submit :value value}]]) (defn- amount-input [article] [:div.form-group.count-input [:div.input-group [:div.input-group-prepend (amount-btn "/article/dec" (:id article) "btn-danger" "-")] [:input.form-control.input-number {:value (:count article) :width "3em" :disabled "true"}] [:div.input-group-append (amount-btn "/article/inc" (:id article) "btn-success" "+")]]]) (defn- 🐱 [] [:div.cat [:div.head [:div.face [:div.stripes [:div.top] [:div.left] [:div.right]] [:div.eyes [:div.left] [:div.right]] [:div.nose] [:div.mouth]] [:div.ears [:div.left] [:div.right]]] [:div.suit [:div.collar [:div.top]] [:div.arms [:div.left] [:div.right]] [:div.paws [:div.left] [:div.right]] [:div.body]] [:div.tail] [:div.shadow]]) (defn article->big-cards [] (for [article (sort-by :title (article/query-all))] [:div.card.mb-3 [:h3.card-header (:title article)] [:div.card-body [:h6.card-subtitle.text-muted (:category article)]] [:img.big {:src (:image article) :alt "article image"}] [:div.card-body [:p.card-text (:description article)] [:a.card-link {:href "#"} "More"] (amount-input article)]])) (defn article->small-cards [] (for [article (sort-by :title (article/query-all))] [:div.card.text-white.bg-secondary.mb-3 [:div.card-header [:h4 (:title article)]] [:div.card-body [:p.card-text (:description article)] [:img.small {:src (:image article)}] (amount-input article)]])) (defn article->checkout [] (for [article (sort-by (juxt :category :title) (article/query-all-with-count))] [:tr [:td (:category article)] [:td (:title article)] [:td [:img.co-img {:src (:image article)}]] [:td [:strong {:class "text-warning"} (:count article)]] [:td (amount-btn "/article/rem" (:id article) "btn-warning btn-sm" "✘")]])) (defn checkout-table [] (if (article/has-articles-with-data?) [:table.table.table-striped.table-hover {:font-size ""} [:thead [:tr [:th "Category"] [:th "Article"] [:th "Image"] [:th "Count"] [:th "Remove"]]] (vec (conj (article->checkout) :tbody))] [:div [:h2.text-warning.center "Empty shopping cart! Manager cat is not amused!"] (🐱)])) (defn button->checkout [] [:a.btn.btn-success.co-btn {:type "button" :href "/checkout"} [:img.co-btn-img {:src "img/shopping-cart.svg" :alt "cart"}] (str "Checkout (" (count (article/query-all-with-count)) ")")]) (defn button->buy-more [] [:a.btn.btn-success.buy-more-btn {:type "button" :href "/"} [:img.buy-more-btn-img {:src "img/shopping-cart.svg" :alt "cart"}] "Buy More"]) (defn text->pizza [] [:p.center "Made with \uD83C\uDF55 in Düsseldorf"])
d2a1de9b58cd04c38cea5c1d0e41113d701745fa05e9a7d3d0aeb7c6db53a64c
robert-strandh/SICL
unintern-defun.lisp
(cl:in-package #:sicl-package) (defun unintern (symbol &optional (package-designator *package*)) (let ((package (package-designator-to-package package-designator)) (name (symbol-name symbol))) (if (symbol-is-present-p symbol package) (progn (remhash name (external-symbols package)) (remhash name (internal-symbols package)) (when (member symbol (shadowing-symbols package)) (setf (shadowing-symbols package) (remove symbol (shadowing-symbols package))) (let ((conflicts '())) (loop for used-package in (use-list package) do (multiple-value-bind (symbol present-p) (find-external-symbol name used-package) (when present-p (pushnew symbol conflicts :test #'eq)))) (when (> (length conflicts) 1) (let ((choice (resolve-conflict name package))) (setf (gethash name (internal-symbols package)) choice) (push choice (shadowing-symbols package)))))) t) nil)))
null
https://raw.githubusercontent.com/robert-strandh/SICL/65d7009247b856b2c0f3d9bb41ca7febd3cd641b/Code/Package/unintern-defun.lisp
lisp
(cl:in-package #:sicl-package) (defun unintern (symbol &optional (package-designator *package*)) (let ((package (package-designator-to-package package-designator)) (name (symbol-name symbol))) (if (symbol-is-present-p symbol package) (progn (remhash name (external-symbols package)) (remhash name (internal-symbols package)) (when (member symbol (shadowing-symbols package)) (setf (shadowing-symbols package) (remove symbol (shadowing-symbols package))) (let ((conflicts '())) (loop for used-package in (use-list package) do (multiple-value-bind (symbol present-p) (find-external-symbol name used-package) (when present-p (pushnew symbol conflicts :test #'eq)))) (when (> (length conflicts) 1) (let ((choice (resolve-conflict name package))) (setf (gethash name (internal-symbols package)) choice) (push choice (shadowing-symbols package)))))) t) nil)))
776f4fce20b6aa80d4707d8573aed07de8549584feb22b4d423f3bd23a36e03e
rems-project/cerberus
global_ocaml.mli
val (-|): ('b -> 'c) -> ('a -> 'b) -> 'a -> 'c type error_verbosity = | Basic (* similar to a normal compiler *) | RefStd (* add an std reference to Basic *) | QuoteStd (* print a full quote of the std text *) type execution_mode = | Exhaustive | Random type cerberus_conf = { backend_name: string; exec_mode_opt: execution_mode option; concurrency: bool; error_verbosity: error_verbosity; defacto: bool; allows GCC extensions and stuff agnostic: bool; n1570: Yojson.Basic.t option; } val (!!): (unit -> 'a) ref -> 'a val cerb_conf: (unit -> cerberus_conf) ref val set_cerb_conf: string -> bool -> execution_mode -> bool -> error_verbosity -> bool -> bool -> bool -> bool -> unit (* NOTE: used in driver.lem *) val current_execution_mode: unit -> execution_mode option val backend_name: unit -> string val concurrency_mode: unit -> bool val isDefacto: unit -> bool val isPermissive: unit -> bool val isAgnostic: unit -> bool NOTE : used in pp_errors.ml val verbose: unit -> error_verbosity val n1570: unit -> Yojson.Basic.t option print an error fatal message and exit with a given code ( default is 1 ) val error: ?code:int -> string -> 'a
null
https://raw.githubusercontent.com/rems-project/cerberus/09bd47db2de59c108ba488108561a34b659761c5/util/global_ocaml.mli
ocaml
similar to a normal compiler add an std reference to Basic print a full quote of the std text NOTE: used in driver.lem
val (-|): ('b -> 'c) -> ('a -> 'b) -> 'a -> 'c type error_verbosity = type execution_mode = | Exhaustive | Random type cerberus_conf = { backend_name: string; exec_mode_opt: execution_mode option; concurrency: bool; error_verbosity: error_verbosity; defacto: bool; allows GCC extensions and stuff agnostic: bool; n1570: Yojson.Basic.t option; } val (!!): (unit -> 'a) ref -> 'a val cerb_conf: (unit -> cerberus_conf) ref val set_cerb_conf: string -> bool -> execution_mode -> bool -> error_verbosity -> bool -> bool -> bool -> bool -> unit val current_execution_mode: unit -> execution_mode option val backend_name: unit -> string val concurrency_mode: unit -> bool val isDefacto: unit -> bool val isPermissive: unit -> bool val isAgnostic: unit -> bool NOTE : used in pp_errors.ml val verbose: unit -> error_verbosity val n1570: unit -> Yojson.Basic.t option print an error fatal message and exit with a given code ( default is 1 ) val error: ?code:int -> string -> 'a
f676a2c2514cb8ffdeb3efd2f669812fa0320c285d77f099ef2da8055455103d
gusbicalho/haskell-todo
UserSpec.hs
HLINT ignore " Redundant do " module HaskellTodo.Adapters.UserSpec (spec) where import Test.Hspec import qualified HaskellTodo.Adapters.User as A.User import qualified HaskellTodo.Models.User as M.User import qualified HaskellTodo.WireTypes.User as Wire.User spec :: Spec spec = do describe "toWire" $ do it "should adapt the User model to the User wire" $ A.User.toWire internalUser `shouldBe` wireUser describe "singleWire" $ do it "should adapt a single internal User to a wire SingleUser document" $ A.User.singleWire internalUser `shouldBe` Wire.User.SingleUser wireUser describe "manyWire" $ do it "should adapt a list of internal Users to a wire ManyUsers document" $ A.User.manyWire [internalUser, internalUser] `shouldBe` Wire.User.ManyUsers [wireUser, wireUser] describe "inputToNewUser" $ do it "should adapt a wire NewUserInput to an internal NewUser" $ A.User.inputToNewUser newUserInput `shouldBe` internalNewUser where internalUser = M.User.User 42 "foo" "bar" wireUser = Wire.User.User 42 "foo" newUserInput = Wire.User.NewUserInput "foo" "bar" internalNewUser = M.User.NewPlainUser "foo" "bar"
null
https://raw.githubusercontent.com/gusbicalho/haskell-todo/f28b0d05ddb72764cf01d29fa978457ac455ac81/test/HaskellTodo/Adapters/UserSpec.hs
haskell
HLINT ignore " Redundant do " module HaskellTodo.Adapters.UserSpec (spec) where import Test.Hspec import qualified HaskellTodo.Adapters.User as A.User import qualified HaskellTodo.Models.User as M.User import qualified HaskellTodo.WireTypes.User as Wire.User spec :: Spec spec = do describe "toWire" $ do it "should adapt the User model to the User wire" $ A.User.toWire internalUser `shouldBe` wireUser describe "singleWire" $ do it "should adapt a single internal User to a wire SingleUser document" $ A.User.singleWire internalUser `shouldBe` Wire.User.SingleUser wireUser describe "manyWire" $ do it "should adapt a list of internal Users to a wire ManyUsers document" $ A.User.manyWire [internalUser, internalUser] `shouldBe` Wire.User.ManyUsers [wireUser, wireUser] describe "inputToNewUser" $ do it "should adapt a wire NewUserInput to an internal NewUser" $ A.User.inputToNewUser newUserInput `shouldBe` internalNewUser where internalUser = M.User.User 42 "foo" "bar" wireUser = Wire.User.User 42 "foo" newUserInput = Wire.User.NewUserInput "foo" "bar" internalNewUser = M.User.NewPlainUser "foo" "bar"
4c666d11f93ae411aec4ce2c5c3ba517c5a37acaeaec94f977dc3662aeb36b4c
typelead/etlas
FetchUtils.hs
----------------------------------------------------------------------------- -- | Module : Distribution . Client . FetchUtils Copyright : ( c ) 2005 2011 -- License : BSD-like -- -- Maintainer : -- Stability : provisional -- Portability : portable -- -- Functions for fetching packages ----------------------------------------------------------------------------- # LANGUAGE RecordWildCards # module Distribution.Client.FetchUtils ( -- * fetching packages fetchPackage, isFetched, checkFetched, -- ** specifically for repo packages checkRepoTarballFetched, fetchRepoTarball, fetchSourceRepo, downloadSourceRepo, -- ** fetching packages asynchronously asyncFetchPackages, waitAsyncFetchPackage, AsyncFetchMap, -- * fetching other things downloadIndex, ) where import Distribution.Client.Types import {-# SOURCE #-} Distribution.Client.BinaryUtils import Distribution.Client.HttpUtils ( downloadURI, isOldHackageURI, DownloadResult(..) , HttpTransport(..), transportCheckHttps, remoteRepoCheckHttps ) import Distribution.Package ( PackageId, packageName, packageVersion ) import Distribution.Simple.Utils ( notice, info, debug, setupMessage ) import Distribution.Text ( display ) import Distribution.Verbosity ( Verbosity, verboseUnmarkOutput ) import Distribution.Client.GlobalFlags ( RepoContext(..) ) import Distribution.Client.Brancher import Distribution.Version import Distribution.Simple.Program import qualified Distribution.PackageDescription as PD import Data.Maybe import Data.Map (Map) import qualified Data.Map as Map import Control.Monad import Control.Exception import Control.Concurrent.Async import Control.Concurrent.MVar import System.Directory ( doesFileExist, createDirectoryIfMissing, getTemporaryDirectory, doesDirectoryExist ) import System.IO ( openTempFile, hClose ) import System.FilePath ( (</>), (<.>) ) import qualified System.FilePath.Posix as FilePath.Posix ( combine, joinPath ) import Network.URI ( URI(uriPath) ) import qualified Hackage.Security.Client as Sec -- ------------------------------------------------------------ -- * Actually fetch things -- ------------------------------------------------------------ -- | Returns @True@ if the package has already been fetched -- or does not need fetching. -- isFetched :: UnresolvedPkgLoc -> IO Bool isFetched loc = case loc of LocalUnpackedPackage _dir -> return True LocalTarballPackage _file _ -> return True RemoteTarballPackage _uri local -> return (isJust local) RepoTarballPackage repo pkgid _ -> doesFileExist (packageFile repo pkgid) ScmPackage (Just repo) _ pkgid _ -> doesDirectoryExist (packageDir repo pkgid) ScmPackage Nothing _ _pkgid _ -> error "isFetched: ScmPackage Nothing" -- | Checks if the package has already been fetched (or does not need -- fetching) and if so returns evidence in the form of a 'PackageLocation' -- with a resolved local file location. -- checkFetched :: UnresolvedPkgLoc -> IO (Maybe ResolvedPkgLoc) checkFetched loc = case loc of LocalUnpackedPackage dir -> return (Just $ LocalUnpackedPackage dir) LocalTarballPackage file isBinary -> return (Just $ LocalTarballPackage file isBinary) RemoteTarballPackage uri (Just file) -> return (Just $ RemoteTarballPackage uri file) RepoTarballPackage repo pkgid (Just file) -> return (Just $ RepoTarballPackage repo pkgid file) ScmPackage maybeRepo srcRepos pkgid (Just file) -> return (Just $ ScmPackage maybeRepo srcRepos pkgid file) RemoteTarballPackage _uri Nothing -> return Nothing RepoTarballPackage repo pkgid Nothing -> fmap (fmap (RepoTarballPackage repo pkgid)) (checkRepoTarballFetched repo pkgid) ScmPackage (Just repo) srcRepos pkgid Nothing -> do let dir = packageDir repo pkgid exists <- doesDirectoryExist dir if exists then return (Just $ ScmPackage (Just repo) srcRepos pkgid dir) else return Nothing ScmPackage Nothing _ _ Nothing -> error "checkFetched: ScmPackage Nothing" -- | Like 'checkFetched' but for the specific case of a 'RepoTarballPackage'. -- checkRepoTarballFetched :: Repo -> PackageId -> IO (Maybe FilePath) checkRepoTarballFetched repo pkgid = do let file = packageFile repo pkgid exists <- doesFileExist file if exists then return (Just file) else return Nothing -- | Fetch a package if we don't have it already. -- fetchPackage :: Verbosity -> RepoContext -> UnresolvedPkgLoc -> IO ResolvedPkgLoc fetchPackage verbosity repoCtxt loc = case loc of LocalUnpackedPackage dir -> return (LocalUnpackedPackage dir) LocalTarballPackage file isBinary -> return (LocalTarballPackage file isBinary) RemoteTarballPackage uri (Just file) -> return (RemoteTarballPackage uri file) RepoTarballPackage repo pkgid (Just file) -> return (RepoTarballPackage repo pkgid file) ScmPackage maybeRepo sourceRepos pkgid (Just file) -> return (ScmPackage maybeRepo sourceRepos pkgid file) RemoteTarballPackage uri Nothing -> do path <- downloadTarballPackage uri return (RemoteTarballPackage uri path) RepoTarballPackage repo pkgid Nothing -> do local <- fetchRepoTarball verbosity repoCtxt repo pkgid return (RepoTarballPackage repo pkgid local) ScmPackage (Just repo) sourceRepos pkgid Nothing -> do local <- fetchSourceRepo verbosity repo pkgid sourceRepos return (ScmPackage (Just repo) sourceRepos pkgid local) ScmPackage Nothing _ _ Nothing -> do error "fetchPackage: ScmPackage Nothing" where downloadTarballPackage uri = do transport <- repoContextGetTransport repoCtxt transportCheckHttps verbosity transport uri notice verbosity ("Downloading " ++ show uri) tmpdir <- getTemporaryDirectory (path, hnd) <- openTempFile tmpdir "etlas-.tar.gz" hClose hnd _ <- downloadURI transport verbosity uri path return path -- | Fetch a source control management repo package if we don't have it already. -- fetchSourceRepo :: Verbosity -> Repo -> PackageId -> [PD.SourceRepo] -> IO FilePath fetchSourceRepo verbosity repo pkgid sourceRepos = do fetched <- doesDirectoryExist repoDir if fetched then do info verbosity $ repoDir ++ " has already been downloaded." return repoDir else do notice verbosity $ "Downloading " ++ display pkgid ++ "..." downloadSourceRepo verbosity repoDir (Right pkgid) sourceRepos return repoDir where repoDir = packageDir repo pkgid downloadSourceRepo :: Verbosity -> FilePath -> Either String PackageId -> [PD.SourceRepo] -> IO () downloadSourceRepo verbosity targetDir ePkgDesc sourceRepos = do branchers <- findUsableBranchers forkPackage verbosity branchers targetDir Nothing ePkgDesc sourceRepos -- | Fetch a repo package if we don't have it already. -- fetchRepoTarball :: Verbosity -> RepoContext -> Repo -> PackageId -> IO FilePath fetchRepoTarball verbosity repoCtxt repo pkgid = do fetched <- doesFileExist (packageFile repo pkgid) if fetched then do info verbosity $ display pkgid ++ " has already been downloaded." return (packageFile repo pkgid) else do setupMessage verbosity "Downloading [source]" pkgid downloadRepoPackage where downloadRepoPackage = case repo of RepoLocal{..} -> return (packageFile repo pkgid) RepoRemote{..} -> do transport <- repoContextGetTransport repoCtxt remoteRepoCheckHttps verbosity transport repoRemote let uri = packageURI repoRemote pkgid dir = packageDir repo pkgid path = packageFile repo pkgid createDirectoryIfMissing True dir _ <- downloadURI transport verbosity uri path return path RepoSecure{} -> repoContextWithSecureRepo repoCtxt repo $ \rep -> do let dir = packageDir repo pkgid path = packageFile repo pkgid createDirectoryIfMissing True dir Sec.uncheckClientErrors $ do info verbosity ("writing " ++ path) Sec.downloadPackage' rep pkgid path return path -- | Downloads an index file to [config-dir/packages/serv-id] without -- hackage-security. You probably don't want to call this directly; -- use 'updateRepo' instead. -- downloadIndex :: Verbosity -> HttpTransport -> RemoteRepo -> FilePath -> FilePath -> IO DownloadResult downloadIndex verbosity transport remoteRepo cacheDir binariesPath | remoteRepoGitIndexed remoteRepo = do exists <- doesDirectoryExist cacheDir (gitProg, _, _) <- requireProgramVersion verbosity gitProgram (orLaterVersion (mkVersion [1,8,5])) defaultProgramDb let runGit args = getProgramInvocationOutput verbosity (programInvocation gitProg args) >>= info verbosity if exists then runGit ["-C", cacheDir, "pull"] else runGit ["clone", "--depth=1", show (remoteRepoURI remoteRepo), cacheDir] updateBinaryPackageCaches verbosity transport cacheDir binariesPath return FileAlreadyInCache | otherwise = do remoteRepoCheckHttps verbosity transport remoteRepo let uri = (remoteRepoURI remoteRepo) { uriPath = uriPath (remoteRepoURI remoteRepo) `FilePath.Posix.combine` "00-index.tar.gz" } path = cacheDir </> "00-index" <.> "tar.gz" createDirectoryIfMissing True cacheDir downloadURI transport verbosity uri path -- ------------------------------------------------------------ -- * Async fetch wrapper utilities -- ------------------------------------------------------------ type AsyncFetchMap = Map UnresolvedPkgLoc (MVar (Either SomeException ResolvedPkgLoc)) -- | Fork off an async action to download the given packages (by location). -- -- The downloads are initiated in order, so you can arrange for packages that -- will likely be needed sooner to be earlier in the list. -- -- The body action is passed a map from those packages (identified by their -- location) to a completion var for that package. So the body action should -- lookup the location and use 'asyncFetchPackage' to get the result. -- asyncFetchPackages :: Verbosity -> RepoContext -> [UnresolvedPkgLoc] -> (AsyncFetchMap -> IO a) -> IO a asyncFetchPackages verbosity repoCtxt pkglocs body = do --TODO: [nice to have] use parallel downloads? asyncDownloadVars <- sequence [ do v <- newEmptyMVar return (pkgloc, v) | pkgloc <- pkglocs ] let fetchPackages :: IO () fetchPackages = forM_ asyncDownloadVars $ \(pkgloc, var) -> do -- Suppress marking here, because 'withAsync' means -- that we get nondeterministic interleaving result <- try $ fetchPackage (verboseUnmarkOutput verbosity) repoCtxt pkgloc putMVar var result withAsync fetchPackages $ \_ -> body (Map.fromList asyncDownloadVars) -- | Expect to find a download in progress in the given 'AsyncFetchMap' -- and wait on it to finish. -- -- If the download failed with an exception then this will be thrown. -- -- Note: This function is supposed to be idempotent, as our install plans -- can now use the same tarball for many builds, e.g. different -- components and/or qualified goals, and these all go through the -- download phase so we end up using 'waitAsyncFetchPackage' twice on the same package . C.f . # 4461 . waitAsyncFetchPackage :: Verbosity -> AsyncFetchMap -> UnresolvedPkgLoc -> IO ResolvedPkgLoc waitAsyncFetchPackage verbosity downloadMap srcloc = case Map.lookup srcloc downloadMap of Just hnd -> do debug verbosity $ "Waiting for download of " ++ show srcloc either throwIO return =<< readMVar hnd Nothing -> fail "waitAsyncFetchPackage: package not being downloaded" -- ------------------------------------------------------------ -- * Path utilities -- ------------------------------------------------------------ -- | Generate the full path to the locally cached copy of -- the tarball for a given @PackageIdentifer@. -- packageFile :: Repo -> PackageId -> FilePath packageFile repo pkgid = packageDir repo pkgid </> display pkgid <.> "tar.gz" -- | Generate the full path to the directory where the local cached copy of -- the tarball for a given @PackageIdentifer@ is stored. -- packageDir :: Repo -> PackageId -> FilePath packageDir repo pkgid = repoLocalDir repo </> display (packageName pkgid) </> display (packageVersion pkgid) -- | Generate the URI of the tarball for a given package. -- packageURI :: RemoteRepo -> PackageId -> URI packageURI repo pkgid | isOldHackageURI (remoteRepoURI repo) = (remoteRepoURI repo) { uriPath = FilePath.Posix.joinPath [uriPath (remoteRepoURI repo) ,display (packageName pkgid) ,display (packageVersion pkgid) ,display pkgid <.> "tar.gz"] } packageURI repo pkgid = (remoteRepoURI repo) { uriPath = FilePath.Posix.joinPath [uriPath (remoteRepoURI repo) ,"package" ,display pkgid <.> "tar.gz"] }
null
https://raw.githubusercontent.com/typelead/etlas/bbd7c558169e1fda086e759e1a6f8c8ca2807583/etlas/Distribution/Client/FetchUtils.hs
haskell
--------------------------------------------------------------------------- | License : BSD-like Maintainer : Stability : provisional Portability : portable Functions for fetching packages --------------------------------------------------------------------------- * fetching packages ** specifically for repo packages ** fetching packages asynchronously * fetching other things # SOURCE # ------------------------------------------------------------ * Actually fetch things ------------------------------------------------------------ | Returns @True@ if the package has already been fetched or does not need fetching. | Checks if the package has already been fetched (or does not need fetching) and if so returns evidence in the form of a 'PackageLocation' with a resolved local file location. | Like 'checkFetched' but for the specific case of a 'RepoTarballPackage'. | Fetch a package if we don't have it already. | Fetch a source control management repo package if we don't have it already. | Fetch a repo package if we don't have it already. | Downloads an index file to [config-dir/packages/serv-id] without hackage-security. You probably don't want to call this directly; use 'updateRepo' instead. ------------------------------------------------------------ * Async fetch wrapper utilities ------------------------------------------------------------ | Fork off an async action to download the given packages (by location). The downloads are initiated in order, so you can arrange for packages that will likely be needed sooner to be earlier in the list. The body action is passed a map from those packages (identified by their location) to a completion var for that package. So the body action should lookup the location and use 'asyncFetchPackage' to get the result. TODO: [nice to have] use parallel downloads? Suppress marking here, because 'withAsync' means that we get nondeterministic interleaving | Expect to find a download in progress in the given 'AsyncFetchMap' and wait on it to finish. If the download failed with an exception then this will be thrown. Note: This function is supposed to be idempotent, as our install plans can now use the same tarball for many builds, e.g. different components and/or qualified goals, and these all go through the download phase so we end up using 'waitAsyncFetchPackage' twice on ------------------------------------------------------------ * Path utilities ------------------------------------------------------------ | Generate the full path to the locally cached copy of the tarball for a given @PackageIdentifer@. | Generate the full path to the directory where the local cached copy of the tarball for a given @PackageIdentifer@ is stored. | Generate the URI of the tarball for a given package.
Module : Distribution . Client . FetchUtils Copyright : ( c ) 2005 2011 # LANGUAGE RecordWildCards # module Distribution.Client.FetchUtils ( fetchPackage, isFetched, checkFetched, checkRepoTarballFetched, fetchRepoTarball, fetchSourceRepo, downloadSourceRepo, asyncFetchPackages, waitAsyncFetchPackage, AsyncFetchMap, downloadIndex, ) where import Distribution.Client.Types import Distribution.Client.HttpUtils ( downloadURI, isOldHackageURI, DownloadResult(..) , HttpTransport(..), transportCheckHttps, remoteRepoCheckHttps ) import Distribution.Package ( PackageId, packageName, packageVersion ) import Distribution.Simple.Utils ( notice, info, debug, setupMessage ) import Distribution.Text ( display ) import Distribution.Verbosity ( Verbosity, verboseUnmarkOutput ) import Distribution.Client.GlobalFlags ( RepoContext(..) ) import Distribution.Client.Brancher import Distribution.Version import Distribution.Simple.Program import qualified Distribution.PackageDescription as PD import Data.Maybe import Data.Map (Map) import qualified Data.Map as Map import Control.Monad import Control.Exception import Control.Concurrent.Async import Control.Concurrent.MVar import System.Directory ( doesFileExist, createDirectoryIfMissing, getTemporaryDirectory, doesDirectoryExist ) import System.IO ( openTempFile, hClose ) import System.FilePath ( (</>), (<.>) ) import qualified System.FilePath.Posix as FilePath.Posix ( combine, joinPath ) import Network.URI ( URI(uriPath) ) import qualified Hackage.Security.Client as Sec isFetched :: UnresolvedPkgLoc -> IO Bool isFetched loc = case loc of LocalUnpackedPackage _dir -> return True LocalTarballPackage _file _ -> return True RemoteTarballPackage _uri local -> return (isJust local) RepoTarballPackage repo pkgid _ -> doesFileExist (packageFile repo pkgid) ScmPackage (Just repo) _ pkgid _ -> doesDirectoryExist (packageDir repo pkgid) ScmPackage Nothing _ _pkgid _ -> error "isFetched: ScmPackage Nothing" checkFetched :: UnresolvedPkgLoc -> IO (Maybe ResolvedPkgLoc) checkFetched loc = case loc of LocalUnpackedPackage dir -> return (Just $ LocalUnpackedPackage dir) LocalTarballPackage file isBinary -> return (Just $ LocalTarballPackage file isBinary) RemoteTarballPackage uri (Just file) -> return (Just $ RemoteTarballPackage uri file) RepoTarballPackage repo pkgid (Just file) -> return (Just $ RepoTarballPackage repo pkgid file) ScmPackage maybeRepo srcRepos pkgid (Just file) -> return (Just $ ScmPackage maybeRepo srcRepos pkgid file) RemoteTarballPackage _uri Nothing -> return Nothing RepoTarballPackage repo pkgid Nothing -> fmap (fmap (RepoTarballPackage repo pkgid)) (checkRepoTarballFetched repo pkgid) ScmPackage (Just repo) srcRepos pkgid Nothing -> do let dir = packageDir repo pkgid exists <- doesDirectoryExist dir if exists then return (Just $ ScmPackage (Just repo) srcRepos pkgid dir) else return Nothing ScmPackage Nothing _ _ Nothing -> error "checkFetched: ScmPackage Nothing" checkRepoTarballFetched :: Repo -> PackageId -> IO (Maybe FilePath) checkRepoTarballFetched repo pkgid = do let file = packageFile repo pkgid exists <- doesFileExist file if exists then return (Just file) else return Nothing fetchPackage :: Verbosity -> RepoContext -> UnresolvedPkgLoc -> IO ResolvedPkgLoc fetchPackage verbosity repoCtxt loc = case loc of LocalUnpackedPackage dir -> return (LocalUnpackedPackage dir) LocalTarballPackage file isBinary -> return (LocalTarballPackage file isBinary) RemoteTarballPackage uri (Just file) -> return (RemoteTarballPackage uri file) RepoTarballPackage repo pkgid (Just file) -> return (RepoTarballPackage repo pkgid file) ScmPackage maybeRepo sourceRepos pkgid (Just file) -> return (ScmPackage maybeRepo sourceRepos pkgid file) RemoteTarballPackage uri Nothing -> do path <- downloadTarballPackage uri return (RemoteTarballPackage uri path) RepoTarballPackage repo pkgid Nothing -> do local <- fetchRepoTarball verbosity repoCtxt repo pkgid return (RepoTarballPackage repo pkgid local) ScmPackage (Just repo) sourceRepos pkgid Nothing -> do local <- fetchSourceRepo verbosity repo pkgid sourceRepos return (ScmPackage (Just repo) sourceRepos pkgid local) ScmPackage Nothing _ _ Nothing -> do error "fetchPackage: ScmPackage Nothing" where downloadTarballPackage uri = do transport <- repoContextGetTransport repoCtxt transportCheckHttps verbosity transport uri notice verbosity ("Downloading " ++ show uri) tmpdir <- getTemporaryDirectory (path, hnd) <- openTempFile tmpdir "etlas-.tar.gz" hClose hnd _ <- downloadURI transport verbosity uri path return path fetchSourceRepo :: Verbosity -> Repo -> PackageId -> [PD.SourceRepo] -> IO FilePath fetchSourceRepo verbosity repo pkgid sourceRepos = do fetched <- doesDirectoryExist repoDir if fetched then do info verbosity $ repoDir ++ " has already been downloaded." return repoDir else do notice verbosity $ "Downloading " ++ display pkgid ++ "..." downloadSourceRepo verbosity repoDir (Right pkgid) sourceRepos return repoDir where repoDir = packageDir repo pkgid downloadSourceRepo :: Verbosity -> FilePath -> Either String PackageId -> [PD.SourceRepo] -> IO () downloadSourceRepo verbosity targetDir ePkgDesc sourceRepos = do branchers <- findUsableBranchers forkPackage verbosity branchers targetDir Nothing ePkgDesc sourceRepos fetchRepoTarball :: Verbosity -> RepoContext -> Repo -> PackageId -> IO FilePath fetchRepoTarball verbosity repoCtxt repo pkgid = do fetched <- doesFileExist (packageFile repo pkgid) if fetched then do info verbosity $ display pkgid ++ " has already been downloaded." return (packageFile repo pkgid) else do setupMessage verbosity "Downloading [source]" pkgid downloadRepoPackage where downloadRepoPackage = case repo of RepoLocal{..} -> return (packageFile repo pkgid) RepoRemote{..} -> do transport <- repoContextGetTransport repoCtxt remoteRepoCheckHttps verbosity transport repoRemote let uri = packageURI repoRemote pkgid dir = packageDir repo pkgid path = packageFile repo pkgid createDirectoryIfMissing True dir _ <- downloadURI transport verbosity uri path return path RepoSecure{} -> repoContextWithSecureRepo repoCtxt repo $ \rep -> do let dir = packageDir repo pkgid path = packageFile repo pkgid createDirectoryIfMissing True dir Sec.uncheckClientErrors $ do info verbosity ("writing " ++ path) Sec.downloadPackage' rep pkgid path return path downloadIndex :: Verbosity -> HttpTransport -> RemoteRepo -> FilePath -> FilePath -> IO DownloadResult downloadIndex verbosity transport remoteRepo cacheDir binariesPath | remoteRepoGitIndexed remoteRepo = do exists <- doesDirectoryExist cacheDir (gitProg, _, _) <- requireProgramVersion verbosity gitProgram (orLaterVersion (mkVersion [1,8,5])) defaultProgramDb let runGit args = getProgramInvocationOutput verbosity (programInvocation gitProg args) >>= info verbosity if exists then runGit ["-C", cacheDir, "pull"] else runGit ["clone", "--depth=1", show (remoteRepoURI remoteRepo), cacheDir] updateBinaryPackageCaches verbosity transport cacheDir binariesPath return FileAlreadyInCache | otherwise = do remoteRepoCheckHttps verbosity transport remoteRepo let uri = (remoteRepoURI remoteRepo) { uriPath = uriPath (remoteRepoURI remoteRepo) `FilePath.Posix.combine` "00-index.tar.gz" } path = cacheDir </> "00-index" <.> "tar.gz" createDirectoryIfMissing True cacheDir downloadURI transport verbosity uri path type AsyncFetchMap = Map UnresolvedPkgLoc (MVar (Either SomeException ResolvedPkgLoc)) asyncFetchPackages :: Verbosity -> RepoContext -> [UnresolvedPkgLoc] -> (AsyncFetchMap -> IO a) -> IO a asyncFetchPackages verbosity repoCtxt pkglocs body = do asyncDownloadVars <- sequence [ do v <- newEmptyMVar return (pkgloc, v) | pkgloc <- pkglocs ] let fetchPackages :: IO () fetchPackages = forM_ asyncDownloadVars $ \(pkgloc, var) -> do result <- try $ fetchPackage (verboseUnmarkOutput verbosity) repoCtxt pkgloc putMVar var result withAsync fetchPackages $ \_ -> body (Map.fromList asyncDownloadVars) the same package . C.f . # 4461 . waitAsyncFetchPackage :: Verbosity -> AsyncFetchMap -> UnresolvedPkgLoc -> IO ResolvedPkgLoc waitAsyncFetchPackage verbosity downloadMap srcloc = case Map.lookup srcloc downloadMap of Just hnd -> do debug verbosity $ "Waiting for download of " ++ show srcloc either throwIO return =<< readMVar hnd Nothing -> fail "waitAsyncFetchPackage: package not being downloaded" packageFile :: Repo -> PackageId -> FilePath packageFile repo pkgid = packageDir repo pkgid </> display pkgid <.> "tar.gz" packageDir :: Repo -> PackageId -> FilePath packageDir repo pkgid = repoLocalDir repo </> display (packageName pkgid) </> display (packageVersion pkgid) packageURI :: RemoteRepo -> PackageId -> URI packageURI repo pkgid | isOldHackageURI (remoteRepoURI repo) = (remoteRepoURI repo) { uriPath = FilePath.Posix.joinPath [uriPath (remoteRepoURI repo) ,display (packageName pkgid) ,display (packageVersion pkgid) ,display pkgid <.> "tar.gz"] } packageURI repo pkgid = (remoteRepoURI repo) { uriPath = FilePath.Posix.joinPath [uriPath (remoteRepoURI repo) ,"package" ,display pkgid <.> "tar.gz"] }
c6dfd51451f709143966e277418dafda326cebc27ca56b4a8914d2db96f59dfc
Vaelatern/necessary-evil
methodcall.clj
(ns necessary-evil.methodcall "This module implements the methodCall wire format portion of the XML-RPC spec. You can find the official spect at -rpc.com/spec. It is expected that this module will always be required, rather than used. The parse function will consume a clojure.xml structure and return a MethodCall record. The unparse function is the dual of parse; it takes a MethodCall record and returns xml. Use clojure.xml/emit to turn the xml structure returned into text. As emit prints to *out* you may need to use with-out-str to capture the result. " (:use [clojure.data.zip.xml :only [xml-> xml1-> text]] (necessary-evil xml-utils value)) (:require [clojure.zip :as zip] [clojure.data.zip :as zf] [clojure.string :as su]) (:import org.apache.commons.codec.binary.Base64)) (defrecord MethodCall [method-name parameters]) (defn methodcall "A convenience function that creates a new MethodCall. record" [method-name parameters] (MethodCall. method-name parameters)) ;; The following functions parse the xml structure of a <methodCall> and return a new MethodCall record (defn method-call? "a predicate to ensure that this xml is a methodCall" [x] (-> x zip/node :tag (= :methodCall))) (defn parse-method-name "returns the method name for a methodcall" [x] (when-let [name ^String (xml1-> x :methodName text)] (let [clean-name (.trim name)] (when (-> clean-name empty? not) clean-name)))) (defn parse-params "returns a vector containing one element for each param in the method call" [x] (vec (map (comp parse-value first-child) (xml-> x :params :param :value)))) (defn parse "Takes xml structure representing an RPC method call and returns a new MethodCall record." [x] (when (method-call? x) (MethodCall. (parse-method-name x) (parse-params x)))) ;; The following functions are used to emit a <methodCall> xml structure (defn unparse "This function returns a string that represents a method call record in the XML format described by the xml-rpc 'spec'." [mc] (let [name-elem (elem :methodName [(-> mc :method-name name)]) params (:parameters mc) children (if (seq params) [name-elem (elem :params (map #(elem :param [(value-elem %)]) params))] [name-elem])] (elem :methodCall children)))
null
https://raw.githubusercontent.com/Vaelatern/necessary-evil/e4e8c9ccb0a631b57ef2eed52b8670bf9f705567/src/necessary_evil/methodcall.clj
clojure
it takes a The following functions parse the xml structure of a <methodCall> The following functions are used to emit a <methodCall> xml structure
(ns necessary-evil.methodcall "This module implements the methodCall wire format portion of the XML-RPC spec. You can find the official spect at -rpc.com/spec. It is expected that this module will always be required, rather than used. The parse function will consume a clojure.xml structure and return a MethodCall record and returns xml. Use clojure.xml/emit to turn the xml structure returned into text. As emit prints to *out* you may need to use with-out-str to capture the result. " (:use [clojure.data.zip.xml :only [xml-> xml1-> text]] (necessary-evil xml-utils value)) (:require [clojure.zip :as zip] [clojure.data.zip :as zf] [clojure.string :as su]) (:import org.apache.commons.codec.binary.Base64)) (defrecord MethodCall [method-name parameters]) (defn methodcall "A convenience function that creates a new MethodCall. record" [method-name parameters] (MethodCall. method-name parameters)) and return a new MethodCall record (defn method-call? "a predicate to ensure that this xml is a methodCall" [x] (-> x zip/node :tag (= :methodCall))) (defn parse-method-name "returns the method name for a methodcall" [x] (when-let [name ^String (xml1-> x :methodName text)] (let [clean-name (.trim name)] (when (-> clean-name empty? not) clean-name)))) (defn parse-params "returns a vector containing one element for each param in the method call" [x] (vec (map (comp parse-value first-child) (xml-> x :params :param :value)))) (defn parse "Takes xml structure representing an RPC method call and returns a new MethodCall record." [x] (when (method-call? x) (MethodCall. (parse-method-name x) (parse-params x)))) (defn unparse "This function returns a string that represents a method call record in the XML format described by the xml-rpc 'spec'." [mc] (let [name-elem (elem :methodName [(-> mc :method-name name)]) params (:parameters mc) children (if (seq params) [name-elem (elem :params (map #(elem :param [(value-elem %)]) params))] [name-elem])] (elem :methodCall children)))
3aed8ced34ff69b92ef0d6c3961cb901942e3da8c4596deb5b43337b6da3e433
kovisoft/slimv
allegro.lisp
;;;; -*- indent-tabs-mode: nil; outline-regexp: ";;;;;* "; -*- ;;; swank-allegro.lisp --- Allegro CL specific code for SLIME . ;;; Created 2003 ;;; ;;; This code has been placed in the Public Domain. All warranties ;;; are disclaimed. ;;; (defpackage swank/allegro (:use cl swank/backend)) (in-package swank/allegro) (eval-when (:compile-toplevel :load-toplevel :execute) (require :sock) (require :process) #+(version>= 8 2) (require 'lldb)) (defimplementation gray-package-name () '#:excl) ;;; swank-mop (import-swank-mop-symbols :clos '(:slot-definition-documentation)) (defun swank-mop:slot-definition-documentation (slot) (documentation slot t)) ;;;; UTF8 (define-symbol-macro utf8-ef (load-time-value (excl:crlf-base-ef (excl:find-external-format :utf-8)) t)) (defimplementation string-to-utf8 (s) (excl:string-to-octets s :external-format utf8-ef :null-terminate nil)) (defimplementation utf8-to-string (u) (excl:octets-to-string u :external-format utf8-ef)) ;;;; TCP Server (defimplementation preferred-communication-style () :spawn) (defimplementation create-socket (host port &key backlog) (socket:make-socket :connect :passive :local-port port :local-host host :reuse-address t :backlog (or backlog 5))) (defimplementation local-port (socket) (socket:local-port socket)) (defimplementation close-socket (socket) (close socket)) (defimplementation accept-connection (socket &key external-format buffering timeout) (declare (ignore buffering timeout)) (let ((s (socket:accept-connection socket :wait t))) (when external-format (setf (stream-external-format s) external-format)) s)) (defimplementation socket-fd (stream) (excl::stream-input-handle stream)) (defvar *external-format-to-coding-system* '((:iso-8859-1 "latin-1" "latin-1-unix" "iso-latin-1-unix" "iso-8859-1" "iso-8859-1-unix") (:utf-8 "utf-8" "utf-8-unix") (:euc-jp "euc-jp" "euc-jp-unix") (:us-ascii "us-ascii" "us-ascii-unix") (:emacs-mule "emacs-mule" "emacs-mule-unix"))) (defimplementation find-external-format (coding-system) (let ((e (rassoc-if (lambda (x) (member coding-system x :test #'equal)) *external-format-to-coding-system*))) (and e (excl:crlf-base-ef (excl:find-external-format (car e) :try-variant t))))) ;;;; Unix signals (defimplementation getpid () (excl::getpid)) (defimplementation lisp-implementation-type-name () "allegro") (defimplementation set-default-directory (directory) (let* ((dir (namestring (truename (merge-pathnames directory))))) (setf *default-pathname-defaults* (pathname (excl:chdir dir))) dir)) (defimplementation default-directory () (namestring (excl:current-directory))) ;;;; Misc (defimplementation arglist (symbol) (handler-case (excl:arglist symbol) (simple-error () :not-available))) (defimplementation macroexpand-all (form &optional env) (declare (ignore env)) #+(version>= 8 0) (excl::walk-form form) #-(version>= 8 0) (excl::walk form)) (defimplementation describe-symbol-for-emacs (symbol) (let ((result '())) (flet ((doc (kind &optional (sym symbol)) (or (documentation sym kind) :not-documented)) (maybe-push (property value) (when value (setf result (list* property value result))))) (maybe-push :variable (when (boundp symbol) (doc 'variable))) (maybe-push :function (if (fboundp symbol) (doc 'function))) (maybe-push :class (if (find-class symbol nil) (doc 'class))) result))) (defimplementation describe-definition (symbol namespace) (ecase namespace (:variable (describe symbol)) ((:function :generic-function) (describe (symbol-function symbol))) (:class (describe (find-class symbol))))) (defimplementation type-specifier-p (symbol) (or (ignore-errors (subtypep nil symbol)) (not (eq (type-specifier-arglist symbol) :not-available)))) (defimplementation function-name (f) (check-type f function) (cross-reference::object-to-function-name f)) ;;;; Debugger (defvar *sldb-topframe*) (defimplementation call-with-debugging-environment (debugger-loop-fn) (let ((*sldb-topframe* (find-topframe)) (excl::*break-hook* nil)) (funcall debugger-loop-fn))) (defimplementation sldb-break-at-start (fname) ;; :print-before is kind of mis-used but we just want to stuff our break form somewhere . This does not work for setf , : before and ;; :after methods, which need special syntax in the trace call, see ACL 's doc / debugging.htm chapter 10 . (eval `(trace (,fname :print-before ((break "Function start breakpoint of ~A" ',fname))))) `(:ok ,(format nil "Set breakpoint at start of ~S" fname))) (defun find-topframe () (let ((magic-symbol (intern (symbol-name :swank-debugger-hook) (find-package :swank))) (top-frame (excl::int-newest-frame (excl::current-thread)))) (loop for frame = top-frame then (next-frame frame) for i from 0 while (and frame (< i 30)) when (eq (debugger:frame-name frame) magic-symbol) return (next-frame frame) finally (return top-frame)))) (defun next-frame (frame) (let ((next (excl::int-next-older-frame frame))) (cond ((not next) nil) ((debugger:frame-visible-p next) next) (t (next-frame next))))) (defun nth-frame (index) (do ((frame *sldb-topframe* (next-frame frame)) (i index (1- i))) ((zerop i) frame))) (defimplementation compute-backtrace (start end) (let ((end (or end most-positive-fixnum))) (loop for f = (nth-frame start) then (next-frame f) for i from start below end while f collect f))) (defimplementation print-frame (frame stream) (debugger:output-frame stream frame :moderate)) (defimplementation frame-locals (index) (let ((frame (nth-frame index))) (loop for i from 0 below (debugger:frame-number-vars frame) collect (list :name (debugger:frame-var-name frame i) :id 0 :value (debugger:frame-var-value frame i))))) (defimplementation frame-var-value (frame var) (let ((frame (nth-frame frame))) (debugger:frame-var-value frame var))) (defimplementation disassemble-frame (index) (let ((frame (nth-frame index))) (multiple-value-bind (x fun xx xxx pc) (debugger::dyn-fd-analyze frame) (format t "pc: ~d (~s ~s ~s)~%fun: ~a~%" pc x xx xxx fun) (disassemble (debugger:frame-function frame))))) (defimplementation frame-source-location (index) (let* ((frame (nth-frame index))) (multiple-value-bind (x fun xx xxx pc) (debugger::dyn-fd-analyze frame) (declare (ignore x xx xxx)) (cond ((and pc #+(version>= 8 2) (pc-source-location fun pc) #-(version>= 8 2) (function-source-location fun))) (t ; frames for unbound functions etc end up here (cadr (car (fspec-definition-locations (car (debugger:frame-expression frame)))))))))) (defun function-source-location (fun) (cadr (car (fspec-definition-locations (xref::object-to-function-name fun))))) #+(version>= 8 2) (defun pc-source-location (fun pc) (let* ((debug-info (excl::function-source-debug-info fun))) (cond ((not debug-info) (function-source-location fun)) (t (let* ((code-loc (find-if (lambda (c) (<= (- pc (sys::natural-width)) (let ((x (excl::ldb-code-pc c))) (or x -1)) pc)) debug-info))) (cond ((not code-loc) (ldb-code-to-src-loc (aref debug-info 0))) (t (ldb-code-to-src-loc code-loc)))))))) #+(version>= 8 2) (defun ldb-code-to-src-loc (code) (declare (optimize debug)) (let* ((func (excl::ldb-code-func code)) (debug-info (excl::function-source-debug-info func)) (start (loop for i from (excl::ldb-code-index code) downto 0 for bpt = (aref debug-info i) for start = (excl::ldb-code-start-char bpt) when start return (if (listp start) (first start) start))) (src-file (excl:source-file func))) (cond (start (buffer-or-file-location src-file start)) (func (let* ((debug-info (excl::function-source-debug-info func)) (whole (aref debug-info 0)) (paths (source-paths-of (excl::ldb-code-source whole) (excl::ldb-code-source code))) (path (if paths (longest-common-prefix paths) '())) (start 0)) (buffer-or-file src-file (lambda (file) (make-location `(:file ,file) `(:source-path (0 . ,path) ,start))) (lambda (buffer bstart) (make-location `(:buffer ,buffer) `(:source-path (0 . ,path) ,(+ bstart start))))))) (t nil)))) (defun longest-common-prefix (sequences) (assert sequences) (flet ((common-prefix (s1 s2) (let ((diff-pos (mismatch s1 s2))) (if diff-pos (subseq s1 0 diff-pos) s1)))) (reduce #'common-prefix sequences))) (defun source-paths-of (whole part) (let ((result '())) (labels ((walk (form path) (cond ((eq form part) (push (reverse path) result)) ((consp form) (loop for i from 0 while (consp form) do (walk (pop form) (cons i path))))))) (walk whole '()) (reverse result)))) (defimplementation eval-in-frame (form frame-number) (let ((frame (nth-frame frame-number))) ;; let-bind lexical variables (let ((vars (loop for i below (debugger:frame-number-vars frame) for name = (debugger:frame-var-name frame i) if (typep name '(and symbol (not null) (not keyword))) collect `(,name ',(debugger:frame-var-value frame i))))) (debugger:eval-form-in-context `(let* ,vars ,form) (debugger:environment-of-frame frame))))) (defimplementation frame-package (frame-number) (let* ((frame (nth-frame frame-number)) (exp (debugger:frame-expression frame))) (typecase exp ((cons symbol) (symbol-package (car exp))) ((cons (cons (eql :internal) (cons symbol))) (symbol-package (cadar exp)))))) (defimplementation return-from-frame (frame-number form) (let ((frame (nth-frame frame-number))) (multiple-value-call #'debugger:frame-return frame (debugger:eval-form-in-context form (debugger:environment-of-frame frame))))) (defimplementation frame-restartable-p (frame) (handler-case (debugger:frame-retryable-p frame) (serious-condition (c) (funcall (read-from-string "swank::background-message") "~a ~a" frame (princ-to-string c)) nil))) (defimplementation restart-frame (frame-number) (let ((frame (nth-frame frame-number))) (cond ((debugger:frame-retryable-p frame) (apply #'debugger:frame-retry frame (debugger:frame-function frame) (cdr (debugger:frame-expression frame)))) (t "Frame is not retryable")))) Compiler hooks (defvar *buffer-name* nil) (defvar *buffer-start-position*) (defvar *buffer-string*) (defvar *compile-filename* nil) (defun compiler-note-p (object) (member (type-of object) '(excl::compiler-note compiler::compiler-note))) (defun redefinition-p (condition) (and (typep condition 'style-warning) (every #'char-equal "redefin" (princ-to-string condition)))) (defun compiler-undefined-functions-called-warning-p (object) (typep object 'excl:compiler-undefined-functions-called-warning)) (deftype compiler-note () `(satisfies compiler-note-p)) (deftype redefinition () `(satisfies redefinition-p)) (defun signal-compiler-condition (&rest args) (apply #'signal 'compiler-condition args)) (defun handle-compiler-warning (condition) (declare (optimize (debug 3) (speed 0) (space 0))) (cond ((and #-(version>= 10 0) (not *buffer-name*) (compiler-undefined-functions-called-warning-p condition)) (handle-undefined-functions-warning condition)) ((and (typep condition 'excl::compiler-note) (let ((format (slot-value condition 'excl::format-control))) (and (search "Closure" format) (search "will be stack allocated" format)))) ;; Ignore "Closure <foo> will be stack allocated" notes. ;; That occurs often but is usually uninteresting. ) (t (signal-compiler-condition :original-condition condition :severity (etypecase condition (redefinition :redefinition) (style-warning :style-warning) (warning :warning) (compiler-note :note) (reader-error :read-error) (error :error)) :message (format nil "~A" condition) :location (compiler-warning-location condition))))) (defun condition-pathname-and-position (condition) (let* ((context #+(version>= 10 0) (getf (slot-value condition 'excl::plist) :source-context)) (location-available (and context (excl::source-context-start-char context)))) (cond (location-available (values (excl::source-context-pathname context) (when-let (start-char (excl::source-context-start-char context)) (let ((position (if (listp start-char) ; HACK (first start-char) start-char))) (if (typep condition 'excl::compiler-free-reference-warning) position (1+ position)))))) ((typep condition 'reader-error) (let ((pos (car (last (slot-value condition 'excl::format-arguments)))) (file (pathname (stream-error-stream condition)))) (when (integerp pos) (values file pos)))) (t (let ((loc (getf (slot-value condition 'excl::plist) :loc))) (when loc (destructuring-bind (file . pos) loc 8.2 and newer #+(version>= 10 1) (if (typep condition 'excl::compiler-inconsistent-name-usage-warning) (second pos) (first pos)) #-(version>= 10 1) (first pos) pos))) (values file start))))))))) (defun compiler-warning-location (condition) (multiple-value-bind (pathname position) (condition-pathname-and-position condition) (cond (*buffer-name* (make-location (list :buffer *buffer-name*) (if position (list :offset 1 (1- position)) (list :offset *buffer-start-position* 0)))) (pathname (make-location (list :file (namestring (truename pathname))) #+(version>= 10 1) (list :offset 1 position) #-(version>= 10 1) (list :position (1+ position)))) (t (make-error-location "No error location available."))))) TODO : report it as a bug to that the condition 's plist slot contains (: ) . (defun handle-undefined-functions-warning (condition) (let ((fargs (slot-value condition 'excl::format-arguments))) (loop for (fname . locs) in (car fargs) do (dolist (loc locs) (multiple-value-bind (pos file) (ecase (length loc) (2 (values-list loc)) (3 (destructuring-bind (start end file) loc (declare (ignore end)) (values start file)))) (signal-compiler-condition :original-condition condition :severity :warning :message (format nil "Undefined function referenced: ~S" fname) :location (make-location (list :file file) #+(version>= 9 0) (list :offset 1 pos) #-(version>= 9 0) (list :position (1+ pos))))))))) (defimplementation call-with-compilation-hooks (function) (handler-bind ((warning #'handle-compiler-warning) (compiler-note #'handle-compiler-warning) (reader-error #'handle-compiler-warning)) (funcall function))) (defimplementation swank-compile-file (input-file output-file load-p external-format &key policy) (declare (ignore policy)) (handler-case (with-compilation-hooks () (let ((*buffer-name* nil) (*compile-filename* input-file) #+(version>= 8 2) (compiler:save-source-level-debug-info-switch t) (excl:*load-source-file-info* t) #+(version>= 8 2) (excl:*load-source-debug-info* t)) (compile-file *compile-filename* :output-file output-file :load-after-compile load-p :external-format external-format))) (reader-error () (values nil nil t)))) (defun call-with-temp-file (fn) (let ((tmpname (system:make-temp-file-name))) (unwind-protect (with-open-file (file tmpname :direction :output :if-exists :error) (funcall fn file tmpname)) (delete-file tmpname)))) (defvar *temp-file-map* (make-hash-table :test #'equal) "A mapping from tempfile names to Emacs buffer names.") (defun write-tracking-preamble (stream file file-offset) "Instrument the top of the temporary file to be compiled. The header tells allegro that any definitions compiled in the temp file should be found in FILE exactly at FILE-OFFSET. To get Allegro to do this, this factors in the length of the inserted header itself." (with-standard-io-syntax (let* ((*package* (find-package :keyword)) (source-pathname-form `(cl:eval-when (:compile-toplevel :load-toplevel :execute) (cl:setq excl::*source-pathname* (pathname ,(sys::frob-source-file file))))) (source-pathname-string (write-to-string source-pathname-form)) (position-form-length-bound 160) ; should be enough for everyone (header-length (+ (length source-pathname-string) position-form-length-bound)) (position-form `(cl:eval-when (:compile-toplevel :load-toplevel :execute) (cl:setq excl::*partial-source-file-p* ,(- file-offset header-length 1 ; for the newline )))) (position-form-string (write-to-string position-form)) (padding-string (make-string (- position-form-length-bound (length position-form-string)) :initial-element #\;))) (write-string source-pathname-string stream) (write-string position-form-string stream) (write-string padding-string stream) (write-char #\newline stream)))) (defun compile-from-temp-file (string buffer offset file) (call-with-temp-file (lambda (stream filename) (when (and file offset (probe-file file)) (write-tracking-preamble stream file offset)) (write-string string stream) (finish-output stream) (multiple-value-bind (binary-filename warnings? failure?) suppress .lisp extension #+(version>= 8 2) (compiler:save-source-level-debug-info-switch t) (excl:*redefinition-warnings* nil)) (compile-file filename)) (declare (ignore warnings?)) (when binary-filename (let ((excl:*load-source-file-info* t) #+(version>= 8 2) (excl:*load-source-debug-info* t)) excl::*source-pathname* (load binary-filename)) (when (and buffer offset (or (not file) (not (probe-file file)))) (setf (gethash (pathname stream) *temp-file-map*) (list buffer offset))) (delete-file binary-filename)) (not failure?))))) (defimplementation swank-compile-string (string &key buffer position filename line column policy) (declare (ignore line column policy)) (handler-case (with-compilation-hooks () (let ((*buffer-name* buffer) (*buffer-start-position* position) (*buffer-string* string)) (compile-from-temp-file string buffer position filename))) (reader-error () nil))) ;;;; Definition Finding (defun buffer-or-file (file file-fun buffer-fun) (let* ((probe (gethash file *temp-file-map*))) (cond (probe (destructuring-bind (buffer start) probe (funcall buffer-fun buffer start))) (t (funcall file-fun (namestring (truename file))))))) (defun buffer-or-file-location (file offset) (buffer-or-file file (lambda (filename) (make-location `(:file ,filename) `(:position ,(1+ offset)))) (lambda (buffer start) (make-location `(:buffer ,buffer) `(:offset ,start ,offset))))) (defun fspec-primary-name (fspec) (etypecase fspec (symbol fspec) (list (fspec-primary-name (second fspec))))) (defun find-definition-in-file (fspec type file top-level) (let* ((part (or (scm::find-definition-in-definition-group fspec type (scm:section-file :file file) :top-level top-level) (scm::find-definition-in-definition-group (fspec-primary-name fspec) type (scm:section-file :file file) :top-level top-level))) (start (and part (scm::source-part-start part))) (pos (if start (list :offset 1 start) (list :function-name (string (fspec-primary-name fspec)))))) (make-location (list :file (namestring (truename file))) pos))) (defun find-fspec-location (fspec type file top-level) (handler-case (etypecase file (pathname (let ((probe (gethash file *temp-file-map*))) (cond (probe (destructuring-bind (buffer offset) probe (make-location `(:buffer ,buffer) `(:offset ,offset 0)))) (t (find-definition-in-file fspec type file top-level))))) ((member :top-level) (make-error-location "Defined at toplevel: ~A" (fspec->string fspec)))) (error (e) (make-error-location "Error: ~A" e)))) (defun fspec->string (fspec) (typecase fspec (symbol (let ((*package* (find-package :keyword))) (prin1-to-string fspec))) (list (format nil "(~A ~A)" (prin1-to-string (first fspec)) (let ((*package* (find-package :keyword))) (prin1-to-string (second fspec))))) (t (princ-to-string fspec)))) (defun fspec-definition-locations (fspec) (cond ((and (listp fspec) (eq (car fspec) :internal)) (destructuring-bind (_internal next _n) fspec (declare (ignore _internal _n)) (fspec-definition-locations next))) (t (let ((defs (excl::find-source-file fspec))) (when (and (null defs) (listp fspec) (string= (car fspec) '#:method)) ;; If methods are defined in a defgeneric form, the source location is ;; recorded for the gf but not for the methods. Therefore fall back to ;; the gf as the likely place of definition. (setq defs (excl::find-source-file (second fspec)))) (if (null defs) (list (list fspec (make-error-location "Unknown source location for ~A" (fspec->string fspec)))) (loop for (fspec type file top-level) in defs collect (list (list type fspec) (find-fspec-location fspec type file top-level)))))))) (defimplementation find-definitions (symbol) (fspec-definition-locations symbol)) (defimplementation find-source-location (obj) (first (rest (first (fspec-definition-locations obj))))) ;;;; XREF (defmacro defxref (name relation name1 name2) `(defimplementation ,name (x) (xref-result (xref:get-relation ,relation ,name1 ,name2)))) (defxref who-calls :calls :wild x) (defxref calls-who :calls x :wild) (defxref who-references :uses :wild x) (defxref who-binds :binds :wild x) (defxref who-macroexpands :macro-calls :wild x) (defxref who-sets :sets :wild x) (defun xref-result (fspecs) (loop for fspec in fspecs append (fspec-definition-locations fspec))) ;; list-callers implemented by groveling through all fbound symbols. ;; Only symbols are considered. Functions in the constant pool are ;; searched recursively. Closure environments are ignored at the ;; moment (constants in methods are therefore not found). (defun map-function-constants (function fn depth) "Call FN with the elements of FUNCTION's constant pool." (do ((i 0 (1+ i)) (max (excl::function-constant-count function))) ((= i max)) (let ((c (excl::function-constant function i))) (cond ((and (functionp c) (not (eq c function)) (plusp depth)) (map-function-constants c fn (1- depth))) (t (funcall fn c)))))) (defun in-constants-p (fun symbol) (map-function-constants fun (lambda (c) (when (eq c symbol) (return-from in-constants-p t))) 3)) (defun function-callers (name) (let ((callers '())) (do-all-symbols (sym) (when (fboundp sym) (let ((fn (fdefinition sym))) (when (in-constants-p fn name) (push sym callers))))) callers)) (defimplementation list-callers (name) (xref-result (function-callers name))) (defimplementation list-callees (name) (let ((result '())) (map-function-constants (fdefinition name) (lambda (c) (when (fboundp c) (push c result))) 2) (xref-result result))) ;;;; Profiling ;; Per-function profiling based on description in ;; /\ ;; doc/runtime-analyzer.htm#data-collection-control-2 (defvar *profiled-functions* ()) (defvar *profile-depth* 0) (defmacro with-redirected-y-or-n-p (&body body) ;; If the profiler is restarted when the data from the previous session is not reported yet , the user is warned via Y - OR - N - P. As the CL : Y - OR - N - P question is ( for some reason ) not directly sent to the Slime user , the function CL : Y - OR - N - P is temporarily ;; overruled. `(let* ((pkg (find-package :common-lisp)) (saved-pdl (excl::package-definition-lock pkg)) (saved-ynp (symbol-function 'cl:y-or-n-p))) (setf (excl::package-definition-lock pkg) nil (symbol-function 'cl:y-or-n-p) (symbol-function (read-from-string "swank:y-or-n-p-in-emacs"))) (unwind-protect (progn ,@body) (setf (symbol-function 'cl:y-or-n-p) saved-ynp (excl::package-definition-lock pkg) saved-pdl)))) (defun start-acl-profiler () (with-redirected-y-or-n-p (prof:start-profiler :type :time :count t :start-sampling-p nil :verbose nil))) (defun acl-profiler-active-p () (not (eq (prof:profiler-status :verbose nil) :inactive))) (defun stop-acl-profiler () (prof:stop-profiler :verbose nil)) (excl:def-fwrapper profile-fwrapper (&rest args) ;; Ensures sampling is done during the execution of the function, ;; taking into account recursion. (declare (ignore args)) (cond ((zerop *profile-depth*) (let ((*profile-depth* (1+ *profile-depth*))) (prof:start-sampling) (unwind-protect (excl:call-next-fwrapper) (prof:stop-sampling)))) (t (excl:call-next-fwrapper)))) (defimplementation profile (fname) (unless (acl-profiler-active-p) (start-acl-profiler)) (excl:fwrap fname 'profile-fwrapper 'profile-fwrapper) (push fname *profiled-functions*)) (defimplementation profiled-functions () *profiled-functions*) (defimplementation unprofile (fname) (excl:funwrap fname 'profile-fwrapper) (setq *profiled-functions* (remove fname *profiled-functions*))) (defimplementation profile-report () (prof:show-flat-profile :verbose nil) (when *profiled-functions* (start-acl-profiler))) (defimplementation profile-reset () (when (acl-profiler-active-p) (stop-acl-profiler) (start-acl-profiler)) "Reset profiling counters.") ;;;; Inspecting (excl:without-redefinition-warnings (defmethod emacs-inspect ((o t)) (allegro-inspect o))) (defmethod emacs-inspect ((o function)) (allegro-inspect o)) (defmethod emacs-inspect ((o standard-object)) (allegro-inspect o)) (defun allegro-inspect (o) (loop for (d dd) on (inspect::inspect-ctl o) append (frob-allegro-field-def o d) until (eq d dd))) (defun frob-allegro-field-def (object def) (with-struct (inspect::field-def- name type access) def (ecase type ((:unsigned-word :unsigned-byte :unsigned-natural :unsigned-long :unsigned-half-long :unsigned-3byte :unsigned-long32) (label-value-line name (inspect::component-ref-v object access type))) ((:lisp :value :func) (label-value-line name (inspect::component-ref object access))) (:indirect (destructuring-bind (prefix count ref set) access (declare (ignore set prefix)) (loop for i below (funcall count object) append (label-value-line (format nil "~A-~D" name i) (funcall ref object i)))))))) ;;;; Multithreading (defimplementation initialize-multiprocessing (continuation) (mp:start-scheduler) (funcall continuation)) (defimplementation spawn (fn &key name) (mp:process-run-function name fn)) (defvar *id-lock* (mp:make-process-lock :name "id lock")) (defvar *thread-id-counter* 0) (defimplementation thread-id (thread) (mp:with-process-lock (*id-lock*) (or (getf (mp:process-property-list thread) 'id) (setf (getf (mp:process-property-list thread) 'id) (incf *thread-id-counter*))))) (defimplementation find-thread (id) (find id mp:*all-processes* :key (lambda (p) (getf (mp:process-property-list p) 'id)))) (defimplementation thread-name (thread) (mp:process-name thread)) (defimplementation thread-status (thread) (princ-to-string (mp:process-whostate thread))) (defimplementation thread-attributes (thread) (list :priority (mp:process-priority thread) :times-resumed (mp:process-times-resumed thread))) (defimplementation make-lock (&key name) (mp:make-process-lock :name name)) (defimplementation call-with-lock-held (lock function) (mp:with-process-lock (lock) (funcall function))) (defimplementation current-thread () mp:*current-process*) (defimplementation all-threads () (copy-list mp:*all-processes*)) (defimplementation interrupt-thread (thread fn) (mp:process-interrupt thread fn)) (defimplementation kill-thread (thread) (mp:process-kill thread)) (defvar *mailbox-lock* (mp:make-process-lock :name "mailbox lock")) (defstruct (mailbox (:conc-name mailbox.)) (lock (mp:make-process-lock :name "process mailbox")) (queue '() :type list) (gate (mp:make-gate nil))) (defun mailbox (thread) "Return THREAD's mailbox." (mp:with-process-lock (*mailbox-lock*) (or (getf (mp:process-property-list thread) 'mailbox) (setf (getf (mp:process-property-list thread) 'mailbox) (make-mailbox))))) (defimplementation send (thread message) (let* ((mbox (mailbox thread))) (mp:with-process-lock ((mailbox.lock mbox)) (setf (mailbox.queue mbox) (nconc (mailbox.queue mbox) (list message))) (mp:open-gate (mailbox.gate mbox))))) (defimplementation wake-thread (thread) (let* ((mbox (mailbox thread))) (mp:open-gate (mailbox.gate mbox)))) (defimplementation receive-if (test &optional timeout) (let ((mbox (mailbox mp:*current-process*))) (flet ((open-mailbox () ;; this opens the mailbox and returns if has the message we are expecting . But first , check for interrupts . (check-slime-interrupts) (mp:with-process-lock ((mailbox.lock mbox)) (let* ((q (mailbox.queue mbox)) (tail (member-if test q))) (when tail (setf (mailbox.queue mbox) (nconc (ldiff q tail) (cdr tail))) (return-from receive-if (car tail))) ;; ...if it doesn't, we close the gate (even if it ;; was already closed) (mp:close-gate (mailbox.gate mbox)))))) (cond (timeout ;; open the mailbox and return asap (open-mailbox) (return-from receive-if (values nil t))) (t ;; wait until gate open, then open mailbox. If there's ;; no message there, repeat forever. (loop (mp:process-wait "receive-if (waiting on gate)" #'mp:gate-open-p (mailbox.gate mbox)) (open-mailbox))))))) (let ((alist '()) (lock (mp:make-process-lock :name "register-thread"))) (defimplementation register-thread (name thread) (declare (type symbol name)) (mp:with-process-lock (lock) (etypecase thread (null (setf alist (delete name alist :key #'car))) (mp:process (let ((probe (assoc name alist))) (cond (probe (setf (cdr probe) thread)) (t (setf alist (acons name thread alist)))))))) nil) (defimplementation find-registered (name) (mp:with-process-lock (lock) (cdr (assoc name alist))))) (defimplementation set-default-initial-binding (var form) (push (cons var form) #+(version>= 9 0) excl:*required-thread-bindings* #-(version>= 9 0) excl::required-thread-bindings)) (defimplementation quit-lisp () (excl:exit 0 :quiet t)) Trace implementations In Allegro 7.0 , we have : ;; (trace <name>) ;; (trace ((method <name> <qualifier>? (<specializer>+)))) ;; (trace ((labels <name> <label-name>))) ;; (trace ((labels (method <name> (<specializer>+)) <label-name>))) < name > can be a normal name or a ( setf name ) (defimplementation toggle-trace (spec) (ecase (car spec) ((setf) (toggle-trace-aux spec)) (:defgeneric (toggle-trace-generic-function-methods (second spec))) ((setf :defmethod :labels :flet) (toggle-trace-aux (process-fspec-for-allegro spec))) (:call (destructuring-bind (caller callee) (cdr spec) (toggle-trace-aux callee :inside (list (process-fspec-for-allegro caller))))))) (defun tracedp (fspec) (member fspec (eval '(trace)) :test #'equal)) (defun toggle-trace-aux (fspec &rest args) (cond ((tracedp fspec) (eval `(untrace ,fspec)) (format nil "~S is now untraced." fspec)) (t (eval `(trace (,fspec ,@args))) (format nil "~S is now traced." fspec)))) (defun toggle-trace-generic-function-methods (name) (let ((methods (mop:generic-function-methods (fdefinition name)))) (cond ((tracedp name) (eval `(untrace ,name)) (dolist (method methods (format nil "~S is now untraced." name)) (excl:funtrace (mop:method-function method)))) (t (eval `(trace (,name))) (dolist (method methods (format nil "~S is now traced." name)) (excl:ftrace (mop:method-function method))))))) (defun process-fspec-for-allegro (fspec) (cond ((consp fspec) (ecase (first fspec) ((setf) fspec) ((:defun :defgeneric) (second fspec)) ((:defmethod) `(method ,@(rest fspec))) ((:labels) `(labels ,(process-fspec-for-allegro (second fspec)) ,(third fspec))) ((:flet) `(flet ,(process-fspec-for-allegro (second fspec)) ,(third fspec))))) (t fspec))) ;;;; Weak hashtables (defimplementation make-weak-key-hash-table (&rest args) (apply #'make-hash-table :weak-keys t args)) (defimplementation make-weak-value-hash-table (&rest args) (apply #'make-hash-table :values :weak args)) (defimplementation hash-table-weakness (hashtable) (cond ((excl:hash-table-weak-keys hashtable) :key) ((eq (excl:hash-table-values hashtable) :weak) :value))) ;;;; Character names (defimplementation character-completion-set (prefix matchp) (loop for name being the hash-keys of excl::*name-to-char-table* when (funcall matchp prefix name) collect (string-capitalize name))) ;;;; wrap interface implementation (defimplementation wrap (spec indicator &key before after replace) (let ((allegro-spec (process-fspec-for-allegro spec))) (excl:fwrap allegro-spec indicator (excl:def-fwrapper allegro-wrapper (&rest args) (let (retlist completed) (unwind-protect (progn (when before (funcall before args)) (setq retlist (multiple-value-list (if replace (funcall replace args) (excl:call-next-fwrapper)))) (setq completed t) (values-list retlist)) (when after (funcall after (if completed retlist :exited-non-locally))))))) allegro-spec)) (defimplementation unwrap (spec indicator) (let ((allegro-spec (process-fspec-for-allegro spec))) (excl:funwrap allegro-spec indicator) allegro-spec)) (defimplementation wrapped-p (spec indicator) (getf (excl:fwrap-order (process-fspec-for-allegro spec)) indicator))
null
https://raw.githubusercontent.com/kovisoft/slimv/cf8334cb7d71bf9793cb5588497b4fe15e501626/slime/swank/allegro.lisp
lisp
-*- indent-tabs-mode: nil; outline-regexp: ";;;;;* "; -*- This code has been placed in the Public Domain. All warranties are disclaimed. swank-mop UTF8 TCP Server Unix signals Misc Debugger :print-before is kind of mis-used but we just want to stuff our :after methods, which need special syntax in the trace call, see frames for unbound functions etc end up here let-bind lexical variables Ignore "Closure <foo> will be stack allocated" notes. That occurs often but is usually uninteresting. HACK should be enough for everyone for the newline ))) Definition Finding If methods are defined in a defgeneric form, the source location is recorded for the gf but not for the methods. Therefore fall back to the gf as the likely place of definition. XREF list-callers implemented by groveling through all fbound symbols. Only symbols are considered. Functions in the constant pool are searched recursively. Closure environments are ignored at the moment (constants in methods are therefore not found). Profiling Per-function profiling based on description in /\ doc/runtime-analyzer.htm#data-collection-control-2 If the profiler is restarted when the data from the previous overruled. Ensures sampling is done during the execution of the function, taking into account recursion. Inspecting Multithreading this opens the mailbox and returns if has the message ...if it doesn't, we close the gate (even if it was already closed) open the mailbox and return asap wait until gate open, then open mailbox. If there's no message there, repeat forever. (trace <name>) (trace ((method <name> <qualifier>? (<specializer>+)))) (trace ((labels <name> <label-name>))) (trace ((labels (method <name> (<specializer>+)) <label-name>))) Weak hashtables Character names wrap interface implementation
swank-allegro.lisp --- Allegro CL specific code for SLIME . Created 2003 (defpackage swank/allegro (:use cl swank/backend)) (in-package swank/allegro) (eval-when (:compile-toplevel :load-toplevel :execute) (require :sock) (require :process) #+(version>= 8 2) (require 'lldb)) (defimplementation gray-package-name () '#:excl) (import-swank-mop-symbols :clos '(:slot-definition-documentation)) (defun swank-mop:slot-definition-documentation (slot) (documentation slot t)) (define-symbol-macro utf8-ef (load-time-value (excl:crlf-base-ef (excl:find-external-format :utf-8)) t)) (defimplementation string-to-utf8 (s) (excl:string-to-octets s :external-format utf8-ef :null-terminate nil)) (defimplementation utf8-to-string (u) (excl:octets-to-string u :external-format utf8-ef)) (defimplementation preferred-communication-style () :spawn) (defimplementation create-socket (host port &key backlog) (socket:make-socket :connect :passive :local-port port :local-host host :reuse-address t :backlog (or backlog 5))) (defimplementation local-port (socket) (socket:local-port socket)) (defimplementation close-socket (socket) (close socket)) (defimplementation accept-connection (socket &key external-format buffering timeout) (declare (ignore buffering timeout)) (let ((s (socket:accept-connection socket :wait t))) (when external-format (setf (stream-external-format s) external-format)) s)) (defimplementation socket-fd (stream) (excl::stream-input-handle stream)) (defvar *external-format-to-coding-system* '((:iso-8859-1 "latin-1" "latin-1-unix" "iso-latin-1-unix" "iso-8859-1" "iso-8859-1-unix") (:utf-8 "utf-8" "utf-8-unix") (:euc-jp "euc-jp" "euc-jp-unix") (:us-ascii "us-ascii" "us-ascii-unix") (:emacs-mule "emacs-mule" "emacs-mule-unix"))) (defimplementation find-external-format (coding-system) (let ((e (rassoc-if (lambda (x) (member coding-system x :test #'equal)) *external-format-to-coding-system*))) (and e (excl:crlf-base-ef (excl:find-external-format (car e) :try-variant t))))) (defimplementation getpid () (excl::getpid)) (defimplementation lisp-implementation-type-name () "allegro") (defimplementation set-default-directory (directory) (let* ((dir (namestring (truename (merge-pathnames directory))))) (setf *default-pathname-defaults* (pathname (excl:chdir dir))) dir)) (defimplementation default-directory () (namestring (excl:current-directory))) (defimplementation arglist (symbol) (handler-case (excl:arglist symbol) (simple-error () :not-available))) (defimplementation macroexpand-all (form &optional env) (declare (ignore env)) #+(version>= 8 0) (excl::walk-form form) #-(version>= 8 0) (excl::walk form)) (defimplementation describe-symbol-for-emacs (symbol) (let ((result '())) (flet ((doc (kind &optional (sym symbol)) (or (documentation sym kind) :not-documented)) (maybe-push (property value) (when value (setf result (list* property value result))))) (maybe-push :variable (when (boundp symbol) (doc 'variable))) (maybe-push :function (if (fboundp symbol) (doc 'function))) (maybe-push :class (if (find-class symbol nil) (doc 'class))) result))) (defimplementation describe-definition (symbol namespace) (ecase namespace (:variable (describe symbol)) ((:function :generic-function) (describe (symbol-function symbol))) (:class (describe (find-class symbol))))) (defimplementation type-specifier-p (symbol) (or (ignore-errors (subtypep nil symbol)) (not (eq (type-specifier-arglist symbol) :not-available)))) (defimplementation function-name (f) (check-type f function) (cross-reference::object-to-function-name f)) (defvar *sldb-topframe*) (defimplementation call-with-debugging-environment (debugger-loop-fn) (let ((*sldb-topframe* (find-topframe)) (excl::*break-hook* nil)) (funcall debugger-loop-fn))) (defimplementation sldb-break-at-start (fname) break form somewhere . This does not work for setf , : before and ACL 's doc / debugging.htm chapter 10 . (eval `(trace (,fname :print-before ((break "Function start breakpoint of ~A" ',fname))))) `(:ok ,(format nil "Set breakpoint at start of ~S" fname))) (defun find-topframe () (let ((magic-symbol (intern (symbol-name :swank-debugger-hook) (find-package :swank))) (top-frame (excl::int-newest-frame (excl::current-thread)))) (loop for frame = top-frame then (next-frame frame) for i from 0 while (and frame (< i 30)) when (eq (debugger:frame-name frame) magic-symbol) return (next-frame frame) finally (return top-frame)))) (defun next-frame (frame) (let ((next (excl::int-next-older-frame frame))) (cond ((not next) nil) ((debugger:frame-visible-p next) next) (t (next-frame next))))) (defun nth-frame (index) (do ((frame *sldb-topframe* (next-frame frame)) (i index (1- i))) ((zerop i) frame))) (defimplementation compute-backtrace (start end) (let ((end (or end most-positive-fixnum))) (loop for f = (nth-frame start) then (next-frame f) for i from start below end while f collect f))) (defimplementation print-frame (frame stream) (debugger:output-frame stream frame :moderate)) (defimplementation frame-locals (index) (let ((frame (nth-frame index))) (loop for i from 0 below (debugger:frame-number-vars frame) collect (list :name (debugger:frame-var-name frame i) :id 0 :value (debugger:frame-var-value frame i))))) (defimplementation frame-var-value (frame var) (let ((frame (nth-frame frame))) (debugger:frame-var-value frame var))) (defimplementation disassemble-frame (index) (let ((frame (nth-frame index))) (multiple-value-bind (x fun xx xxx pc) (debugger::dyn-fd-analyze frame) (format t "pc: ~d (~s ~s ~s)~%fun: ~a~%" pc x xx xxx fun) (disassemble (debugger:frame-function frame))))) (defimplementation frame-source-location (index) (let* ((frame (nth-frame index))) (multiple-value-bind (x fun xx xxx pc) (debugger::dyn-fd-analyze frame) (declare (ignore x xx xxx)) (cond ((and pc #+(version>= 8 2) (pc-source-location fun pc) #-(version>= 8 2) (function-source-location fun))) (cadr (car (fspec-definition-locations (car (debugger:frame-expression frame)))))))))) (defun function-source-location (fun) (cadr (car (fspec-definition-locations (xref::object-to-function-name fun))))) #+(version>= 8 2) (defun pc-source-location (fun pc) (let* ((debug-info (excl::function-source-debug-info fun))) (cond ((not debug-info) (function-source-location fun)) (t (let* ((code-loc (find-if (lambda (c) (<= (- pc (sys::natural-width)) (let ((x (excl::ldb-code-pc c))) (or x -1)) pc)) debug-info))) (cond ((not code-loc) (ldb-code-to-src-loc (aref debug-info 0))) (t (ldb-code-to-src-loc code-loc)))))))) #+(version>= 8 2) (defun ldb-code-to-src-loc (code) (declare (optimize debug)) (let* ((func (excl::ldb-code-func code)) (debug-info (excl::function-source-debug-info func)) (start (loop for i from (excl::ldb-code-index code) downto 0 for bpt = (aref debug-info i) for start = (excl::ldb-code-start-char bpt) when start return (if (listp start) (first start) start))) (src-file (excl:source-file func))) (cond (start (buffer-or-file-location src-file start)) (func (let* ((debug-info (excl::function-source-debug-info func)) (whole (aref debug-info 0)) (paths (source-paths-of (excl::ldb-code-source whole) (excl::ldb-code-source code))) (path (if paths (longest-common-prefix paths) '())) (start 0)) (buffer-or-file src-file (lambda (file) (make-location `(:file ,file) `(:source-path (0 . ,path) ,start))) (lambda (buffer bstart) (make-location `(:buffer ,buffer) `(:source-path (0 . ,path) ,(+ bstart start))))))) (t nil)))) (defun longest-common-prefix (sequences) (assert sequences) (flet ((common-prefix (s1 s2) (let ((diff-pos (mismatch s1 s2))) (if diff-pos (subseq s1 0 diff-pos) s1)))) (reduce #'common-prefix sequences))) (defun source-paths-of (whole part) (let ((result '())) (labels ((walk (form path) (cond ((eq form part) (push (reverse path) result)) ((consp form) (loop for i from 0 while (consp form) do (walk (pop form) (cons i path))))))) (walk whole '()) (reverse result)))) (defimplementation eval-in-frame (form frame-number) (let ((frame (nth-frame frame-number))) (let ((vars (loop for i below (debugger:frame-number-vars frame) for name = (debugger:frame-var-name frame i) if (typep name '(and symbol (not null) (not keyword))) collect `(,name ',(debugger:frame-var-value frame i))))) (debugger:eval-form-in-context `(let* ,vars ,form) (debugger:environment-of-frame frame))))) (defimplementation frame-package (frame-number) (let* ((frame (nth-frame frame-number)) (exp (debugger:frame-expression frame))) (typecase exp ((cons symbol) (symbol-package (car exp))) ((cons (cons (eql :internal) (cons symbol))) (symbol-package (cadar exp)))))) (defimplementation return-from-frame (frame-number form) (let ((frame (nth-frame frame-number))) (multiple-value-call #'debugger:frame-return frame (debugger:eval-form-in-context form (debugger:environment-of-frame frame))))) (defimplementation frame-restartable-p (frame) (handler-case (debugger:frame-retryable-p frame) (serious-condition (c) (funcall (read-from-string "swank::background-message") "~a ~a" frame (princ-to-string c)) nil))) (defimplementation restart-frame (frame-number) (let ((frame (nth-frame frame-number))) (cond ((debugger:frame-retryable-p frame) (apply #'debugger:frame-retry frame (debugger:frame-function frame) (cdr (debugger:frame-expression frame)))) (t "Frame is not retryable")))) Compiler hooks (defvar *buffer-name* nil) (defvar *buffer-start-position*) (defvar *buffer-string*) (defvar *compile-filename* nil) (defun compiler-note-p (object) (member (type-of object) '(excl::compiler-note compiler::compiler-note))) (defun redefinition-p (condition) (and (typep condition 'style-warning) (every #'char-equal "redefin" (princ-to-string condition)))) (defun compiler-undefined-functions-called-warning-p (object) (typep object 'excl:compiler-undefined-functions-called-warning)) (deftype compiler-note () `(satisfies compiler-note-p)) (deftype redefinition () `(satisfies redefinition-p)) (defun signal-compiler-condition (&rest args) (apply #'signal 'compiler-condition args)) (defun handle-compiler-warning (condition) (declare (optimize (debug 3) (speed 0) (space 0))) (cond ((and #-(version>= 10 0) (not *buffer-name*) (compiler-undefined-functions-called-warning-p condition)) (handle-undefined-functions-warning condition)) ((and (typep condition 'excl::compiler-note) (let ((format (slot-value condition 'excl::format-control))) (and (search "Closure" format) (search "will be stack allocated" format)))) ) (t (signal-compiler-condition :original-condition condition :severity (etypecase condition (redefinition :redefinition) (style-warning :style-warning) (warning :warning) (compiler-note :note) (reader-error :read-error) (error :error)) :message (format nil "~A" condition) :location (compiler-warning-location condition))))) (defun condition-pathname-and-position (condition) (let* ((context #+(version>= 10 0) (getf (slot-value condition 'excl::plist) :source-context)) (location-available (and context (excl::source-context-start-char context)))) (cond (location-available (values (excl::source-context-pathname context) (when-let (start-char (excl::source-context-start-char context)) (first start-char) start-char))) (if (typep condition 'excl::compiler-free-reference-warning) position (1+ position)))))) ((typep condition 'reader-error) (let ((pos (car (last (slot-value condition 'excl::format-arguments)))) (file (pathname (stream-error-stream condition)))) (when (integerp pos) (values file pos)))) (t (let ((loc (getf (slot-value condition 'excl::plist) :loc))) (when loc (destructuring-bind (file . pos) loc 8.2 and newer #+(version>= 10 1) (if (typep condition 'excl::compiler-inconsistent-name-usage-warning) (second pos) (first pos)) #-(version>= 10 1) (first pos) pos))) (values file start))))))))) (defun compiler-warning-location (condition) (multiple-value-bind (pathname position) (condition-pathname-and-position condition) (cond (*buffer-name* (make-location (list :buffer *buffer-name*) (if position (list :offset 1 (1- position)) (list :offset *buffer-start-position* 0)))) (pathname (make-location (list :file (namestring (truename pathname))) #+(version>= 10 1) (list :offset 1 position) #-(version>= 10 1) (list :position (1+ position)))) (t (make-error-location "No error location available."))))) TODO : report it as a bug to that the condition 's plist slot contains (: ) . (defun handle-undefined-functions-warning (condition) (let ((fargs (slot-value condition 'excl::format-arguments))) (loop for (fname . locs) in (car fargs) do (dolist (loc locs) (multiple-value-bind (pos file) (ecase (length loc) (2 (values-list loc)) (3 (destructuring-bind (start end file) loc (declare (ignore end)) (values start file)))) (signal-compiler-condition :original-condition condition :severity :warning :message (format nil "Undefined function referenced: ~S" fname) :location (make-location (list :file file) #+(version>= 9 0) (list :offset 1 pos) #-(version>= 9 0) (list :position (1+ pos))))))))) (defimplementation call-with-compilation-hooks (function) (handler-bind ((warning #'handle-compiler-warning) (compiler-note #'handle-compiler-warning) (reader-error #'handle-compiler-warning)) (funcall function))) (defimplementation swank-compile-file (input-file output-file load-p external-format &key policy) (declare (ignore policy)) (handler-case (with-compilation-hooks () (let ((*buffer-name* nil) (*compile-filename* input-file) #+(version>= 8 2) (compiler:save-source-level-debug-info-switch t) (excl:*load-source-file-info* t) #+(version>= 8 2) (excl:*load-source-debug-info* t)) (compile-file *compile-filename* :output-file output-file :load-after-compile load-p :external-format external-format))) (reader-error () (values nil nil t)))) (defun call-with-temp-file (fn) (let ((tmpname (system:make-temp-file-name))) (unwind-protect (with-open-file (file tmpname :direction :output :if-exists :error) (funcall fn file tmpname)) (delete-file tmpname)))) (defvar *temp-file-map* (make-hash-table :test #'equal) "A mapping from tempfile names to Emacs buffer names.") (defun write-tracking-preamble (stream file file-offset) "Instrument the top of the temporary file to be compiled. The header tells allegro that any definitions compiled in the temp file should be found in FILE exactly at FILE-OFFSET. To get Allegro to do this, this factors in the length of the inserted header itself." (with-standard-io-syntax (let* ((*package* (find-package :keyword)) (source-pathname-form `(cl:eval-when (:compile-toplevel :load-toplevel :execute) (cl:setq excl::*source-pathname* (pathname ,(sys::frob-source-file file))))) (source-pathname-string (write-to-string source-pathname-form)) (header-length (+ (length source-pathname-string) position-form-length-bound)) (position-form `(cl:eval-when (:compile-toplevel :load-toplevel :execute) (cl:setq excl::*partial-source-file-p* ,(- file-offset header-length )))) (position-form-string (write-to-string position-form)) (padding-string (make-string (- position-form-length-bound (length position-form-string)) (write-string source-pathname-string stream) (write-string position-form-string stream) (write-string padding-string stream) (write-char #\newline stream)))) (defun compile-from-temp-file (string buffer offset file) (call-with-temp-file (lambda (stream filename) (when (and file offset (probe-file file)) (write-tracking-preamble stream file offset)) (write-string string stream) (finish-output stream) (multiple-value-bind (binary-filename warnings? failure?) suppress .lisp extension #+(version>= 8 2) (compiler:save-source-level-debug-info-switch t) (excl:*redefinition-warnings* nil)) (compile-file filename)) (declare (ignore warnings?)) (when binary-filename (let ((excl:*load-source-file-info* t) #+(version>= 8 2) (excl:*load-source-debug-info* t)) excl::*source-pathname* (load binary-filename)) (when (and buffer offset (or (not file) (not (probe-file file)))) (setf (gethash (pathname stream) *temp-file-map*) (list buffer offset))) (delete-file binary-filename)) (not failure?))))) (defimplementation swank-compile-string (string &key buffer position filename line column policy) (declare (ignore line column policy)) (handler-case (with-compilation-hooks () (let ((*buffer-name* buffer) (*buffer-start-position* position) (*buffer-string* string)) (compile-from-temp-file string buffer position filename))) (reader-error () nil))) (defun buffer-or-file (file file-fun buffer-fun) (let* ((probe (gethash file *temp-file-map*))) (cond (probe (destructuring-bind (buffer start) probe (funcall buffer-fun buffer start))) (t (funcall file-fun (namestring (truename file))))))) (defun buffer-or-file-location (file offset) (buffer-or-file file (lambda (filename) (make-location `(:file ,filename) `(:position ,(1+ offset)))) (lambda (buffer start) (make-location `(:buffer ,buffer) `(:offset ,start ,offset))))) (defun fspec-primary-name (fspec) (etypecase fspec (symbol fspec) (list (fspec-primary-name (second fspec))))) (defun find-definition-in-file (fspec type file top-level) (let* ((part (or (scm::find-definition-in-definition-group fspec type (scm:section-file :file file) :top-level top-level) (scm::find-definition-in-definition-group (fspec-primary-name fspec) type (scm:section-file :file file) :top-level top-level))) (start (and part (scm::source-part-start part))) (pos (if start (list :offset 1 start) (list :function-name (string (fspec-primary-name fspec)))))) (make-location (list :file (namestring (truename file))) pos))) (defun find-fspec-location (fspec type file top-level) (handler-case (etypecase file (pathname (let ((probe (gethash file *temp-file-map*))) (cond (probe (destructuring-bind (buffer offset) probe (make-location `(:buffer ,buffer) `(:offset ,offset 0)))) (t (find-definition-in-file fspec type file top-level))))) ((member :top-level) (make-error-location "Defined at toplevel: ~A" (fspec->string fspec)))) (error (e) (make-error-location "Error: ~A" e)))) (defun fspec->string (fspec) (typecase fspec (symbol (let ((*package* (find-package :keyword))) (prin1-to-string fspec))) (list (format nil "(~A ~A)" (prin1-to-string (first fspec)) (let ((*package* (find-package :keyword))) (prin1-to-string (second fspec))))) (t (princ-to-string fspec)))) (defun fspec-definition-locations (fspec) (cond ((and (listp fspec) (eq (car fspec) :internal)) (destructuring-bind (_internal next _n) fspec (declare (ignore _internal _n)) (fspec-definition-locations next))) (t (let ((defs (excl::find-source-file fspec))) (when (and (null defs) (listp fspec) (string= (car fspec) '#:method)) (setq defs (excl::find-source-file (second fspec)))) (if (null defs) (list (list fspec (make-error-location "Unknown source location for ~A" (fspec->string fspec)))) (loop for (fspec type file top-level) in defs collect (list (list type fspec) (find-fspec-location fspec type file top-level)))))))) (defimplementation find-definitions (symbol) (fspec-definition-locations symbol)) (defimplementation find-source-location (obj) (first (rest (first (fspec-definition-locations obj))))) (defmacro defxref (name relation name1 name2) `(defimplementation ,name (x) (xref-result (xref:get-relation ,relation ,name1 ,name2)))) (defxref who-calls :calls :wild x) (defxref calls-who :calls x :wild) (defxref who-references :uses :wild x) (defxref who-binds :binds :wild x) (defxref who-macroexpands :macro-calls :wild x) (defxref who-sets :sets :wild x) (defun xref-result (fspecs) (loop for fspec in fspecs append (fspec-definition-locations fspec))) (defun map-function-constants (function fn depth) "Call FN with the elements of FUNCTION's constant pool." (do ((i 0 (1+ i)) (max (excl::function-constant-count function))) ((= i max)) (let ((c (excl::function-constant function i))) (cond ((and (functionp c) (not (eq c function)) (plusp depth)) (map-function-constants c fn (1- depth))) (t (funcall fn c)))))) (defun in-constants-p (fun symbol) (map-function-constants fun (lambda (c) (when (eq c symbol) (return-from in-constants-p t))) 3)) (defun function-callers (name) (let ((callers '())) (do-all-symbols (sym) (when (fboundp sym) (let ((fn (fdefinition sym))) (when (in-constants-p fn name) (push sym callers))))) callers)) (defimplementation list-callers (name) (xref-result (function-callers name))) (defimplementation list-callees (name) (let ((result '())) (map-function-constants (fdefinition name) (lambda (c) (when (fboundp c) (push c result))) 2) (xref-result result))) (defvar *profiled-functions* ()) (defvar *profile-depth* 0) (defmacro with-redirected-y-or-n-p (&body body) session is not reported yet , the user is warned via Y - OR - N - P. As the CL : Y - OR - N - P question is ( for some reason ) not directly sent to the Slime user , the function CL : Y - OR - N - P is temporarily `(let* ((pkg (find-package :common-lisp)) (saved-pdl (excl::package-definition-lock pkg)) (saved-ynp (symbol-function 'cl:y-or-n-p))) (setf (excl::package-definition-lock pkg) nil (symbol-function 'cl:y-or-n-p) (symbol-function (read-from-string "swank:y-or-n-p-in-emacs"))) (unwind-protect (progn ,@body) (setf (symbol-function 'cl:y-or-n-p) saved-ynp (excl::package-definition-lock pkg) saved-pdl)))) (defun start-acl-profiler () (with-redirected-y-or-n-p (prof:start-profiler :type :time :count t :start-sampling-p nil :verbose nil))) (defun acl-profiler-active-p () (not (eq (prof:profiler-status :verbose nil) :inactive))) (defun stop-acl-profiler () (prof:stop-profiler :verbose nil)) (excl:def-fwrapper profile-fwrapper (&rest args) (declare (ignore args)) (cond ((zerop *profile-depth*) (let ((*profile-depth* (1+ *profile-depth*))) (prof:start-sampling) (unwind-protect (excl:call-next-fwrapper) (prof:stop-sampling)))) (t (excl:call-next-fwrapper)))) (defimplementation profile (fname) (unless (acl-profiler-active-p) (start-acl-profiler)) (excl:fwrap fname 'profile-fwrapper 'profile-fwrapper) (push fname *profiled-functions*)) (defimplementation profiled-functions () *profiled-functions*) (defimplementation unprofile (fname) (excl:funwrap fname 'profile-fwrapper) (setq *profiled-functions* (remove fname *profiled-functions*))) (defimplementation profile-report () (prof:show-flat-profile :verbose nil) (when *profiled-functions* (start-acl-profiler))) (defimplementation profile-reset () (when (acl-profiler-active-p) (stop-acl-profiler) (start-acl-profiler)) "Reset profiling counters.") (excl:without-redefinition-warnings (defmethod emacs-inspect ((o t)) (allegro-inspect o))) (defmethod emacs-inspect ((o function)) (allegro-inspect o)) (defmethod emacs-inspect ((o standard-object)) (allegro-inspect o)) (defun allegro-inspect (o) (loop for (d dd) on (inspect::inspect-ctl o) append (frob-allegro-field-def o d) until (eq d dd))) (defun frob-allegro-field-def (object def) (with-struct (inspect::field-def- name type access) def (ecase type ((:unsigned-word :unsigned-byte :unsigned-natural :unsigned-long :unsigned-half-long :unsigned-3byte :unsigned-long32) (label-value-line name (inspect::component-ref-v object access type))) ((:lisp :value :func) (label-value-line name (inspect::component-ref object access))) (:indirect (destructuring-bind (prefix count ref set) access (declare (ignore set prefix)) (loop for i below (funcall count object) append (label-value-line (format nil "~A-~D" name i) (funcall ref object i)))))))) (defimplementation initialize-multiprocessing (continuation) (mp:start-scheduler) (funcall continuation)) (defimplementation spawn (fn &key name) (mp:process-run-function name fn)) (defvar *id-lock* (mp:make-process-lock :name "id lock")) (defvar *thread-id-counter* 0) (defimplementation thread-id (thread) (mp:with-process-lock (*id-lock*) (or (getf (mp:process-property-list thread) 'id) (setf (getf (mp:process-property-list thread) 'id) (incf *thread-id-counter*))))) (defimplementation find-thread (id) (find id mp:*all-processes* :key (lambda (p) (getf (mp:process-property-list p) 'id)))) (defimplementation thread-name (thread) (mp:process-name thread)) (defimplementation thread-status (thread) (princ-to-string (mp:process-whostate thread))) (defimplementation thread-attributes (thread) (list :priority (mp:process-priority thread) :times-resumed (mp:process-times-resumed thread))) (defimplementation make-lock (&key name) (mp:make-process-lock :name name)) (defimplementation call-with-lock-held (lock function) (mp:with-process-lock (lock) (funcall function))) (defimplementation current-thread () mp:*current-process*) (defimplementation all-threads () (copy-list mp:*all-processes*)) (defimplementation interrupt-thread (thread fn) (mp:process-interrupt thread fn)) (defimplementation kill-thread (thread) (mp:process-kill thread)) (defvar *mailbox-lock* (mp:make-process-lock :name "mailbox lock")) (defstruct (mailbox (:conc-name mailbox.)) (lock (mp:make-process-lock :name "process mailbox")) (queue '() :type list) (gate (mp:make-gate nil))) (defun mailbox (thread) "Return THREAD's mailbox." (mp:with-process-lock (*mailbox-lock*) (or (getf (mp:process-property-list thread) 'mailbox) (setf (getf (mp:process-property-list thread) 'mailbox) (make-mailbox))))) (defimplementation send (thread message) (let* ((mbox (mailbox thread))) (mp:with-process-lock ((mailbox.lock mbox)) (setf (mailbox.queue mbox) (nconc (mailbox.queue mbox) (list message))) (mp:open-gate (mailbox.gate mbox))))) (defimplementation wake-thread (thread) (let* ((mbox (mailbox thread))) (mp:open-gate (mailbox.gate mbox)))) (defimplementation receive-if (test &optional timeout) (let ((mbox (mailbox mp:*current-process*))) (flet ((open-mailbox () we are expecting . But first , check for interrupts . (check-slime-interrupts) (mp:with-process-lock ((mailbox.lock mbox)) (let* ((q (mailbox.queue mbox)) (tail (member-if test q))) (when tail (setf (mailbox.queue mbox) (nconc (ldiff q tail) (cdr tail))) (return-from receive-if (car tail))) (mp:close-gate (mailbox.gate mbox)))))) (cond (timeout (open-mailbox) (return-from receive-if (values nil t))) (t (loop (mp:process-wait "receive-if (waiting on gate)" #'mp:gate-open-p (mailbox.gate mbox)) (open-mailbox))))))) (let ((alist '()) (lock (mp:make-process-lock :name "register-thread"))) (defimplementation register-thread (name thread) (declare (type symbol name)) (mp:with-process-lock (lock) (etypecase thread (null (setf alist (delete name alist :key #'car))) (mp:process (let ((probe (assoc name alist))) (cond (probe (setf (cdr probe) thread)) (t (setf alist (acons name thread alist)))))))) nil) (defimplementation find-registered (name) (mp:with-process-lock (lock) (cdr (assoc name alist))))) (defimplementation set-default-initial-binding (var form) (push (cons var form) #+(version>= 9 0) excl:*required-thread-bindings* #-(version>= 9 0) excl::required-thread-bindings)) (defimplementation quit-lisp () (excl:exit 0 :quiet t)) Trace implementations In Allegro 7.0 , we have : < name > can be a normal name or a ( setf name ) (defimplementation toggle-trace (spec) (ecase (car spec) ((setf) (toggle-trace-aux spec)) (:defgeneric (toggle-trace-generic-function-methods (second spec))) ((setf :defmethod :labels :flet) (toggle-trace-aux (process-fspec-for-allegro spec))) (:call (destructuring-bind (caller callee) (cdr spec) (toggle-trace-aux callee :inside (list (process-fspec-for-allegro caller))))))) (defun tracedp (fspec) (member fspec (eval '(trace)) :test #'equal)) (defun toggle-trace-aux (fspec &rest args) (cond ((tracedp fspec) (eval `(untrace ,fspec)) (format nil "~S is now untraced." fspec)) (t (eval `(trace (,fspec ,@args))) (format nil "~S is now traced." fspec)))) (defun toggle-trace-generic-function-methods (name) (let ((methods (mop:generic-function-methods (fdefinition name)))) (cond ((tracedp name) (eval `(untrace ,name)) (dolist (method methods (format nil "~S is now untraced." name)) (excl:funtrace (mop:method-function method)))) (t (eval `(trace (,name))) (dolist (method methods (format nil "~S is now traced." name)) (excl:ftrace (mop:method-function method))))))) (defun process-fspec-for-allegro (fspec) (cond ((consp fspec) (ecase (first fspec) ((setf) fspec) ((:defun :defgeneric) (second fspec)) ((:defmethod) `(method ,@(rest fspec))) ((:labels) `(labels ,(process-fspec-for-allegro (second fspec)) ,(third fspec))) ((:flet) `(flet ,(process-fspec-for-allegro (second fspec)) ,(third fspec))))) (t fspec))) (defimplementation make-weak-key-hash-table (&rest args) (apply #'make-hash-table :weak-keys t args)) (defimplementation make-weak-value-hash-table (&rest args) (apply #'make-hash-table :values :weak args)) (defimplementation hash-table-weakness (hashtable) (cond ((excl:hash-table-weak-keys hashtable) :key) ((eq (excl:hash-table-values hashtable) :weak) :value))) (defimplementation character-completion-set (prefix matchp) (loop for name being the hash-keys of excl::*name-to-char-table* when (funcall matchp prefix name) collect (string-capitalize name))) (defimplementation wrap (spec indicator &key before after replace) (let ((allegro-spec (process-fspec-for-allegro spec))) (excl:fwrap allegro-spec indicator (excl:def-fwrapper allegro-wrapper (&rest args) (let (retlist completed) (unwind-protect (progn (when before (funcall before args)) (setq retlist (multiple-value-list (if replace (funcall replace args) (excl:call-next-fwrapper)))) (setq completed t) (values-list retlist)) (when after (funcall after (if completed retlist :exited-non-locally))))))) allegro-spec)) (defimplementation unwrap (spec indicator) (let ((allegro-spec (process-fspec-for-allegro spec))) (excl:funwrap allegro-spec indicator) allegro-spec)) (defimplementation wrapped-p (spec indicator) (getf (excl:fwrap-order (process-fspec-for-allegro spec)) indicator))
988c88baab033e5a9d9a82062c083719b5236f2368d71952b6a08cb91314a8cd
nyu-acsys/drift
reverse.ml
(*rename error*) let rec reverseinner (xs:int list) (acc:int list) = match xs with [] -> acc | x :: xs' -> reverseinner xs' (x :: acc) let reverse (xs:int list) = reverseinner xs [] let rec make_list n = if n = 0 then [] else n :: make_list (n - 1) let hd (xs:int list) = match xs with [] -> -1 | x::xs' -> x let main (n:int) = let xs = make_list n in if n > 0 then assert(hd (reverse xs) > 0) else () let _ = main 2
null
https://raw.githubusercontent.com/nyu-acsys/drift/51a3160d74b761626180da4f7dd0bb950cfe40c0/tests/benchmarks_call/DOrder/list/reverse.ml
ocaml
rename error
let rec reverseinner (xs:int list) (acc:int list) = match xs with [] -> acc | x :: xs' -> reverseinner xs' (x :: acc) let reverse (xs:int list) = reverseinner xs [] let rec make_list n = if n = 0 then [] else n :: make_list (n - 1) let hd (xs:int list) = match xs with [] -> -1 | x::xs' -> x let main (n:int) = let xs = make_list n in if n > 0 then assert(hd (reverse xs) > 0) else () let _ = main 2
2c3de92df29c450b622f2d9cf7b0d07d6ebdc6ebfe626d34d3e3b596db190f3b
lamdu/hypertypes
Infer.hs
# LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE TemplateHaskell # module Hyper.Class.Infer ( InferOf , Infer (..) , InferChild (..) , _InferChild , InferredChild (..) , inType , inRep ) where import qualified Control.Lens as Lens import GHC.Generics import Hyper import Hyper.Class.Unify import Hyper.Recurse import Hyper.Internal.Prelude | @InferOf e@ is the inference result of @e@. -- -- Most commonly it is an inferred type, using -- > type instance MyType -- -- But it may also be other things, for example: -- -- * An inferred value (for types inside terms) -- * An inferred type together with a scope type family InferOf (t :: HyperType) :: HyperType | A ' HyperType ' containing an inferred child node data InferredChild v h t = InferredChild { _inRep :: !(h t) -- ^ Inferred node. -- -- An 'inferBody' implementation needs to place this value in the corresponding child node of the inferred term body , _inType :: !(InferOf (GetHyperType t) # v) -- ^ The inference result for the child node. -- -- An 'inferBody' implementation may use it to perform unifications with it. } makeLenses ''InferredChild | A ' HyperType ' containing an inference action . -- -- The caller may modify the scope before invoking the action via -- 'Hyper.Class.Infer.Env.localScopeType' or 'Hyper.Infer.ScopeLevel.localLevel' newtype InferChild m h t = InferChild {inferChild :: m (InferredChild (UVarOf m) h t)} makePrisms ''InferChild | @Infer m t@ enables ' Hyper.Infer.infer ' to perform type - inference for @t@ in the ' Monad ' @m@. -- -- The 'inferContext' method represents the following constraints on @t@: -- * @HNodesConstraint ( InferOf t ) ( Unify m)@ - The child nodes of the inferrence can unify in the @m@ ' Monad ' -- * @HNodesConstraint t (Infer m)@ - @Infer m@ is also available for child nodes -- -- It replaces context for the 'Infer' class to avoid @UndecidableSuperClasses@. -- -- Instances usually don't need to implement this method as the default implementation works for them, -- but infinitely polymorphic trees such as 'Hyper.Type.AST.NamelessScope.Scope' do need to implement the method, -- because the required context is infinite. class (Monad m, HFunctor t) => Infer m t where -- | Infer the body of an expression given the inference actions for its child nodes. inferBody :: t # InferChild m h -> m (t # h, InferOf t # UVarOf m) default inferBody :: (Generic1 t, Infer m (Rep1 t), InferOf t ~ InferOf (Rep1 t)) => t # InferChild m h -> m (t # h, InferOf t # UVarOf m) inferBody = fmap (Lens._1 %~ to1) . inferBody . from1 -- TODO: Putting documentation here causes duplication in the haddock documentation inferContext :: proxy0 m -> proxy1 t -> Dict (HNodesConstraint t (Infer m), HNodesConstraint (InferOf t) (UnifyGen m)) # INLINE inferContext # default inferContext :: (HNodesConstraint t (Infer m), HNodesConstraint (InferOf t) (UnifyGen m)) => proxy0 m -> proxy1 t -> Dict (HNodesConstraint t (Infer m), HNodesConstraint (InferOf t) (UnifyGen m)) inferContext _ _ = Dict instance Recursive (Infer m) where {-# INLINE recurse #-} recurse p = Dict \\ inferContext (Proxy @m) (proxyArgument p) type instance InferOf (a :+: _) = InferOf a instance (InferOf a ~ InferOf b, Infer m a, Infer m b) => Infer m (a :+: b) where # INLINE inferBody # inferBody (L1 x) = inferBody x <&> Lens._1 %~ L1 inferBody (R1 x) = inferBody x <&> Lens._1 %~ R1 # INLINE inferContext # inferContext p _ = Dict \\ inferContext p (Proxy @a) \\ inferContext p (Proxy @b) type instance InferOf (M1 _ _ h) = InferOf h instance Infer m h => Infer m (M1 i c h) where # INLINE inferBody # inferBody (M1 x) = inferBody x <&> Lens._1 %~ M1 # INLINE inferContext # inferContext p _ = Dict \\ inferContext p (Proxy @h) type instance InferOf (Rec1 h) = InferOf h instance Infer m h => Infer m (Rec1 h) where # INLINE inferBody # inferBody (Rec1 x) = inferBody x <&> Lens._1 %~ Rec1 # INLINE inferContext # inferContext p _ = Dict \\ inferContext p (Proxy @h)
null
https://raw.githubusercontent.com/lamdu/hypertypes/161142e0d9f503194b85fb6f5b2a5907a1ae3783/src/Hyper/Class/Infer.hs
haskell
Most commonly it is an inferred type, using But it may also be other things, for example: * An inferred value (for types inside terms) * An inferred type together with a scope ^ Inferred node. An 'inferBody' implementation needs to place this value in the corresponding child node of the inferred term body ^ The inference result for the child node. An 'inferBody' implementation may use it to perform unifications with it. The caller may modify the scope before invoking the action via 'Hyper.Class.Infer.Env.localScopeType' or 'Hyper.Infer.ScopeLevel.localLevel' The 'inferContext' method represents the following constraints on @t@: * @HNodesConstraint t (Infer m)@ - @Infer m@ is also available for child nodes It replaces context for the 'Infer' class to avoid @UndecidableSuperClasses@. Instances usually don't need to implement this method as the default implementation works for them, but infinitely polymorphic trees such as 'Hyper.Type.AST.NamelessScope.Scope' do need to implement the method, because the required context is infinite. | Infer the body of an expression given the inference actions for its child nodes. TODO: Putting documentation here causes duplication in the haddock documentation # INLINE recurse #
# LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE TemplateHaskell # module Hyper.Class.Infer ( InferOf , Infer (..) , InferChild (..) , _InferChild , InferredChild (..) , inType , inRep ) where import qualified Control.Lens as Lens import GHC.Generics import Hyper import Hyper.Class.Unify import Hyper.Recurse import Hyper.Internal.Prelude | @InferOf e@ is the inference result of @e@. > type instance MyType type family InferOf (t :: HyperType) :: HyperType | A ' HyperType ' containing an inferred child node data InferredChild v h t = InferredChild { _inRep :: !(h t) , _inType :: !(InferOf (GetHyperType t) # v) } makeLenses ''InferredChild | A ' HyperType ' containing an inference action . newtype InferChild m h t = InferChild {inferChild :: m (InferredChild (UVarOf m) h t)} makePrisms ''InferChild | @Infer m t@ enables ' Hyper.Infer.infer ' to perform type - inference for @t@ in the ' Monad ' @m@. * @HNodesConstraint ( InferOf t ) ( Unify m)@ - The child nodes of the inferrence can unify in the @m@ ' Monad ' class (Monad m, HFunctor t) => Infer m t where inferBody :: t # InferChild m h -> m (t # h, InferOf t # UVarOf m) default inferBody :: (Generic1 t, Infer m (Rep1 t), InferOf t ~ InferOf (Rep1 t)) => t # InferChild m h -> m (t # h, InferOf t # UVarOf m) inferBody = fmap (Lens._1 %~ to1) . inferBody . from1 inferContext :: proxy0 m -> proxy1 t -> Dict (HNodesConstraint t (Infer m), HNodesConstraint (InferOf t) (UnifyGen m)) # INLINE inferContext # default inferContext :: (HNodesConstraint t (Infer m), HNodesConstraint (InferOf t) (UnifyGen m)) => proxy0 m -> proxy1 t -> Dict (HNodesConstraint t (Infer m), HNodesConstraint (InferOf t) (UnifyGen m)) inferContext _ _ = Dict instance Recursive (Infer m) where recurse p = Dict \\ inferContext (Proxy @m) (proxyArgument p) type instance InferOf (a :+: _) = InferOf a instance (InferOf a ~ InferOf b, Infer m a, Infer m b) => Infer m (a :+: b) where # INLINE inferBody # inferBody (L1 x) = inferBody x <&> Lens._1 %~ L1 inferBody (R1 x) = inferBody x <&> Lens._1 %~ R1 # INLINE inferContext # inferContext p _ = Dict \\ inferContext p (Proxy @a) \\ inferContext p (Proxy @b) type instance InferOf (M1 _ _ h) = InferOf h instance Infer m h => Infer m (M1 i c h) where # INLINE inferBody # inferBody (M1 x) = inferBody x <&> Lens._1 %~ M1 # INLINE inferContext # inferContext p _ = Dict \\ inferContext p (Proxy @h) type instance InferOf (Rec1 h) = InferOf h instance Infer m h => Infer m (Rec1 h) where # INLINE inferBody # inferBody (Rec1 x) = inferBody x <&> Lens._1 %~ Rec1 # INLINE inferContext # inferContext p _ = Dict \\ inferContext p (Proxy @h)
fea556406225c6de8f8aa591bbb22180730e1306e67e35ffc2663b308eb37664
simplegeo/erlang
supervisor_1.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 1996 - 2009 . All Rights Reserved . %% The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in %% compliance with the License. You should have received a copy of the %% Erlang Public License along with this software. If not, it can be %% retrieved online at /. %% Software distributed under the License is distributed on an " AS IS " %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See %% the License for the specific language governing rights and limitations %% under the License. %% %% %CopyrightEnd% %% %% Description: Simulates the behaviour that a child process may have. %% Is used by the supervisor_SUITE test suite. -module(supervisor_1). -export([start_child/0, start_child/1, init/1]). -export([handle_call/3, handle_info/2, terminate/2]). start_child(ignore) -> case get(child_ignored) of true -> start_child(); _ -> put(child_ignored, true), ignore end; start_child(error) -> case get(start_child_error) of undefined -> put(start_child_error, set), start_child(); set -> gen_server:start_link(?MODULE, error, []) end; start_child(Extra) -> {ok, Pid} = gen_server:start_link(?MODULE, normal, []), {ok, Pid, Extra}. start_child() -> gen_server:start_link(?MODULE, normal, []). init(normal) -> process_flag(trap_exit, true), {ok, {}}. handle_call(Req, _From, State) -> {reply, Req, State}. handle_info(die, State) -> {stop, died, State}; handle_info(stop, State) -> {stop, normal, State}; handle_info({sleep, Time}, State) -> io:format("FOO: ~p~n", [Time]), timer:sleep(Time), io:format("FOO: sleept~n", []), handle_info({sleep, Time}, State); handle_info(_, State) -> {noreply, State}. terminate(_Reason, _State) -> ok.
null
https://raw.githubusercontent.com/simplegeo/erlang/15eda8de27ba73d176c7eeb3a70a64167f50e2c4/lib/stdlib/test/supervisor_1.erl
erlang
%CopyrightBegin% compliance with the License. You should have received a copy of the Erlang Public License along with this software. If not, it can be retrieved online at /. basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. %CopyrightEnd% Description: Simulates the behaviour that a child process may have. Is used by the supervisor_SUITE test suite.
Copyright Ericsson AB 1996 - 2009 . All Rights Reserved . The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in Software distributed under the License is distributed on an " AS IS " -module(supervisor_1). -export([start_child/0, start_child/1, init/1]). -export([handle_call/3, handle_info/2, terminate/2]). start_child(ignore) -> case get(child_ignored) of true -> start_child(); _ -> put(child_ignored, true), ignore end; start_child(error) -> case get(start_child_error) of undefined -> put(start_child_error, set), start_child(); set -> gen_server:start_link(?MODULE, error, []) end; start_child(Extra) -> {ok, Pid} = gen_server:start_link(?MODULE, normal, []), {ok, Pid, Extra}. start_child() -> gen_server:start_link(?MODULE, normal, []). init(normal) -> process_flag(trap_exit, true), {ok, {}}. handle_call(Req, _From, State) -> {reply, Req, State}. handle_info(die, State) -> {stop, died, State}; handle_info(stop, State) -> {stop, normal, State}; handle_info({sleep, Time}, State) -> io:format("FOO: ~p~n", [Time]), timer:sleep(Time), io:format("FOO: sleept~n", []), handle_info({sleep, Time}, State); handle_info(_, State) -> {noreply, State}. terminate(_Reason, _State) -> ok.
c8d903ad62fc1ed5645cc5becf947d8b2ebe5fd61e9e8cfa47b49b9dd448b742
marksteele/cinched
cinched_log.erl
%%%------------------------------------------------------------------- @author < > ( C ) 2016 , %%% @doc Cinched audit logging service %%% @end Created : 24 Jan 2016 by < > %%%------------------------------------------------------------------- This file is provided to you under the Apache License , %% Version 2.0 (the "License"); you may not use this file except in compliance with the License . You may obtain %% a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY %% KIND, either express or implied. See the License for the %% specific language governing permissions and limitations %% under the License. -module(cinched_log). -behaviour(gen_server). -include("cinched.hrl"). -export([ start_link/0, rotate/0, log/1 ]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -define(SERVER, ?MODULE). -record(state, {current_key, current_hash, log, path, hash}). -spec start_link() -> {ok,pid()}. start_link() -> gen_server:start_link({local, ?SERVER}, ?MODULE,[], []). -spec log(term()) -> ok. log(Payload) -> gen_server:call(?SERVER,{log, Payload},infinity). -spec rotate() -> ok. rotate() -> gen_server:call(?SERVER,rotate). -spec init([]) -> {ok, tuple()}. init([]) -> {ok, SK} = application:get_env(cinched,sk), CurrentKey = cinched:generate_hash(SK), LogPath = filename:join(?PLATFORM_LOG_DIR,"audit"), File = filename:join(LogPath,"audit.log"), ok = filelib:ensure_dir(File), ok = rename_old_log(LogPath, File), {ok, Log} = disk_log:open([{name, audit},{file,File}]), timer:apply_interval(?AUDIT_LOG_SYNC_INTERVAL, gen_server, cast, [?SERVER,sync]), {ok, #state{ hash = SK, current_key = CurrentKey, current_hash = <<>>, log = Log, path = LogPath}}. -spec handle_call(rotate,_,tuple()) -> {reply,ok,tuple()} ; (log,_,tuple()) -> {reply,ok,tuple()}. handle_call(rotate, _From, S=#state{log=Log, path=Path, hash=Hash}) -> File = create_filename(Path), ok = disk_log:reopen(Log,File), CurrentKey = cinched:generate_hash(Hash), {reply, ok, S#state{current_key = CurrentKey, current_hash = <<>>}}; handle_call({log, P}, _, S=#state{log=Log, current_key=K,current_hash=H}) -> EP = term_to_binary(P,[compressed]), {ok, EEP} = nacl:secretbox(EP,K), EEEP = term_to_binary(EEP), Hash = nacl:hash(<<EEEP/binary, H/binary>>), Record = #cinched_log{ hash = Hash, payload = EEEP, timestamp = os:timestamp() }, ok = disk_log:log(Log, Record), NextKey = cinched:generate_hash(K), {reply, ok, S#state{current_key = NextKey, current_hash=Hash}}. -spec handle_cast(sync,tuple()) -> {noreply, tuple()}. handle_cast(sync, S=#state{log=Log}) -> ok = disk_log:sync(Log), {noreply,S}. -spec handle_info(_,tuple()) -> {noreply,tuple()}. handle_info(_Info, State) -> {noreply, State}. -spec terminate(_,_) -> ok. terminate(_Reason, _State) -> ok. -spec code_change(_,tuple,_) -> {ok,tuple()}. code_change(_OldVsn, State, _Extra) -> {ok, State}. -spec create_filename(list()) -> list(). create_filename(Path) -> File = Path ++ "/" ++ "audit.log." ++ integer_to_list(cinched:unix_timestamp()), case filelib:is_file(File) of true -> timer:sleep(1000), create_filename(Path); false -> File end. -spec rename_old_log(list(),list()) -> ok. rename_old_log(Path,File) -> case filelib:is_file(File) of true -> NewFile = create_filename(Path), ok = file:rename(File, NewFile); false -> ok end.
null
https://raw.githubusercontent.com/marksteele/cinched/5284d048c649128fa8929f6e85cdc4747d223427/src/cinched_log.erl
erlang
------------------------------------------------------------------- @doc @end ------------------------------------------------------------------- Version 2.0 (the "License"); you may not use this file a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
@author < > ( C ) 2016 , Cinched audit logging service Created : 24 Jan 2016 by < > This file is provided to you under the Apache License , except in compliance with the License . You may obtain software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY -module(cinched_log). -behaviour(gen_server). -include("cinched.hrl"). -export([ start_link/0, rotate/0, log/1 ]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -define(SERVER, ?MODULE). -record(state, {current_key, current_hash, log, path, hash}). -spec start_link() -> {ok,pid()}. start_link() -> gen_server:start_link({local, ?SERVER}, ?MODULE,[], []). -spec log(term()) -> ok. log(Payload) -> gen_server:call(?SERVER,{log, Payload},infinity). -spec rotate() -> ok. rotate() -> gen_server:call(?SERVER,rotate). -spec init([]) -> {ok, tuple()}. init([]) -> {ok, SK} = application:get_env(cinched,sk), CurrentKey = cinched:generate_hash(SK), LogPath = filename:join(?PLATFORM_LOG_DIR,"audit"), File = filename:join(LogPath,"audit.log"), ok = filelib:ensure_dir(File), ok = rename_old_log(LogPath, File), {ok, Log} = disk_log:open([{name, audit},{file,File}]), timer:apply_interval(?AUDIT_LOG_SYNC_INTERVAL, gen_server, cast, [?SERVER,sync]), {ok, #state{ hash = SK, current_key = CurrentKey, current_hash = <<>>, log = Log, path = LogPath}}. -spec handle_call(rotate,_,tuple()) -> {reply,ok,tuple()} ; (log,_,tuple()) -> {reply,ok,tuple()}. handle_call(rotate, _From, S=#state{log=Log, path=Path, hash=Hash}) -> File = create_filename(Path), ok = disk_log:reopen(Log,File), CurrentKey = cinched:generate_hash(Hash), {reply, ok, S#state{current_key = CurrentKey, current_hash = <<>>}}; handle_call({log, P}, _, S=#state{log=Log, current_key=K,current_hash=H}) -> EP = term_to_binary(P,[compressed]), {ok, EEP} = nacl:secretbox(EP,K), EEEP = term_to_binary(EEP), Hash = nacl:hash(<<EEEP/binary, H/binary>>), Record = #cinched_log{ hash = Hash, payload = EEEP, timestamp = os:timestamp() }, ok = disk_log:log(Log, Record), NextKey = cinched:generate_hash(K), {reply, ok, S#state{current_key = NextKey, current_hash=Hash}}. -spec handle_cast(sync,tuple()) -> {noreply, tuple()}. handle_cast(sync, S=#state{log=Log}) -> ok = disk_log:sync(Log), {noreply,S}. -spec handle_info(_,tuple()) -> {noreply,tuple()}. handle_info(_Info, State) -> {noreply, State}. -spec terminate(_,_) -> ok. terminate(_Reason, _State) -> ok. -spec code_change(_,tuple,_) -> {ok,tuple()}. code_change(_OldVsn, State, _Extra) -> {ok, State}. -spec create_filename(list()) -> list(). create_filename(Path) -> File = Path ++ "/" ++ "audit.log." ++ integer_to_list(cinched:unix_timestamp()), case filelib:is_file(File) of true -> timer:sleep(1000), create_filename(Path); false -> File end. -spec rename_old_log(list(),list()) -> ok. rename_old_log(Path,File) -> case filelib:is_file(File) of true -> NewFile = create_filename(Path), ok = file:rename(File, NewFile); false -> ok end.
1ab3f822a5583f001429ee42ba74c5705b87c9a6d7c7668f01a64019c5ae6754
anuragsoni/http_async
hello_world.ml
open! Core open! Async open Http_async let () = Command_unix.run (Server.run_command ~summary:"Hello world HTTP Server" (fun addr (request, _body) -> Log.Global.info "(%s): %s" (Socket.Address.Inet.to_string addr) (Request.path request); return (Response.create `Ok, Body.Writer.string "Hello World"))) ;;
null
https://raw.githubusercontent.com/anuragsoni/http_async/602889e33b92a842ce7a64dcc259270f529231e3/example/hello_world.ml
ocaml
open! Core open! Async open Http_async let () = Command_unix.run (Server.run_command ~summary:"Hello world HTTP Server" (fun addr (request, _body) -> Log.Global.info "(%s): %s" (Socket.Address.Inet.to_string addr) (Request.path request); return (Response.create `Ok, Body.Writer.string "Hello World"))) ;;
8fae2b3014442d678404690dfa1c43fc7d8b0979a856a15d2de212cf7286b5fa
openvstorage/alba
gcrypt_test.ml
Copyright ( C ) iNuron - This file is part of Open vStorage . For license information , see < LICENSE.txt > Copyright (C) iNuron - This file is part of Open vStorage. For license information, see <LICENSE.txt> *) open! Prelude open Gcrypt open Lwt.Infix let test_encrypt_decrypt_cbc () = let t () = let data = "abc" in let block_len = 16 in let key = String.make 32 'a' in let get_res () = let padded_data = Padding.pad (Bigstring_slice.of_string data) block_len in Cipher.with_t_lwt key Cipher.AES256 Cipher.CBC [] (fun cipher -> Cipher.set_iv cipher (String.make block_len '\000'); Cipher.encrypt cipher padded_data) >>= fun () -> Lwt.return padded_data in get_res () >>= fun res1 -> get_res () >>= fun res2 -> assert (res1 = res2); Cipher.with_t_lwt key Cipher.AES256 Cipher.CBC [] (fun cipher -> Cipher.decrypt_detached cipher res1 0 (Lwt_bytes.length res1)) >>= fun () -> let data' = Padding.unpad res1 in OUnit.assert_equal (Bigstring_slice.to_string data') data; Lwt.return () in Lwt_main.run (t ()) let test_sha1 () = let open Digest in let hd = open_ SHA1 in write hd "abc"; final hd; let res = Option.get_some (read hd SHA1) in assert ("a9993e364706816aba3e25717850c26c9cd0d89d" = to_hex res) let test_ctr_encryption () = small test to verify my understanding of CBC vs CTR encryption modes cbc encrypt ctr using all zeroes iv * should give same result as * ctr encrypting all zeroes with ctr = ctr * should give same result as * ctr encrypting all zeroes with ctr=ctr *) let t () = let block_len = 16 in let key = get_random_string block_len in let ctr = get_random_string block_len in let open Cipher in let encrypted1 = Lwt_bytes.of_string ctr in with_t_lwt key AES256 CBC [] (fun handle -> set_iv handle (String.make block_len '\000'); encrypt handle encrypted1 ) >>= fun () -> let encrypted2 = Lwt_bytes.create block_len in Lwt_bytes.fill encrypted2 0 block_len '\000'; with_t_lwt key AES256 CTR [] (fun handle -> set_ctr handle ctr; encrypt handle encrypted2 ) >>= fun () -> assert (encrypted1 = encrypted2); Lwt.return () in Lwt_main.run (t ()) let test_encrypt_decrypt_ctr () = let block_len = 16 in let t ctr = let data = Lwt_bytes.create_random 100_001 in let key = get_random_string block_len in let open Gcrypt in let open Cipher in let with_handle f = with_t_lwt key AES256 CTR [] f in let encrypted = Lwt_bytes.copy data in with_handle (fun handle -> let () = set_ctr handle ctr in encrypt handle encrypted) >>= fun () -> let decrypt data offset length = let result = Lwt_bytes.extract data offset length in with_handle (fun handle -> set_ctr_with_offset handle ctr offset; decrypt_detached handle result 0 (Lwt_bytes.length result) ) >>= fun () -> Lwt.return result in decrypt encrypted 0 (Lwt_bytes.length encrypted) >>= fun decrypted -> assert (decrypted = data); let test_partial_decrypt offset length = Lwt_log.debug_f "test_partial_decrypt %i %i" offset length >>= fun () -> decrypt encrypted offset length >>= fun decrypted -> assert (decrypted = Lwt_bytes.extract data offset length); Lwt.return () in Lwt_list.iter_s (fun (offset, length) -> test_partial_decrypt offset length) [ (0, 256); (0, 1024); (1024, 256); (1025, 256); (1, 1); (1027, 6); (10_000, 4096); (100_000, 1); ] >>= fun () -> Lwt.return () in Lwt_main.run begin let make_ctr cntr_high cntr_low = let ctr = String.make block_len 'a' in EndianBytes.BigEndian.set_int64 ctr 0 cntr_high; EndianBytes.BigEndian.set_int64 ctr 8 cntr_low; ctr in Lwt_list.iter_s (fun ctr -> Lwt_log.debug_f "ctr = %S" ctr >>= fun () -> t ctr) [ get_random_string block_len; get_random_string block_len; get_random_string block_len; get_random_string block_len; String.make block_len '\000'; String.make block_len '\255'; String.make block_len '\127'; String.make block_len '\128'; make_ctr Int64.max_int Int64.max_int; make_ctr (-1L) Int64.max_int; make_ctr Int64.max_int (-1L); make_ctr (-1L) (-1L); ] end open OUnit let suite = "gcrypt_test" >:::[ "test_encrypt_decrypt_cbc" >:: test_encrypt_decrypt_cbc; "test_sha1" >:: test_sha1; "test_ctr_encryption" >:: test_ctr_encryption; "test_encrypt_decrypt_ctr" >:: test_encrypt_decrypt_ctr; ]
null
https://raw.githubusercontent.com/openvstorage/alba/459bd459335138d6b282d332fcff53a1b4300c29/ocaml/src/tools/gcrypt_test.ml
ocaml
Copyright ( C ) iNuron - This file is part of Open vStorage . For license information , see < LICENSE.txt > Copyright (C) iNuron - This file is part of Open vStorage. For license information, see <LICENSE.txt> *) open! Prelude open Gcrypt open Lwt.Infix let test_encrypt_decrypt_cbc () = let t () = let data = "abc" in let block_len = 16 in let key = String.make 32 'a' in let get_res () = let padded_data = Padding.pad (Bigstring_slice.of_string data) block_len in Cipher.with_t_lwt key Cipher.AES256 Cipher.CBC [] (fun cipher -> Cipher.set_iv cipher (String.make block_len '\000'); Cipher.encrypt cipher padded_data) >>= fun () -> Lwt.return padded_data in get_res () >>= fun res1 -> get_res () >>= fun res2 -> assert (res1 = res2); Cipher.with_t_lwt key Cipher.AES256 Cipher.CBC [] (fun cipher -> Cipher.decrypt_detached cipher res1 0 (Lwt_bytes.length res1)) >>= fun () -> let data' = Padding.unpad res1 in OUnit.assert_equal (Bigstring_slice.to_string data') data; Lwt.return () in Lwt_main.run (t ()) let test_sha1 () = let open Digest in let hd = open_ SHA1 in write hd "abc"; final hd; let res = Option.get_some (read hd SHA1) in assert ("a9993e364706816aba3e25717850c26c9cd0d89d" = to_hex res) let test_ctr_encryption () = small test to verify my understanding of CBC vs CTR encryption modes cbc encrypt ctr using all zeroes iv * should give same result as * ctr encrypting all zeroes with ctr = ctr * should give same result as * ctr encrypting all zeroes with ctr=ctr *) let t () = let block_len = 16 in let key = get_random_string block_len in let ctr = get_random_string block_len in let open Cipher in let encrypted1 = Lwt_bytes.of_string ctr in with_t_lwt key AES256 CBC [] (fun handle -> set_iv handle (String.make block_len '\000'); encrypt handle encrypted1 ) >>= fun () -> let encrypted2 = Lwt_bytes.create block_len in Lwt_bytes.fill encrypted2 0 block_len '\000'; with_t_lwt key AES256 CTR [] (fun handle -> set_ctr handle ctr; encrypt handle encrypted2 ) >>= fun () -> assert (encrypted1 = encrypted2); Lwt.return () in Lwt_main.run (t ()) let test_encrypt_decrypt_ctr () = let block_len = 16 in let t ctr = let data = Lwt_bytes.create_random 100_001 in let key = get_random_string block_len in let open Gcrypt in let open Cipher in let with_handle f = with_t_lwt key AES256 CTR [] f in let encrypted = Lwt_bytes.copy data in with_handle (fun handle -> let () = set_ctr handle ctr in encrypt handle encrypted) >>= fun () -> let decrypt data offset length = let result = Lwt_bytes.extract data offset length in with_handle (fun handle -> set_ctr_with_offset handle ctr offset; decrypt_detached handle result 0 (Lwt_bytes.length result) ) >>= fun () -> Lwt.return result in decrypt encrypted 0 (Lwt_bytes.length encrypted) >>= fun decrypted -> assert (decrypted = data); let test_partial_decrypt offset length = Lwt_log.debug_f "test_partial_decrypt %i %i" offset length >>= fun () -> decrypt encrypted offset length >>= fun decrypted -> assert (decrypted = Lwt_bytes.extract data offset length); Lwt.return () in Lwt_list.iter_s (fun (offset, length) -> test_partial_decrypt offset length) [ (0, 256); (0, 1024); (1024, 256); (1025, 256); (1, 1); (1027, 6); (10_000, 4096); (100_000, 1); ] >>= fun () -> Lwt.return () in Lwt_main.run begin let make_ctr cntr_high cntr_low = let ctr = String.make block_len 'a' in EndianBytes.BigEndian.set_int64 ctr 0 cntr_high; EndianBytes.BigEndian.set_int64 ctr 8 cntr_low; ctr in Lwt_list.iter_s (fun ctr -> Lwt_log.debug_f "ctr = %S" ctr >>= fun () -> t ctr) [ get_random_string block_len; get_random_string block_len; get_random_string block_len; get_random_string block_len; String.make block_len '\000'; String.make block_len '\255'; String.make block_len '\127'; String.make block_len '\128'; make_ctr Int64.max_int Int64.max_int; make_ctr (-1L) Int64.max_int; make_ctr Int64.max_int (-1L); make_ctr (-1L) (-1L); ] end open OUnit let suite = "gcrypt_test" >:::[ "test_encrypt_decrypt_cbc" >:: test_encrypt_decrypt_cbc; "test_sha1" >:: test_sha1; "test_ctr_encryption" >:: test_ctr_encryption; "test_encrypt_decrypt_ctr" >:: test_encrypt_decrypt_ctr; ]
00e715740db215409583200576db04cedee27e8b88aee7504032884f93854041
gfour/gic
tree-let.hs
data Tree = Node Tree Tree | Leaf; result = let t = Node (Node Leaf Leaf) (Node Leaf (Node Leaf Leaf)) in countDepth t; countDepth tr = let max a b = if a > b then a else b in case tr of Leaf -> 1 Node node_0 node_1 -> 1 + (max (countDepth node_0) (countDepth node_1));
null
https://raw.githubusercontent.com/gfour/gic/d5f2e506b31a1a28e02ca54af9610b3d8d618e9a/Examples/Data/tree-let.hs
haskell
data Tree = Node Tree Tree | Leaf; result = let t = Node (Node Leaf Leaf) (Node Leaf (Node Leaf Leaf)) in countDepth t; countDepth tr = let max a b = if a > b then a else b in case tr of Leaf -> 1 Node node_0 node_1 -> 1 + (max (countDepth node_0) (countDepth node_1));
43341311cf2c14452b244f8c41ee1a7deb0430f49bd5ff4e7d65d60c8741382b
compiling-to-categories/concat
Distribution.hs
# LANGUAGE FlexibleInstances # # LANGUAGE TupleSections # # LANGUAGE TypeFamilies # # LANGUAGE MultiParamTypeClasses # # LANGUAGE CPP # # OPTIONS_GHC -Wall # { - # OPTIONS_GHC -Wno - unused - imports # - } -- TEMP -- | A category of probabilistic functions using discrete distributions module ConCat.Distribution where import Prelude hiding (id,(.)) import Data.Map import ConCat.Misc (R) import ConCat.AltCat import qualified ConCat.Category -- | Distribution category newtype Dist a b = Dist (a -> Map b R) -- TODO: generalize Dist to a category transformer | The one category - specific operation . distrib :: (a -> Map b R) -> Dist a b distrib = Dist -- TODO: Perhaps replace 'distrib' with a simpler alternative. -- | Embed a regular deterministic function exactly :: (a -> b) -> Dist a b exactly f = Dist (flip singleton 1 . f) exactly f = Dist ( \ a - > singleton ( f a ) 1 ) instance Category Dist where type Ok Dist = Ord -- needed for Map keys id = exactly id Dist g . Dist f = Dist h where h a = unionsWith (+) [ (p *) <$> g b | (b,p) <- toList (f a) ] -- Finite maps here denote total functions with missing entries being implicitly zero . If so , equality should probably treat explicit zeros as missing entries as the same . It might be worth removing the zero values as they arise . instance AssociativePCat Dist where lassocP = exactly lassocP rassocP = exactly rassocP instance BraidedPCat Dist where swapP = exactly swapP instance MonoidalPCat Dist where Dist f *** Dist g = Dist h where h (a,b) = fromList [ ((c,d),p*q) | (c,p) <- toList (f a), (d,q) <- toList (g b) ] We could default first and second , but the following may be more efficient : first (Dist f) = Dist (\ (a,b) -> mapKeys (,b) (f a)) second (Dist g) = Dist (\ (a,b) -> mapKeys (a,) (g b)) TODO : define ( * * * ) less expensively by using toAscList and fromAscList and -- relying on lexicographic ordering for correctness. instance ProductCat Dist where exl = exactly exl exr = exactly exr dup = exactly dup instance AssociativeSCat Dist where lassocS = exactly lassocS rassocS = exactly rassocS instance BraidedSCat Dist where swapS = exactly swapS instance MonoidalSCat Dist where Dist f +++ Dist g = Dist h where h = mapKeys Left . f ||| mapKeys Right . g -- We could default left and right, but the following may be more efficient: left (Dist f) = Dist (mapKeys Left . f ||| flip singleton 1 . Right) right (Dist g) = Dist (flip singleton 1 . Left ||| mapKeys Right . g) TODO : test whether the first / second and left / right definitions produce more efficient implementations than the defaults . Can GHC optimize away the -- singleton dictionaries in the defaults? instance CoproductCat Dist where inl = exactly inl inr = exactly inr jam = exactly jam instance DistribCat Dist where distl = exactly distl distr = exactly distr instance Num a => ScalarCat Dist a where scale s = exactly (scale s) -- TODO: ClosedCat.
null
https://raw.githubusercontent.com/compiling-to-categories/concat/49e554856576245f583dfd2484e5f7c19f688028/examples/src/ConCat/Distribution.hs
haskell
TEMP | A category of probabilistic functions using discrete distributions | Distribution category TODO: generalize Dist to a category transformer TODO: Perhaps replace 'distrib' with a simpler alternative. | Embed a regular deterministic function needed for Map keys Finite maps here denote total functions with missing entries being implicitly relying on lexicographic ordering for correctness. We could default left and right, but the following may be more efficient: singleton dictionaries in the defaults? TODO: ClosedCat.
# LANGUAGE FlexibleInstances # # LANGUAGE TupleSections # # LANGUAGE TypeFamilies # # LANGUAGE MultiParamTypeClasses # # LANGUAGE CPP # # OPTIONS_GHC -Wall # module ConCat.Distribution where import Prelude hiding (id,(.)) import Data.Map import ConCat.Misc (R) import ConCat.AltCat import qualified ConCat.Category newtype Dist a b = Dist (a -> Map b R) | The one category - specific operation . distrib :: (a -> Map b R) -> Dist a b distrib = Dist exactly :: (a -> b) -> Dist a b exactly f = Dist (flip singleton 1 . f) exactly f = Dist ( \ a - > singleton ( f a ) 1 ) instance Category Dist where id = exactly id Dist g . Dist f = Dist h where h a = unionsWith (+) [ (p *) <$> g b | (b,p) <- toList (f a) ] zero . If so , equality should probably treat explicit zeros as missing entries as the same . It might be worth removing the zero values as they arise . instance AssociativePCat Dist where lassocP = exactly lassocP rassocP = exactly rassocP instance BraidedPCat Dist where swapP = exactly swapP instance MonoidalPCat Dist where Dist f *** Dist g = Dist h where h (a,b) = fromList [ ((c,d),p*q) | (c,p) <- toList (f a), (d,q) <- toList (g b) ] We could default first and second , but the following may be more efficient : first (Dist f) = Dist (\ (a,b) -> mapKeys (,b) (f a)) second (Dist g) = Dist (\ (a,b) -> mapKeys (a,) (g b)) TODO : define ( * * * ) less expensively by using toAscList and fromAscList and instance ProductCat Dist where exl = exactly exl exr = exactly exr dup = exactly dup instance AssociativeSCat Dist where lassocS = exactly lassocS rassocS = exactly rassocS instance BraidedSCat Dist where swapS = exactly swapS instance MonoidalSCat Dist where Dist f +++ Dist g = Dist h where h = mapKeys Left . f ||| mapKeys Right . g left (Dist f) = Dist (mapKeys Left . f ||| flip singleton 1 . Right) right (Dist g) = Dist (flip singleton 1 . Left ||| mapKeys Right . g) TODO : test whether the first / second and left / right definitions produce more efficient implementations than the defaults . Can GHC optimize away the instance CoproductCat Dist where inl = exactly inl inr = exactly inr jam = exactly jam instance DistribCat Dist where distl = exactly distl distr = exactly distr instance Num a => ScalarCat Dist a where scale s = exactly (scale s)
3e32e670a438c12b4656fe55ca243302b8b7dc4c3c81402a0991f8639c943610
composewell/unicode-transforms
NormalizeStream.hs
{-# OPTIONS_GHC -funbox-strict-fields #-} {-# LANGUAGE BangPatterns #-} # LANGUAGE CPP # # LANGUAGE LambdaCase # # LANGUAGE TupleSections # -- | -- Module : Data.Unicode.Internal.NormalizeStream Copyright : ( c ) 2016 ( c ) 2020 -- -- License : BSD-3-Clause -- Maintainer : -- Stability : experimental -- -- Stream based normalization. -- module Data.Unicode.Internal.NormalizeStream ( UC.DecomposeMode(..) , stream , unstream , unstreamC ) where import Data.Char (chr, ord) import GHC.ST (ST(..)) import GHC.Types (SPEC(..)) import qualified Data.Text.Array as A import qualified Unicode.Char as UC #if MIN_VERSION_text(2,0,0) import Data.Text.Internal.Fusion (stream) #else import Data.Bits (shiftR) import Data.Text.Internal.Unsafe.Char (unsafeChr) import Data.Text.Internal.Fusion.Size (betweenSize) import Data.Text.Internal.Encoding.Utf16 (chr2) #endif -- Internal modules import Data.Text.Internal (Text(..)) import Data.Text.Internal.Fusion.Size (upperBound) import Data.Text.Internal.Fusion.Types (Step(..), Stream(..)) import Data.Text.Internal.Private (runText) import Data.Text.Internal.Unsafe.Char (unsafeWrite) ------------------------------------------------------------------------------- -- Reorder buffer to hold characters till the next starter boundary ------------------------------------------------------------------------------- -- | A list of combining characters, ordered by 'UC.combiningClass'. -- Couple of top levels are unrolled and unpacked for efficiency. data ReBuf = Empty | One !Char | Many !Char !Char ![Char] # INLINE insertIntoReBuf # insertIntoReBuf :: Char -> ReBuf -> ReBuf insertIntoReBuf c Empty = One c insertIntoReBuf c (One c0) | UC.combiningClass c < UC.combiningClass c0 = Many c c0 [] | otherwise = Many c0 c [] insertIntoReBuf c (Many c0 c1 cs) | cc < UC.combiningClass c0 = Many c c0 (c1 : cs) | cc < UC.combiningClass c1 = Many c0 c (c1 : cs) | otherwise = Many c0 c1 (cs' ++ (c : cs'')) where cc = UC.combiningClass c (cs', cs'') = span ((<= cc) . UC.combiningClass) cs writeStr :: A.MArray s -> Int -> [Char] -> ST s Int writeStr marr di str = go di str where go i [] = return i go i (c : cs) = do n <- unsafeWrite marr i c go (i + n) cs # INLINE writeReorderBuffer # writeReorderBuffer :: A.MArray s -> Int -> ReBuf -> ST s Int writeReorderBuffer _ di Empty = return di writeReorderBuffer marr di (One c) = do n <- unsafeWrite marr di c return (di + n) writeReorderBuffer marr di (Many c1 c2 str) = do n1 <- unsafeWrite marr di c1 n2 <- unsafeWrite marr (di + n1) c2 writeStr marr (di + n1 + n2) str ------------------------------------------------------------------------------- -- Decomposition of Hangul characters is done algorithmically ------------------------------------------------------------------------------- -- {-# INLINE decomposeCharHangul #-} decomposeCharHangul :: A.MArray s -> Int -> Char -> ST s Int decomposeCharHangul marr j c = if t == chr UC.jamoTFirst then do n1 <- unsafeWrite marr j l n2 <- unsafeWrite marr (j + n1) v return (j + n1 + n2) else do n1 <- unsafeWrite marr j l n2 <- unsafeWrite marr (j + n1) v n3 <- unsafeWrite marr (j + n1 + n2) t return (j + n1 + n2 + n3) where (l, v, t) = UC.decomposeHangul c # INLINE decomposeChar # decomposeChar :: UC.DecomposeMode -> A.MArray s -- destination array for decomposition -> Int -- array index -> ReBuf -- reorder buffer -> Char -- char to be decomposed -> ST s (Int, ReBuf) decomposeChar mode marr index reBuf ch | UC.isHangul ch = do j <- writeReorderBuffer marr index reBuf (, Empty) <$> decomposeCharHangul marr j ch | UC.isDecomposable mode ch = decomposeAll marr index reBuf (UC.decompose mode ch) | otherwise = reorder marr index reBuf ch where # INLINE decomposeAll # decomposeAll _ i rbuf [] = return (i, rbuf) decomposeAll arr i rbuf (x : xs) | UC.isDecomposable mode x = do (i', rbuf') <- decomposeAll arr i rbuf (UC.decompose mode x) decomposeAll arr i' rbuf' xs | otherwise = do (i', rbuf') <- reorder arr i rbuf x decomposeAll arr i' rbuf' xs # INLINE reorder # reorder arr i rbuf c | UC.isCombining c = return (i, insertIntoReBuf c rbuf) | otherwise = do j <- writeReorderBuffer arr i rbuf n <- unsafeWrite arr j c return (j + n, Empty) #if !MIN_VERSION_text(2,0,0) | /O(n)/ Convert a ' Text ' into a ' Stream ' . stream :: Text -> Stream Char stream (Text arr off len) = Stream next off (betweenSize (len `shiftR` 1) len) where !end = off+len # INLINE next # next !i | i >= end = Done shift generates only two branches instead of three in case of range check , works quite a bit faster with backend . | (n `shiftR` 10) == 0x36 = Yield (chr2 n n2) (i + 2) | otherwise = Yield (unsafeChr n) (i + 1) where n = A.unsafeIndex arr i n2 = A.unsafeIndex arr (i + 1) {-# INLINE [0] stream #-} #endif | /O(n)/ Convert a ' Stream ' into a decompose - normalized ' Text ' . unstream :: UC.DecomposeMode -> Stream Char -> Text unstream mode (Stream next0 s0 len) = runText $ \done -> do -- Before encoding each char we perform a buffer realloc check assuming worst case encoding size of two 16 - bit units for the char . Just add an -- extra space to the buffer so that we do not end up reallocating even when -- all the chars are encoded as single unit. let margin = 1 + maxDecomposeLen mlen = (upperBound 4 len + margin) arr0 <- A.new mlen let outer !arr !maxi = encode where -- keep the common case loop as small as possible encode !si !di rbuf = -- simply check for the worst case if maxi < di + margin then realloc si di rbuf else case next0 si of Done -> do di' <- writeReorderBuffer arr di rbuf done arr di' Skip si' -> encode si' di rbuf Yield c si' -> do (di', rbuf') <- decomposeChar mode arr di rbuf c encode si' di' rbuf' -- n <- unsafeWrite arr di c -- encode si' (di + n) rbuf -- keep uncommon case separate from the common case code # NOINLINE realloc # realloc !si !di rbuf = do let newlen = maxi * 2 arr' <- A.new newlen A.copyM arr' 0 arr 0 di outer arr' (newlen - 1) si di rbuf outer arr0 (mlen - 1) s0 0 Empty {-# INLINE [0] unstream #-} we can generate this from UCD maxDecomposeLen :: Int maxDecomposeLen = 32 ------------------------------------------------------------------------------- -- Composition ------------------------------------------------------------------------------- If we are composing we do not need to first decompose . We can just -- compose assuming there could be some partially composed syllables e.g. LV -- syllable followed by a jamo T. We need to compose this case as well. -- Hold an L to wait for V, hold an LV to wait for T. data JamoBuf Jamo L , V or T Hangul Syllable LV or LVT | HangulLV !Char data RegBuf = RegOne !Char | RegMany !Char !Char ![Char] data ComposeState = ComposeNone | ComposeReg !RegBuf | ComposeJamo !JamoBuf ------------------------------------------------------------------------------- Composition of Jamo into Hangul syllables , done algorithmically ------------------------------------------------------------------------------- # INLINE writeJamoBuf # writeJamoBuf :: A.MArray s -> Int -> JamoBuf -> ST s Int writeJamoBuf arr i jbuf = do n <- unsafeWrite arr i (getCh jbuf) return (i + n) where getCh (Jamo ch) = ch getCh (Hangul ch) = ch getCh (HangulLV ch) = ch # INLINE initHangul # initHangul :: Char -> Int -> ST s (Int, ComposeState) initHangul c i = return (i, ComposeJamo (Hangul c)) # INLINE initJamo # initJamo :: Char -> Int -> ST s (Int, ComposeState) initJamo c i = return (i, ComposeJamo (Jamo c)) # INLINE insertJamo # insertJamo :: A.MArray s -> Int -> JamoBuf -> Char -> ST s (Int, ComposeState) insertJamo arr i jbuf ch | ich <= UC.jamoLLast = do j <- writeJamoBuf arr i jbuf return (j, ComposeJamo (Jamo ch)) | ich < UC.jamoVFirst = flushAndWrite arr i jbuf ch | ich <= UC.jamoVLast = do case jbuf of Jamo c -> case UC.jamoLIndex c of Just li -> let vi = ich - UC.jamoVFirst lvi = li * UC.jamoNCount + vi * UC.jamoTCount lv = chr (UC.hangulFirst + lvi) in return (i, ComposeJamo (HangulLV lv)) Nothing -> writeTwo arr i c ch Hangul c -> writeTwo arr i c ch HangulLV c -> writeTwo arr i c ch | ich <= UC.jamoTFirst = do flushAndWrite arr i jbuf ch | otherwise = do let ti = ich - UC.jamoTFirst case jbuf of Jamo c -> writeTwo arr i c ch Hangul c | UC.isHangulLV c -> do writeLVT arr i c ti | otherwise -> writeTwo arr i c ch HangulLV c -> writeLVT arr i c ti where ich = ord ch # INLINE flushAndWrite # flushAndWrite marr ix jb c = do j <- writeJamoBuf marr ix jb n <- unsafeWrite marr j c return (j + n, ComposeNone) {-# INLINE writeLVT #-} writeLVT marr ix lv ti = do n <- unsafeWrite marr ix (chr ((ord lv) + ti)) return (ix + n, ComposeNone) {-# INLINE writeTwo #-} writeTwo marr ix c1 c2 = do n <- unsafeWrite marr ix c1 m <- unsafeWrite marr (ix + n) c2 return ((ix + n + m), ComposeNone) # INLINE insertHangul # insertHangul :: A.MArray s -> Int -> JamoBuf -> Char -> ST s (Int, ComposeState) insertHangul arr i jbuf ch = do j <- writeJamoBuf arr i jbuf return (j, ComposeJamo (Hangul ch)) # INLINE insertIntoRegBuf # insertIntoRegBuf :: Char -> RegBuf -> RegBuf insertIntoRegBuf c (RegOne c0) | UC.combiningClass c < UC.combiningClass c0 = RegMany c c0 [] | otherwise = RegMany c0 c [] insertIntoRegBuf c (RegMany c0 c1 cs) | cc < UC.combiningClass c0 = RegMany c c0 (c1 : cs) | cc < UC.combiningClass c1 = RegMany c0 c (c1 : cs) | otherwise = RegMany c0 c1 (cs' ++ (c : cs'')) where cc = UC.combiningClass c (cs', cs'') = span ((<= cc) . UC.combiningClass) cs # INLINE writeRegBuf # writeRegBuf :: A.MArray s -> Int -> RegBuf -> ST s Int writeRegBuf arr i = \case RegOne c -> do n <- unsafeWrite arr i c return (i + n) RegMany st c [] -> case UC.compose st c of Just x -> do n <- unsafeWrite arr i x return (i + n) Nothing -> do n <- unsafeWrite arr i st m <- unsafeWrite arr (i + n) c return (i + n + m) RegMany st0 c0 cs0 -> go [] st0 (c0 : cs0) where -- arguments: uncombined chars, starter, unprocessed str go uncs st [] = writeStr arr i (st : uncs) go uncs st (c : cs) = case UC.compose st c of Nothing -> go (uncs ++ (c : same)) st bigger Just x -> go uncs x cs where cc = UC.combiningClass c (same, bigger) = span ((== cc) . UC.combiningClass) cs # INLINE flushComposeState # flushComposeState :: A.MArray s -> Int -> ComposeState -> ST s Int flushComposeState arr i = \case ComposeNone -> pure i ComposeReg rbuf -> writeRegBuf arr i rbuf ComposeJamo jbuf -> writeJamoBuf arr i jbuf # INLINE composeChar # composeChar :: UC.DecomposeMode -> A.MArray s -- destination array for composition -> Char -- input char -> Int -- array index -> ComposeState -> ST s (Int, ComposeState) composeChar mode marr = go0 where go0 ch !i !st = case st of ComposeReg rbuf | ich < UC.jamoLFirst -> composeReg rbuf ch i st | ich <= UC.jamoTLast -> do j <- writeRegBuf marr i rbuf initJamo ch j | ich < UC.hangulFirst -> composeReg rbuf ch i st | ich <= UC.hangulLast -> do j <- writeRegBuf marr i rbuf initHangul ch j | otherwise -> composeReg rbuf ch i st ComposeJamo jbuf | ich < UC.jamoLFirst -> do jamoToReg marr i jbuf ch | ich <= UC.jamoTLast -> do insertJamo marr i jbuf ch | ich < UC.hangulFirst -> jamoToReg marr i jbuf ch | ich <= UC.hangulLast -> do insertHangul marr i jbuf ch | otherwise -> jamoToReg marr i jbuf ch ComposeNone | ich < UC.jamoLFirst -> initReg ch i | ich <= UC.jamoTLast -> initJamo ch i | ich < UC.hangulFirst -> initReg ch i | ich <= UC.hangulLast -> initHangul ch i | otherwise -> initReg ch i where ich = ord ch # INLINE jamoToReg # jamoToReg arr i jbuf ch = do j <- writeJamoBuf arr i jbuf initReg ch j # INLINE initReg # initReg !ch !i | UC.isDecomposable mode ch = go (UC.decompose mode ch) i ComposeNone | otherwise = pure (i, ComposeReg (RegOne ch)) # INLINE composeReg # composeReg rbuf !ch !i !st | UC.isDecomposable mode ch = go (UC.decompose mode ch) i st | UC.isCombining ch = do pure (i, ComposeReg (insertIntoRegBuf ch rbuf)) The first char in RegBuf may or may not be a starter . In -- case it is not we rely on composeStarters failing. | RegOne s <- rbuf , UC.isCombiningStarter ch , Just x <- UC.composeStarters s ch = pure (i, (ComposeReg (RegOne x))) | otherwise = do j <- writeRegBuf marr i rbuf pure (j, ComposeReg (RegOne ch)) go [] !i !st = pure (i, st) go (ch : rest) i st = case st of ComposeReg rbuf | UC.isHangul ch -> do j <- writeRegBuf marr i rbuf (k, s) <- initHangul ch j go rest k s | UC.isJamo ch -> do j <- writeRegBuf marr i rbuf (k, s) <- initJamo ch j go rest k s | UC.isDecomposable mode ch -> go (UC.decompose mode ch ++ rest) i st | UC.isCombining ch -> do go rest i (ComposeReg (insertIntoRegBuf ch rbuf)) | RegOne s <- rbuf , UC.isCombiningStarter ch , Just x <- UC.composeStarters s ch -> go rest i (ComposeReg (RegOne x)) | otherwise -> do j <- writeRegBuf marr i rbuf go rest j (ComposeReg (RegOne ch)) ComposeJamo jbuf | UC.isJamo ch -> do (j, s) <- insertJamo marr i jbuf ch go rest j s | UC.isHangul ch -> do (j, s) <- insertHangul marr i jbuf ch go rest j s | otherwise -> do j <- writeJamoBuf marr i jbuf case () of _ | UC.isDecomposable mode ch -> go (UC.decompose mode ch ++ rest) j ComposeNone | otherwise -> go rest j (ComposeReg (RegOne ch)) ComposeNone | UC.isHangul ch -> do (j, s) <- initHangul ch i go rest j s | UC.isJamo ch -> do (j, s) <- initJamo ch i go rest j s | UC.isDecomposable mode ch -> go (UC.decompose mode ch ++ rest) i st | otherwise -> go rest i (ComposeReg (RegOne ch)) | /O(n)/ Convert a ' Stream ' into a composed normalized ' Text ' . unstreamC :: UC.DecomposeMode -> Stream Char -> Text unstreamC mode (Stream next0 s0 len) = runText $ \done -> do -- Before encoding each char we perform a buffer realloc check assuming worst case encoding size of two 16 - bit units for the char . Just add an -- extra space to the buffer so that we do not end up reallocating even when -- all the chars are encoded as single unit. let margin = 1 + maxDecomposeLen mlen = (upperBound 4 len + margin) arr0 <- A.new mlen let outer !arr !maxi = encode SPEC where -- keep the common case loop as small as possible encode !_ !si !di st = -- simply check for the worst case if maxi < di + margin then realloc si di st else case next0 si of Done -> do di' <- flushComposeState arr di st done arr di' Skip si' -> encode SPEC si' di st Yield c si' -> do (di', st') <- composeChar mode arr c di st encode SPEC si' di' st' -- keep uncommon case separate from the common case code # NOINLINE realloc # realloc !si !di st = do let newlen = maxi * 2 arr' <- A.new newlen A.copyM arr' 0 arr 0 di outer arr' (newlen - 1) si di st outer arr0 (mlen - 1) s0 0 ComposeNone {-# INLINE [0] unstreamC #-}
null
https://raw.githubusercontent.com/composewell/unicode-transforms/7e97adff7c230930035640529fb7c200547bd4e0/Data/Unicode/Internal/NormalizeStream.hs
haskell
# OPTIONS_GHC -funbox-strict-fields # # LANGUAGE BangPatterns # | Module : Data.Unicode.Internal.NormalizeStream License : BSD-3-Clause Maintainer : Stability : experimental Stream based normalization. Internal modules ----------------------------------------------------------------------------- Reorder buffer to hold characters till the next starter boundary ----------------------------------------------------------------------------- | A list of combining characters, ordered by 'UC.combiningClass'. Couple of top levels are unrolled and unpacked for efficiency. ----------------------------------------------------------------------------- Decomposition of Hangul characters is done algorithmically ----------------------------------------------------------------------------- {-# INLINE decomposeCharHangul #-} destination array for decomposition array index reorder buffer char to be decomposed # INLINE [0] stream # Before encoding each char we perform a buffer realloc check assuming extra space to the buffer so that we do not end up reallocating even when all the chars are encoded as single unit. keep the common case loop as small as possible simply check for the worst case n <- unsafeWrite arr di c encode si' (di + n) rbuf keep uncommon case separate from the common case code # INLINE [0] unstream # ----------------------------------------------------------------------------- Composition ----------------------------------------------------------------------------- compose assuming there could be some partially composed syllables e.g. LV syllable followed by a jamo T. We need to compose this case as well. Hold an L to wait for V, hold an LV to wait for T. ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- # INLINE writeLVT # # INLINE writeTwo # arguments: uncombined chars, starter, unprocessed str destination array for composition input char array index case it is not we rely on composeStarters failing. Before encoding each char we perform a buffer realloc check assuming extra space to the buffer so that we do not end up reallocating even when all the chars are encoded as single unit. keep the common case loop as small as possible simply check for the worst case keep uncommon case separate from the common case code # INLINE [0] unstreamC #
# LANGUAGE CPP # # LANGUAGE LambdaCase # # LANGUAGE TupleSections # Copyright : ( c ) 2016 ( c ) 2020 module Data.Unicode.Internal.NormalizeStream ( UC.DecomposeMode(..) , stream , unstream , unstreamC ) where import Data.Char (chr, ord) import GHC.ST (ST(..)) import GHC.Types (SPEC(..)) import qualified Data.Text.Array as A import qualified Unicode.Char as UC #if MIN_VERSION_text(2,0,0) import Data.Text.Internal.Fusion (stream) #else import Data.Bits (shiftR) import Data.Text.Internal.Unsafe.Char (unsafeChr) import Data.Text.Internal.Fusion.Size (betweenSize) import Data.Text.Internal.Encoding.Utf16 (chr2) #endif import Data.Text.Internal (Text(..)) import Data.Text.Internal.Fusion.Size (upperBound) import Data.Text.Internal.Fusion.Types (Step(..), Stream(..)) import Data.Text.Internal.Private (runText) import Data.Text.Internal.Unsafe.Char (unsafeWrite) data ReBuf = Empty | One !Char | Many !Char !Char ![Char] # INLINE insertIntoReBuf # insertIntoReBuf :: Char -> ReBuf -> ReBuf insertIntoReBuf c Empty = One c insertIntoReBuf c (One c0) | UC.combiningClass c < UC.combiningClass c0 = Many c c0 [] | otherwise = Many c0 c [] insertIntoReBuf c (Many c0 c1 cs) | cc < UC.combiningClass c0 = Many c c0 (c1 : cs) | cc < UC.combiningClass c1 = Many c0 c (c1 : cs) | otherwise = Many c0 c1 (cs' ++ (c : cs'')) where cc = UC.combiningClass c (cs', cs'') = span ((<= cc) . UC.combiningClass) cs writeStr :: A.MArray s -> Int -> [Char] -> ST s Int writeStr marr di str = go di str where go i [] = return i go i (c : cs) = do n <- unsafeWrite marr i c go (i + n) cs # INLINE writeReorderBuffer # writeReorderBuffer :: A.MArray s -> Int -> ReBuf -> ST s Int writeReorderBuffer _ di Empty = return di writeReorderBuffer marr di (One c) = do n <- unsafeWrite marr di c return (di + n) writeReorderBuffer marr di (Many c1 c2 str) = do n1 <- unsafeWrite marr di c1 n2 <- unsafeWrite marr (di + n1) c2 writeStr marr (di + n1 + n2) str decomposeCharHangul :: A.MArray s -> Int -> Char -> ST s Int decomposeCharHangul marr j c = if t == chr UC.jamoTFirst then do n1 <- unsafeWrite marr j l n2 <- unsafeWrite marr (j + n1) v return (j + n1 + n2) else do n1 <- unsafeWrite marr j l n2 <- unsafeWrite marr (j + n1) v n3 <- unsafeWrite marr (j + n1 + n2) t return (j + n1 + n2 + n3) where (l, v, t) = UC.decomposeHangul c # INLINE decomposeChar # decomposeChar :: UC.DecomposeMode -> ST s (Int, ReBuf) decomposeChar mode marr index reBuf ch | UC.isHangul ch = do j <- writeReorderBuffer marr index reBuf (, Empty) <$> decomposeCharHangul marr j ch | UC.isDecomposable mode ch = decomposeAll marr index reBuf (UC.decompose mode ch) | otherwise = reorder marr index reBuf ch where # INLINE decomposeAll # decomposeAll _ i rbuf [] = return (i, rbuf) decomposeAll arr i rbuf (x : xs) | UC.isDecomposable mode x = do (i', rbuf') <- decomposeAll arr i rbuf (UC.decompose mode x) decomposeAll arr i' rbuf' xs | otherwise = do (i', rbuf') <- reorder arr i rbuf x decomposeAll arr i' rbuf' xs # INLINE reorder # reorder arr i rbuf c | UC.isCombining c = return (i, insertIntoReBuf c rbuf) | otherwise = do j <- writeReorderBuffer arr i rbuf n <- unsafeWrite arr j c return (j + n, Empty) #if !MIN_VERSION_text(2,0,0) | /O(n)/ Convert a ' Text ' into a ' Stream ' . stream :: Text -> Stream Char stream (Text arr off len) = Stream next off (betweenSize (len `shiftR` 1) len) where !end = off+len # INLINE next # next !i | i >= end = Done shift generates only two branches instead of three in case of range check , works quite a bit faster with backend . | (n `shiftR` 10) == 0x36 = Yield (chr2 n n2) (i + 2) | otherwise = Yield (unsafeChr n) (i + 1) where n = A.unsafeIndex arr i n2 = A.unsafeIndex arr (i + 1) #endif | /O(n)/ Convert a ' Stream ' into a decompose - normalized ' Text ' . unstream :: UC.DecomposeMode -> Stream Char -> Text unstream mode (Stream next0 s0 len) = runText $ \done -> do worst case encoding size of two 16 - bit units for the char . Just add an let margin = 1 + maxDecomposeLen mlen = (upperBound 4 len + margin) arr0 <- A.new mlen let outer !arr !maxi = encode where encode !si !di rbuf = if maxi < di + margin then realloc si di rbuf else case next0 si of Done -> do di' <- writeReorderBuffer arr di rbuf done arr di' Skip si' -> encode si' di rbuf Yield c si' -> do (di', rbuf') <- decomposeChar mode arr di rbuf c encode si' di' rbuf' # NOINLINE realloc # realloc !si !di rbuf = do let newlen = maxi * 2 arr' <- A.new newlen A.copyM arr' 0 arr 0 di outer arr' (newlen - 1) si di rbuf outer arr0 (mlen - 1) s0 0 Empty we can generate this from UCD maxDecomposeLen :: Int maxDecomposeLen = 32 If we are composing we do not need to first decompose . We can just data JamoBuf Jamo L , V or T Hangul Syllable LV or LVT | HangulLV !Char data RegBuf = RegOne !Char | RegMany !Char !Char ![Char] data ComposeState = ComposeNone | ComposeReg !RegBuf | ComposeJamo !JamoBuf Composition of Jamo into Hangul syllables , done algorithmically # INLINE writeJamoBuf # writeJamoBuf :: A.MArray s -> Int -> JamoBuf -> ST s Int writeJamoBuf arr i jbuf = do n <- unsafeWrite arr i (getCh jbuf) return (i + n) where getCh (Jamo ch) = ch getCh (Hangul ch) = ch getCh (HangulLV ch) = ch # INLINE initHangul # initHangul :: Char -> Int -> ST s (Int, ComposeState) initHangul c i = return (i, ComposeJamo (Hangul c)) # INLINE initJamo # initJamo :: Char -> Int -> ST s (Int, ComposeState) initJamo c i = return (i, ComposeJamo (Jamo c)) # INLINE insertJamo # insertJamo :: A.MArray s -> Int -> JamoBuf -> Char -> ST s (Int, ComposeState) insertJamo arr i jbuf ch | ich <= UC.jamoLLast = do j <- writeJamoBuf arr i jbuf return (j, ComposeJamo (Jamo ch)) | ich < UC.jamoVFirst = flushAndWrite arr i jbuf ch | ich <= UC.jamoVLast = do case jbuf of Jamo c -> case UC.jamoLIndex c of Just li -> let vi = ich - UC.jamoVFirst lvi = li * UC.jamoNCount + vi * UC.jamoTCount lv = chr (UC.hangulFirst + lvi) in return (i, ComposeJamo (HangulLV lv)) Nothing -> writeTwo arr i c ch Hangul c -> writeTwo arr i c ch HangulLV c -> writeTwo arr i c ch | ich <= UC.jamoTFirst = do flushAndWrite arr i jbuf ch | otherwise = do let ti = ich - UC.jamoTFirst case jbuf of Jamo c -> writeTwo arr i c ch Hangul c | UC.isHangulLV c -> do writeLVT arr i c ti | otherwise -> writeTwo arr i c ch HangulLV c -> writeLVT arr i c ti where ich = ord ch # INLINE flushAndWrite # flushAndWrite marr ix jb c = do j <- writeJamoBuf marr ix jb n <- unsafeWrite marr j c return (j + n, ComposeNone) writeLVT marr ix lv ti = do n <- unsafeWrite marr ix (chr ((ord lv) + ti)) return (ix + n, ComposeNone) writeTwo marr ix c1 c2 = do n <- unsafeWrite marr ix c1 m <- unsafeWrite marr (ix + n) c2 return ((ix + n + m), ComposeNone) # INLINE insertHangul # insertHangul :: A.MArray s -> Int -> JamoBuf -> Char -> ST s (Int, ComposeState) insertHangul arr i jbuf ch = do j <- writeJamoBuf arr i jbuf return (j, ComposeJamo (Hangul ch)) # INLINE insertIntoRegBuf # insertIntoRegBuf :: Char -> RegBuf -> RegBuf insertIntoRegBuf c (RegOne c0) | UC.combiningClass c < UC.combiningClass c0 = RegMany c c0 [] | otherwise = RegMany c0 c [] insertIntoRegBuf c (RegMany c0 c1 cs) | cc < UC.combiningClass c0 = RegMany c c0 (c1 : cs) | cc < UC.combiningClass c1 = RegMany c0 c (c1 : cs) | otherwise = RegMany c0 c1 (cs' ++ (c : cs'')) where cc = UC.combiningClass c (cs', cs'') = span ((<= cc) . UC.combiningClass) cs # INLINE writeRegBuf # writeRegBuf :: A.MArray s -> Int -> RegBuf -> ST s Int writeRegBuf arr i = \case RegOne c -> do n <- unsafeWrite arr i c return (i + n) RegMany st c [] -> case UC.compose st c of Just x -> do n <- unsafeWrite arr i x return (i + n) Nothing -> do n <- unsafeWrite arr i st m <- unsafeWrite arr (i + n) c return (i + n + m) RegMany st0 c0 cs0 -> go [] st0 (c0 : cs0) where go uncs st [] = writeStr arr i (st : uncs) go uncs st (c : cs) = case UC.compose st c of Nothing -> go (uncs ++ (c : same)) st bigger Just x -> go uncs x cs where cc = UC.combiningClass c (same, bigger) = span ((== cc) . UC.combiningClass) cs # INLINE flushComposeState # flushComposeState :: A.MArray s -> Int -> ComposeState -> ST s Int flushComposeState arr i = \case ComposeNone -> pure i ComposeReg rbuf -> writeRegBuf arr i rbuf ComposeJamo jbuf -> writeJamoBuf arr i jbuf # INLINE composeChar # composeChar :: UC.DecomposeMode -> ComposeState -> ST s (Int, ComposeState) composeChar mode marr = go0 where go0 ch !i !st = case st of ComposeReg rbuf | ich < UC.jamoLFirst -> composeReg rbuf ch i st | ich <= UC.jamoTLast -> do j <- writeRegBuf marr i rbuf initJamo ch j | ich < UC.hangulFirst -> composeReg rbuf ch i st | ich <= UC.hangulLast -> do j <- writeRegBuf marr i rbuf initHangul ch j | otherwise -> composeReg rbuf ch i st ComposeJamo jbuf | ich < UC.jamoLFirst -> do jamoToReg marr i jbuf ch | ich <= UC.jamoTLast -> do insertJamo marr i jbuf ch | ich < UC.hangulFirst -> jamoToReg marr i jbuf ch | ich <= UC.hangulLast -> do insertHangul marr i jbuf ch | otherwise -> jamoToReg marr i jbuf ch ComposeNone | ich < UC.jamoLFirst -> initReg ch i | ich <= UC.jamoTLast -> initJamo ch i | ich < UC.hangulFirst -> initReg ch i | ich <= UC.hangulLast -> initHangul ch i | otherwise -> initReg ch i where ich = ord ch # INLINE jamoToReg # jamoToReg arr i jbuf ch = do j <- writeJamoBuf arr i jbuf initReg ch j # INLINE initReg # initReg !ch !i | UC.isDecomposable mode ch = go (UC.decompose mode ch) i ComposeNone | otherwise = pure (i, ComposeReg (RegOne ch)) # INLINE composeReg # composeReg rbuf !ch !i !st | UC.isDecomposable mode ch = go (UC.decompose mode ch) i st | UC.isCombining ch = do pure (i, ComposeReg (insertIntoRegBuf ch rbuf)) The first char in RegBuf may or may not be a starter . In | RegOne s <- rbuf , UC.isCombiningStarter ch , Just x <- UC.composeStarters s ch = pure (i, (ComposeReg (RegOne x))) | otherwise = do j <- writeRegBuf marr i rbuf pure (j, ComposeReg (RegOne ch)) go [] !i !st = pure (i, st) go (ch : rest) i st = case st of ComposeReg rbuf | UC.isHangul ch -> do j <- writeRegBuf marr i rbuf (k, s) <- initHangul ch j go rest k s | UC.isJamo ch -> do j <- writeRegBuf marr i rbuf (k, s) <- initJamo ch j go rest k s | UC.isDecomposable mode ch -> go (UC.decompose mode ch ++ rest) i st | UC.isCombining ch -> do go rest i (ComposeReg (insertIntoRegBuf ch rbuf)) | RegOne s <- rbuf , UC.isCombiningStarter ch , Just x <- UC.composeStarters s ch -> go rest i (ComposeReg (RegOne x)) | otherwise -> do j <- writeRegBuf marr i rbuf go rest j (ComposeReg (RegOne ch)) ComposeJamo jbuf | UC.isJamo ch -> do (j, s) <- insertJamo marr i jbuf ch go rest j s | UC.isHangul ch -> do (j, s) <- insertHangul marr i jbuf ch go rest j s | otherwise -> do j <- writeJamoBuf marr i jbuf case () of _ | UC.isDecomposable mode ch -> go (UC.decompose mode ch ++ rest) j ComposeNone | otherwise -> go rest j (ComposeReg (RegOne ch)) ComposeNone | UC.isHangul ch -> do (j, s) <- initHangul ch i go rest j s | UC.isJamo ch -> do (j, s) <- initJamo ch i go rest j s | UC.isDecomposable mode ch -> go (UC.decompose mode ch ++ rest) i st | otherwise -> go rest i (ComposeReg (RegOne ch)) | /O(n)/ Convert a ' Stream ' into a composed normalized ' Text ' . unstreamC :: UC.DecomposeMode -> Stream Char -> Text unstreamC mode (Stream next0 s0 len) = runText $ \done -> do worst case encoding size of two 16 - bit units for the char . Just add an let margin = 1 + maxDecomposeLen mlen = (upperBound 4 len + margin) arr0 <- A.new mlen let outer !arr !maxi = encode SPEC where encode !_ !si !di st = if maxi < di + margin then realloc si di st else case next0 si of Done -> do di' <- flushComposeState arr di st done arr di' Skip si' -> encode SPEC si' di st Yield c si' -> do (di', st') <- composeChar mode arr c di st encode SPEC si' di' st' # NOINLINE realloc # realloc !si !di st = do let newlen = maxi * 2 arr' <- A.new newlen A.copyM arr' 0 arr 0 di outer arr' (newlen - 1) si di st outer arr0 (mlen - 1) s0 0 ComposeNone
456542796b5872177e09eee699ba0bc42cf53057ebcedc0a0307d64477b8cd54
maralorn/kassandra
Sorting.hs
module Kassandra.Sorting ( sortTasks, saveSorting, SortPosition (SortPosition), SortMode (SortModePartof, SortModeTag), ) where import qualified Data.Aeson as Aeson import Data.Scientific (toRealFloat) import Data.Set (member) import Kassandra.Types (TaskInfos) import qualified Reflex as R import Relude.Extra.Foldable1 (maximum1) import qualified Taskwarrior.Task as Task import qualified Data.Sequence as Seq data SortMode = SortModePartof UUID | SortModeTag Task.Tag deriving stock (Show, Eq, Ord, Generic) makePrismLabels ''SortMode data SortState = HasSortPos Double | WillWrite {iprev :: Double, dprev :: Int, inext :: Double, dnext :: Int} deriving stock (Eq, Show, Ord, Read, Generic) makePrismLabels ''SortState declareFieldLabels [d| data SortPosition t = SortPosition { mode :: R.Behavior t SortMode , list :: R.Behavior t (Seq Task) , before :: R.Behavior t (Maybe UUID) } |] sortTasks :: SortMode -> Seq TaskInfos -> Seq TaskInfos sortTasks mode = Seq.sortOn (getSortOrder mode . (^. #task)) getSortOrder :: SortMode -> Task -> Maybe Double getSortOrder mode = valToNumber <=< (^. #uda % at (sortFieldName mode)) valToNumber :: Aeson.Value -> Maybe Double valToNumber = \case Aeson.Number a -> _Just # toRealFloat a Aeson.String a -> readMaybe $ a ^. unpacked _ -> Nothing sortFieldName :: SortMode -> Text sortFieldName = \case SortModeTag tag -> "kassandra_tag_pos_" <> tag SortModePartof _ -> "kassandra_partof_pos" setSortOrder :: SortMode -> Double -> Task -> Task setSortOrder mode val = #uda %~ at (sortFieldName mode) ?~ Aeson.toJSON val taskInList :: SortMode -> Task -> Bool taskInList (SortModePartof uuid) = (Just uuid ==) . (^. #partof) taskInList (SortModeTag tag) = member tag . Task.tags insertInList :: SortMode -> Task -> Task insertInList (SortModePartof uuid) = #partof ?~ uuid insertInList (SortModeTag tag) = #tags %~ addTag where addTag tags | tag `member` tags = tags | otherwise = tags <> one tag unSetSortOrder :: SortMode -> Task -> Task unSetSortOrder mode = #uda %~ sans (sortFieldName mode) ! Returns a list of tasks for which the UDA attributes need to be changed to reflect the order of the given list . sortingChanges :: SortMode -> Seq Task -> Seq Task sortingChanges mode list = let addState = addSortState (getSortOrder mode) assureSort delta = applyUntil (addState . unSetWorstUnsorted (unSetSortOrder mode) delta) (tasksSorted delta) sortedList = assureSort 0 $ addState list finalList | tasksSorted minDist sortedList = sortedList | otherwise = assureSort minTouchedDist sortedList getWrite (task, sortState) | has #_WillWrite sortState || not (taskInList mode task) = Just . setSortOrder mode (newValue sortState) . insertInList mode $ task | otherwise = Nothing in mapMaybe getWrite finalList applyUntil :: (a -> a) -> (a -> Bool) -> a -> a applyUntil f condition x | condition x = x | otherwise = applyUntil f condition (f x) minOrder, maxOrder, minDist, minTouchedDist :: Double minOrder = -1 maxOrder = - minOrder minDist = 10 ** (-6) minTouchedDist = 10 ** (-3) tasksSorted :: Show a => Double -> Seq (a, SortState) -> Bool tasksSorted = isSortedOn (newValue . (^. _2)) isSortedOn :: Show a => (a -> Double) -> Double -> Seq a -> Bool isSortedOn f delta = \case IsEmpty -> True IsNonEmpty (_ :<|| IsEmpty) -> True IsNonEmpty (x :<|| IsNonEmpty (y :<|| ys)) -> f x + delta < f y && isSortedOn f delta (y <| ys) unSetWorstUnsorted :: (a -> a) -> Double -> Seq (a, SortState) -> Seq a unSetWorstUnsorted _ _ IsEmpty = mempty unSetWorstUnsorted unSet delta (IsNonEmpty (x :<|| xs)) | ((fst <$>) -> fine, (fst <$>) -> IsNonEmpty (a :<|| alsoFine)) <- Seq.breakl ((worst ==) . snd) (toSeq badnesses) = fine <> (unSet a <| alsoFine) | otherwise = error "Assumed wrong invariant in unSetWorstUnsorted" -- The list of badnesses has to contain its maximum where badnesses = go mempty (x :<|| xs) <&> \(a, _, badness) -> (a, badness) worst = maximum1 $ snd <$> badnesses go :: Seq Double -> NESeq (a, SortState) -> NESeq (a, Double, Int) go before ((a, s@(newValue -> value)) :<|| ys) | has #_WillWrite s = (a, value, 0) :<|| rest | otherwise = (a, value, foundBefore + foundAfter) :<|| rest where foundBefore = length $ filter (value - delta <=) before (foundAfter, rest) = maybe (0, mempty) countThroughRest (nonEmptySeq ys) countThroughRest list = (length $ filter (\(_, int, _) -> value + delta >= int) zs, zs) where zs = toSeq (go (value <| before) list) newValue :: SortState -> Double newValue (HasSortPos x) = x newValue (WillWrite iprev (fromIntegral -> dprev) inext (fromIntegral -> dnext)) | dprev + dnext == 0 = iprev | otherwise = iprev + ((inext - iprev) * dprev / (dprev + dnext)) sortStateNext :: SortState -> (Double, Int) sortStateNext (HasSortPos a) = (a, 0) sortStateNext (WillWrite _ _ int d) = (int, d) addSortState :: forall a. (a -> Maybe Double) -> Seq a -> Seq (a, SortState) addSortState f = go (minOrder, 0) where go :: (Double, Int) -> Seq a -> Seq (a, SortState) go (iprev, dprev) list | IsEmpty <- list = mempty | IsNonEmpty (x :<|| xs) <- list , Just int <- f x = (x, HasSortPos int) <| go (int, 0) xs | IsNonEmpty (x :<|| xs) <- list , next@(IsNonEmpty ((_, sortStateNext -> (inext, dnext)) :<|| _)) <- go (iprev, dprev + 1) xs = (x, WillWrite iprev (dprev + 1) inext (dnext + 1)) <| next | IsNonEmpty (x :<|| _) <- list = one (x, WillWrite iprev (dprev + 1) maxOrder 1) insertBefore :: Seq Task -> Seq Task -> Maybe UUID -> Seq Task insertBefore list toInsert = \case Just uuid -> let (front, back) = Seq.breakl ((== uuid) . (^. #uuid)) cleanList in front <> toInsert <> back Nothing -> cleanList <> toInsert where cleanList = filter ((`notElem` (toInsert ^. mapping #uuid)) . (^. #uuid)) list type InsertEvent t = R.Event t (NESeq Task, Maybe UUID) saveSorting :: R.Reflex t => R.Behavior t SortMode -> R.Behavior t (Seq Task) -> InsertEvent t -> R.Event t (NESeq Task) saveSorting modeB listB = R.fmapMaybe nonEmptySeq . R.attachWith attach ((,) <$> modeB <*> listB) where attach (mode, list) (toSeq -> tasks, before) = sortingChanges mode $ insertBefore list tasks before
null
https://raw.githubusercontent.com/maralorn/kassandra/598133b89ab4e4a6209da920636e9e6ee540f38a/apps/kassandra/kassandra/src/Kassandra/Sorting.hs
haskell
The list of badnesses has to contain its maximum
module Kassandra.Sorting ( sortTasks, saveSorting, SortPosition (SortPosition), SortMode (SortModePartof, SortModeTag), ) where import qualified Data.Aeson as Aeson import Data.Scientific (toRealFloat) import Data.Set (member) import Kassandra.Types (TaskInfos) import qualified Reflex as R import Relude.Extra.Foldable1 (maximum1) import qualified Taskwarrior.Task as Task import qualified Data.Sequence as Seq data SortMode = SortModePartof UUID | SortModeTag Task.Tag deriving stock (Show, Eq, Ord, Generic) makePrismLabels ''SortMode data SortState = HasSortPos Double | WillWrite {iprev :: Double, dprev :: Int, inext :: Double, dnext :: Int} deriving stock (Eq, Show, Ord, Read, Generic) makePrismLabels ''SortState declareFieldLabels [d| data SortPosition t = SortPosition { mode :: R.Behavior t SortMode , list :: R.Behavior t (Seq Task) , before :: R.Behavior t (Maybe UUID) } |] sortTasks :: SortMode -> Seq TaskInfos -> Seq TaskInfos sortTasks mode = Seq.sortOn (getSortOrder mode . (^. #task)) getSortOrder :: SortMode -> Task -> Maybe Double getSortOrder mode = valToNumber <=< (^. #uda % at (sortFieldName mode)) valToNumber :: Aeson.Value -> Maybe Double valToNumber = \case Aeson.Number a -> _Just # toRealFloat a Aeson.String a -> readMaybe $ a ^. unpacked _ -> Nothing sortFieldName :: SortMode -> Text sortFieldName = \case SortModeTag tag -> "kassandra_tag_pos_" <> tag SortModePartof _ -> "kassandra_partof_pos" setSortOrder :: SortMode -> Double -> Task -> Task setSortOrder mode val = #uda %~ at (sortFieldName mode) ?~ Aeson.toJSON val taskInList :: SortMode -> Task -> Bool taskInList (SortModePartof uuid) = (Just uuid ==) . (^. #partof) taskInList (SortModeTag tag) = member tag . Task.tags insertInList :: SortMode -> Task -> Task insertInList (SortModePartof uuid) = #partof ?~ uuid insertInList (SortModeTag tag) = #tags %~ addTag where addTag tags | tag `member` tags = tags | otherwise = tags <> one tag unSetSortOrder :: SortMode -> Task -> Task unSetSortOrder mode = #uda %~ sans (sortFieldName mode) ! Returns a list of tasks for which the UDA attributes need to be changed to reflect the order of the given list . sortingChanges :: SortMode -> Seq Task -> Seq Task sortingChanges mode list = let addState = addSortState (getSortOrder mode) assureSort delta = applyUntil (addState . unSetWorstUnsorted (unSetSortOrder mode) delta) (tasksSorted delta) sortedList = assureSort 0 $ addState list finalList | tasksSorted minDist sortedList = sortedList | otherwise = assureSort minTouchedDist sortedList getWrite (task, sortState) | has #_WillWrite sortState || not (taskInList mode task) = Just . setSortOrder mode (newValue sortState) . insertInList mode $ task | otherwise = Nothing in mapMaybe getWrite finalList applyUntil :: (a -> a) -> (a -> Bool) -> a -> a applyUntil f condition x | condition x = x | otherwise = applyUntil f condition (f x) minOrder, maxOrder, minDist, minTouchedDist :: Double minOrder = -1 maxOrder = - minOrder minDist = 10 ** (-6) minTouchedDist = 10 ** (-3) tasksSorted :: Show a => Double -> Seq (a, SortState) -> Bool tasksSorted = isSortedOn (newValue . (^. _2)) isSortedOn :: Show a => (a -> Double) -> Double -> Seq a -> Bool isSortedOn f delta = \case IsEmpty -> True IsNonEmpty (_ :<|| IsEmpty) -> True IsNonEmpty (x :<|| IsNonEmpty (y :<|| ys)) -> f x + delta < f y && isSortedOn f delta (y <| ys) unSetWorstUnsorted :: (a -> a) -> Double -> Seq (a, SortState) -> Seq a unSetWorstUnsorted _ _ IsEmpty = mempty unSetWorstUnsorted unSet delta (IsNonEmpty (x :<|| xs)) | ((fst <$>) -> fine, (fst <$>) -> IsNonEmpty (a :<|| alsoFine)) <- Seq.breakl ((worst ==) . snd) (toSeq badnesses) = fine <> (unSet a <| alsoFine) | otherwise = where badnesses = go mempty (x :<|| xs) <&> \(a, _, badness) -> (a, badness) worst = maximum1 $ snd <$> badnesses go :: Seq Double -> NESeq (a, SortState) -> NESeq (a, Double, Int) go before ((a, s@(newValue -> value)) :<|| ys) | has #_WillWrite s = (a, value, 0) :<|| rest | otherwise = (a, value, foundBefore + foundAfter) :<|| rest where foundBefore = length $ filter (value - delta <=) before (foundAfter, rest) = maybe (0, mempty) countThroughRest (nonEmptySeq ys) countThroughRest list = (length $ filter (\(_, int, _) -> value + delta >= int) zs, zs) where zs = toSeq (go (value <| before) list) newValue :: SortState -> Double newValue (HasSortPos x) = x newValue (WillWrite iprev (fromIntegral -> dprev) inext (fromIntegral -> dnext)) | dprev + dnext == 0 = iprev | otherwise = iprev + ((inext - iprev) * dprev / (dprev + dnext)) sortStateNext :: SortState -> (Double, Int) sortStateNext (HasSortPos a) = (a, 0) sortStateNext (WillWrite _ _ int d) = (int, d) addSortState :: forall a. (a -> Maybe Double) -> Seq a -> Seq (a, SortState) addSortState f = go (minOrder, 0) where go :: (Double, Int) -> Seq a -> Seq (a, SortState) go (iprev, dprev) list | IsEmpty <- list = mempty | IsNonEmpty (x :<|| xs) <- list , Just int <- f x = (x, HasSortPos int) <| go (int, 0) xs | IsNonEmpty (x :<|| xs) <- list , next@(IsNonEmpty ((_, sortStateNext -> (inext, dnext)) :<|| _)) <- go (iprev, dprev + 1) xs = (x, WillWrite iprev (dprev + 1) inext (dnext + 1)) <| next | IsNonEmpty (x :<|| _) <- list = one (x, WillWrite iprev (dprev + 1) maxOrder 1) insertBefore :: Seq Task -> Seq Task -> Maybe UUID -> Seq Task insertBefore list toInsert = \case Just uuid -> let (front, back) = Seq.breakl ((== uuid) . (^. #uuid)) cleanList in front <> toInsert <> back Nothing -> cleanList <> toInsert where cleanList = filter ((`notElem` (toInsert ^. mapping #uuid)) . (^. #uuid)) list type InsertEvent t = R.Event t (NESeq Task, Maybe UUID) saveSorting :: R.Reflex t => R.Behavior t SortMode -> R.Behavior t (Seq Task) -> InsertEvent t -> R.Event t (NESeq Task) saveSorting modeB listB = R.fmapMaybe nonEmptySeq . R.attachWith attach ((,) <$> modeB <*> listB) where attach (mode, list) (toSeq -> tasks, before) = sortingChanges mode $ insertBefore list tasks before
e86d866489d5590142375b83dc11324e2d08bfd69f1a0e3a74df54c01ce078a0
ddmcdonald/sparser
ns-unknown-rd-items-phase3-16001-16400.lisp
(IN-PACKAGE :SP) (DEFPARAMETER SPARSER::*NS-RD-PHASE3-16001-16400* '(".1798_1799GT" ".1799_1800TG" ".444+1G" ".945_946" "474-+30" "4eBP1-S240" "4eBP1-T37" "A+C" "A-1195G" "A-1290G" "A-4" "A-5" "A-D" "A-related" "A-rich" "A-type" "A1" "A146T" "A167T" "A188T" "A1L" "A2" "A276D" "A2a" "A2b" "A30" "A305A" "A30P" "A369T" "A375P" "A5" "A533D" "A549-miR-622" "A549-pLKO" "A549-shDR5" "A550V" "A572V" "A573V" "A628S5" "A8" "A89S" "AA+GA" "ABCSG-90" "ABI" "ABI-3730" "ABI7900" "ABL-inhibitor" "AC" "AC-220" "AC-T" "AC-TH" "ACA-motif" "ACLY-induced" "ACLY-α-ketoglutarate-ETV4" "ACNU-induced" "ACO1" "ACSL4" "ACSL4-functional" "ACTR2" "ACh" "ADAM" "ADR-treatment" "ADRs" "AFMA070WD1" "AG" "AG+GG" "AG-014699" "AG-221" "AGC" "AGGAU" "AGGGT" "AG + GG" "AIIIa" "AJCC" "AKT-DN" "AKT-FOXG1-Reelin" "AKT-HK2" "AKT-mTOR" "AKT-mTOR-p70S6K" "AKT8055" "AKTS1" "ALK-DelGR" "ALK-ECD-Fc" "ALK-FAM150" "ALK-LTK" "ALK-R" "ALK-rearrangement" "ALK-rearrangements" "ALLGGEN" "ALLs" "AMGIO2" "AMIGO1" "AMIGO3" "AMIS" "AML-ETO-expressing" "AML-ETO-induced" "AML1-ETO" "AML1-ETO-depleted" "AML1-ETO-expressing" "AML1-ETO-induced" "AML1-ETO-knockdown" "AMPKα" "ANGPLT2" "ANKRD13" "ANKRD13A" "ANX" "ANX4" "ANXA3" "ANX–2" "ANX–4" "AO" "AOC" "AP-1-dependent" "AP-1-mediated" "AP1-dependent" "AP24163" "AP24534" "APACHE" "APACHE-II" "AR-AKT" "AR-FL" "AR-FL-overexpressing" "AR-V" "AR-V-targeted" "AR-V2" "AR-V3" "AR-V4" "AR-V9" "AR-Vs" "AR-positive" "AR-status" "AR45" "ARBS" "ARE-RNA" "ARE1~4" "ARE2" "ARE3" "ARE4" "ARMS-qPCR" "AS-NMD" "ASC-J9" "ASCL4" "ASCO" "ASF-ESE" "ASO-miR-346" "ASO-miR-346-treated" "AT10" "AT20" "AT7867" "ATAD2-MKK3" "ATB" "ATB-737" "ATC-28" "ATCC" "ATI-KD" "ATM-defective" "ATM-dependent" "ATM-specificity" "ATMIN-null" "ATP-competitive" "ATR-Substrate" "ATRi2" "ATS" "ATTS" "AUBPs" "AUG" "AUKB" "AZD" "AZD-2281" "AZD-6738" "AZD-7762" "AZD1208" "AZD1840" "AZD6378" "Abcam" "Abdel-Ghany" "Ac-Arg-His-Lys" "AcGFP" "Achilles" "Ad" "Ad-LacZ" "Ad-cycE" "Ad-cycE-infected" "Ad-cycE-treated" "Ad-induced" "Ad-mediated" "Ad12" "Ad5-Null" "Ad5-PKCδ-transfected" "Ad5-null" "Ad5-null-transfected" "AdGFP" "AdGFP-HBx-infected" "AdGFP-HCCR" "AdGFP-HCCR-infected" "AdSqLCs" "Adwt" "Affymetrix" "Africa" "African" "African-American" "African-Americans" "Africans" "African–American" "Ahn" "Ahr" "Ai" "Ai+Di" "Aigner" "Aki1" "Akt-CA" "Akt-PH-RFP" "Akt-PS473" "Akt-S473" "Akt-pathways" "Akt1" "Akti" "Akti-2" "Akti1" "Ala2Val" "Alexa" "AlexaFluor-488" "Alzheimer" "America" "American" "Americans" "Amigo" "Amino-acid" "Aminopyrazine" "Anderson" "Androgen-deprivation" "AngII" "Annexin-FITC" "Antagomir-9-3p" "Antagomirs" "Anthriscus" "Apgar" "Arg399Gln" "Aristolactam" "Armt1" "ArrayScan" "Article" "AsPC-1-pBABE-TAZ" "Ashkenazi" "Asian" "Asians" "Asp-N-generated" "Astra" "AstraZeneca" "Astragali" "Astragalus" "Atg5-Atg12" "Au-rich" "AuNP" "AuNPs" "Aukema" "Auranen" "Aurora-A-Borealis" "Aurora-a" "Australia" "Auto-Regulated" "AutoDock" "Aviel-Ronen" "AzadC" "Aβ" "A–5C" "A–C" "A–D" "B-2" "B-LMP1" "B-LMP1and" "B-NHL" "B-SLL" "B-lineage" "B-lymphoid" "B-malignancies" "B-miR-346" "B-regulated" "B-type" "B1" "B16-GFP-MAGE-C2" "B2" "B3" "B4" "BAF3-JAK2-V617F" "BAK-dependent" "BAL-L" "BALB" "BALF" "BAP-1" "BAX" "BCAR4" "BCSCs" "BC‐related" "BD" "BDL" "BEL7402" "BG" "BG-12" "BG-647-SiR" "BGJ398" "BH3-mimetic" "BH3-mimetics" "BH3-only" "BICseq" "BIMEL" "BIN-67" "BJ" "BK" "BK-SS" "BL-like" "BL1" "BLT1-NAD(P)H" "BLT1-NOX-ROS-EGFR-PI3K-ERK1" "BLT1-NOX-linked" "BMI" "BMN" "BMN-673" "BN82685" "BODIPY-493" "BODIPY-GTP-binding" "BPIFA1" "BRAC2" "BRAFV" "BRAFV600" "BRCA-2" "BRCA1-A" "BRCA2-null" "BRCAness" "BRD9" "BS" "BS153" "BSA-Au" "BT168" "BT275" "BT747" "BTC27" "BTC29" "BTCs" "BTZ-resistnat" "BTZ-susceptibility" "BV-176-treated" "BaF3-JAK2-V617F" "BaF3-JAK2-V617F-R" "Balb" "Bardoxolone" "Bardoxolone-methyl" "Barrios-Garcia" "Basal-type" "Bax" "Bay11-7802" "Bay117085" "Bay11–7802" "Bayes" "Bcl" "Bcl-2" "Bcl-xl" "Beesley" "Begg" "Beige" "Bel-7704" "Berkeley" "Berkeley-SS" "Bernasconi" "Bernier-Villamor" "Biacore" "BigDye" "Bim" "Bio" "Bio-6-OAP" "Bio-6-OAP-Skp1" "BioGRID" "Biomax" "Biosystems" "Birt-Hogg-Dubé" "Birt–Hogg–Dubé" "Blc-2" "Blenkiron" "Blood" "Blood-borne" "Bni-1" "Boehringer" "Bond-Max" "Bonferroni" "Bortezomib" "Boyden" "Braak" "Brattain" "Brazil" "BrdUrd" "Bre1" "Bric-a-brac" "Broad-Novartis" "Broad-spectrum" "Bruton" "Burkitt" "B–D" "B–S" "B–S7D" "C+202T" "C-124T" "C-146T" "C-5" "C-899G" "C-C" "C-PARP1" "C-T" "C-T-T-T" "C-glucose" "C-labeled" "C-labelled" "C-labelling" "C-methyl-Met" "C-phosphate-G" "C-rich" "C-serine" "C-terminally" "C0" "C1" "C124R" "C147R" "C18" "C19ORF5" "C2" "C2-TRIM28" "C20" "C2089" "C28" "C2BBel" "C3" "C3H" "C57BK" "C6" "C62" "C62S" "C7ORF60" "CA16" "CA19" "CA19-9" "CA199" "CA19–9" "CACCAGTAATATGC-3" "CACGTG" "CACNA2D" "CAECs" "CAIRO-2" "CAL-101" "CAP" "CAP18" "CARD16" "CAS-1" "CASMC" "CASMCs" "CASP3DN" "CASP8AP2" "CAV1-interaction" "CAV1-interactions" "CB17-Prkdc" "CBF-AML" "CBF-AMLs" "CBF-fusion" "CBFB-MYH11-expressing" "CBFB-MYH11-induced" "CBL-depleted" "CBL-mutant" "CBRH-7919" "CC+CG" "CC-chemokine" "CCAAT" "CCAAT-enhancer-binding" "CCAT2" "CCD" "CCD66" "CCDC66" "CCDs" "CCID" "CCIDs" "CCL" "CCL227" "CCR4-NOT-deadenylase" "CCT031374" "CD-C451A" "CD-C464A" "CD-transfected" "CD102" "CD133-integrin-Par" "CD133WT" "CD133ΔC11" "CD133ΔC3" "CD133ΔC3-7" "CD133ΔC7" "CD133ΔE5" "CD135" "CD168" "CD25 + " "CD28null" "CD28nullCD8 + " "CD28 + " "CD317" "CD326" "CD44 + " "CD4 + " "CD4 +  " "CD52" "CD74‐positive" "CD8 + " "CD90" "CDC25s" "CDDO-Im" "CDK2-mediated" "CDK6-Del" "CDK6-Del-directed" "CDKNA2A" "CEER" "CELSR" "CELSR1" "CENP-1" "CENPJ" "CEP17" "CEP8" "CEU" "CFpac‐1" "CG" "CGA-arginine" "CGK733-inducecd" "CGP3" "CGP53353" "CH25OH" "CHASM" "CHD7" "CHDs" "CHEK2*1100delC" "CHI3L1" "CHOP-like" "CI=1.09–1.24" "CI=1.16–1.37" "CID2950007" "CIMP" "CIP2A–PP2A–c-Myc–dependent" "CJ" "CK1δ" "CKB" "CKB-C283S" "CKD" "CKLF-like" "CL1–5" "CLASH" "CLB-GAR" "CLDs" "CMTM1-8" "CMTMs" "CMV6-Klotho" "CN03" "CN03treatment" "CNS2-deficient" "CNS2-mediated" "CNVer" "CNVs" "CNVseq" "CONSORT" "COPD-PH" "COX-2–1195" "COX-2–765" "COX-2–homozygous" "COX-2–null" "COX-PG" "COX3" "CPEB3" "CPEB4" "CPEBs" "CR-0560" "CR0004" "CR0010" "CR1515" "CR1744" "CRFS" "CRISPR" "CRISPR-Cas9" "CRISPR-Cas9-based" "CRISPR-Cas9-mediated" "CRL-1848" "CSC-like" "CSCS" "CSCs" "CSDC2" "CSDE1" "CSK" "CT+CC" "CT+TT" "CT04" "CTC" "CTD" "CU" "CU-element" "CV" "CVAD" "CVs" "CWR22rv1" "CXB1" "CXCL" "CXCL-12" "CXCL12-mediated" "CXCL14" "CYT-387" "CaMKK" "CaMKKβ" "CaP8" "CaP8 " "Café-au-lait" "Cajal-Retzius" "Caki2" "Caki‐1" "Cancer" "Cardiac-specific" "Carney-Stratakis" "Case1" "Case6" "Casitas" "Catlett-Falcone" "Caucasians" "Cav1" "Cbl_hi" "Cbl_lo" "CdLS-like" "Cdc42" "Cdc42Q61L" "Cdc42‐GTP" "Cdk1" "CellSearch" "Cells" "Cellworks" "Centipeda" "ChIP-PCR" "ChIP-qPCR" "ChIP–quantitative" "ChT" "ChT-L" "Chan" "Chang" "Chaoshan" "Charlson" "CheR-like" "Chem" "Cheminformatics-based" "Chen" "Cheng" "CherryLacR" "Chi-square" "Chi-squared" "Chiron99021" "Chk-1" "Chou" "Chou-Talalay" "Chr5" "Christopher" "Chung" "Cip" "Cip1" "ClG" "ClinicalTrials" "Clinico-pathological" "CoA-Cy3" "CoA-Cy5" "CoA-biotin" "CoA-fluorophore" "Collagen1a1" "College" "Colo-206" "Colonoscopies" "Con" "Con-injected" "Con-treated" "Cornelia" "Corp" "Cox-regression" "Cpeb4-mediated" "Cre-recombinase" "Cre-transducedPhb2" "CreERT2" "Crohn" "Cross-sectional" "Cr " "Cse4" "Ct" "Ctrl" "Cu" "Cul3" "Cullin1" "Cullin1-myc-ΔC" "Cullin1-myc-ΔN" "Cx43-mRFP" "Cybulski" "Cyclapolin1" "Cyp450" "Cyr61-PI3K" "Cys-Sec" "Cys-pair" "CytoSelect" "Cytoscape" "Cytox" "Czech" "Cα" "C‐kinase" "C‐to" "C–Cdc20–substrate" "C–E" "D-3" "D-aspartate" "D-aspartyl" "D10" "D10A" "D10Y" "D17S945" "D2" "D233–K202–S276" "D25N" "D283-effLuc" "D3" "D54" "D6" "DAAs" "DAB21P" "DAB2IPloss" "DAB2IP‐deficient" "DAB2IP‐knockdown" "DAB2IP‐reduced" "DAB2IP‐reduction" "DAB2IP‐retained" "DAF-16" "DAP-81" "DAVID" "DAZAP" "DBF4B" "DC-3" "DC-C" "DCC-2036" "DCLK1" "DEmiRs" "DFG-in" "DG" "DH-PH" "DHPLC" "DIANA-miR" "DIANA-miRPath" "DIANA-microT" "DIANA-mirPath" "DKC" "DLEU1" "DLG" "DLG-motif" "DNA-DNA" "DNA-DSBs" "DNA-DSBs-related" "DNA-End" "DNA-binding" "DNA-damage-induced" "DNA-methyltransferase" "DNA-protein" "DNAH7" "DNAJA2" "DNAJC10" "DNA–DNA" "DNA–PK-dependent" "DNA–protein" "DNM3os" "DNMT-1between" "DNMT3" "DOC‐2" "DOI" "DOX-DNA" "DPL" "DPP3" "DPT" "DR5-mediated" "DRB5" "DRFI" "DSBs" "DTX" "DUB-cofactor" "DUF89" "Daniela" "Dapi" "Darwinian-like" "Davicioni" "Davis" "DcRs" "De-conjugation" "De-differentiated" "Decidual-stromal-cell-derived" "Defensin2" "Diaphanous‐related" "Dictostylium" "Dnd1" "Dohmen" "Dong" "Doppler" "Dose-response" "Double-hit" "Dovizio" "Doyle" "Drip" "Drozd" "DsRed-Rab5-positive" "Dunn" "E-CSC-like" "E-CSCs" "E-FRET" "E-box" "E-box-containing" "E-boxes" "E-cadherin-1" "E-cadherin-like" "E-regulated" "E1-like" "E1308X" "E169del" "E1978X" "E1b" "E1b55K" "E2-signaling" "E2-ubiqitination" "E2419" "E260Term" "E260term" "E2F-regulated" "E2F1-4" "E2F1-His" "E2F1-K63" "E2F1-binding" "E2F1-downstream" "E2F1-driven" "E2F1-mediated" "E2F1-related" "E2F1-target" "E2F3a" "E2F3b" "E2β" "E3-ligase" "E3-like" "E3-ubiquitin" "E3-ubiqutin" "E380A" "E5" "E596QS" "E6" "E6-expressing" "E6-induced" "E6-mediated" "E6-stimulated" "E6E7" "E7" "E7449-dose" "E746-A750" "E748-A752" "E7directly" "E9-pSPL3" "E9.5" "EADC" "EAV1" "EAV1-exressiong" "EAV3" "EBNA1itself" "EBPb" "EBPα-complex" "EBPε" "EBV-LMP1" "EBarrays" "EC109-RASSF8" "EC109-RASSF8-RNAi" "EC109-miR-101" "EC50" "EC9706-miR-101" "ECFP2" "ECFP4" "ECH‐associated" "ECM-receptor" "ECOG-PS" "ED" "ED-1" "EEA1-containing" "EF" "EF-24" "EG" "EGAS00001001302" "EGF-Src-β4" "EGF-TM7" "EGF-like" "EGFP" "EGFP-Fbxw7a" "EGFR-AKT" "EGFR-AKT-mTOR" "EGFR-NSCLC" "EGFR-PI3-kinase-ERK1" "EGFR-PI3K-ERK1" "EGFR-TKIs-naïve" "EGFR-TKIs-resistance" "EGFR-TKIs-resistant" "EGFRvIII" "EGanimals" "EJ-1" "EKR1" "EL" "ELF" "ELF-EMF" "ELF-EMF-dependent" "ELF-EMF-exposed" "ELF-EMF-exposure" "ELF-EMF-induced" "ELISPOT" "EMF-ELF" "EML-4ALK" "EML-ALK" "EML4-ALK-induced" "EML4-ALK-mediated" "EML4-ALK-rearranged" "EMQA" "EMQA-paclitaxel" "EMT-CTCs" "EMT-like" "EMT-suppressive" "ENSMUSP00000005504" "ENSMUSP00000130379" "ENaC" "EORTC" "EPITHELIAL" "EPSM" "ER-CDH1" "ER-positive" "ER-siIGF1R" "ER-α36" "ER-α66" "ERD7" "ERE-luciferase" "EREs" "ERGIC3" "ERK-dependent" "ERMS" "ERS" "ERp29\\MGMT" "ERα-and" "ERα-negative" "ERα-replete" "ERα-splice" "ER‐positive" "ES7" "ES8" "ESC-like" "ESEs" "ESMO" "ETGE" "ETO-treatment" "ETV5" "EU" "EVTs" "EVs" "EWSC" "EWSCs" "Early-stage" "East-Asian" "EdU-incorporation" "Edu" "Edward" "Effects" "Egger" "Egypt" "Eighty-nine" "Ell-OE" "Ell3-OE" "Emodin-3-methyl" "End1" "Endothelial-specific" "English" "EpRE" "EpREs" "Epcam" "Epithelial-mesenchymal" "Epithelial-to-mesenchymal" "Epstein-Barr" "Epstein–Barr" "ErbB" "ErbB2–ErbB3" "ErbB2–ErbB3-mediated" "ErbB3" "ErbB4-mediated" "Estrogen" "Estrogen-and" "Europe" "European" "Europeans" "Evans" "Ewing’s" "Ex2-28C" "ExAC" "Exosomes" "Eμ-Myc" "F+I" "F-FDG" "F-SNP" "F-actin" "F-purification" "F-purified" "F26IIB" "F9" "F9-derived" "FA-Lys" "FA-chromatin" "FA-histone" "FA-like" "FADH" "FAF2" "FAK-Tyr" "FAK-mediated" "FAM150A-ALK" "FAM150A-HA" "FAM150A " "FAM150B-ALK" "FAM150B-HA" "FAM150B " "FAM150ba" "FAM150bb" "FANC-proficient" "FANCC-proficient" "FANCD2-siRNA-depleted" "FANCP" "FANCcore" "FAs" "FBOX5" "FBX011" "FCFP2" "FCFP4" "FCFP6" "FERM" "FERM-domain" "FEV1" "FEZF1" "FFBF" "FG-Sh-TAZ-1" "FGF-2and" "FGF2-dependentstimulation" "FGF2R" "FGF2Rα" "FGFR-3" "FGFs" "FHs" "FIB-4" "FIGO" "FISH" "FISH-negative" "FISH-positive" "FKB12-rapamycin-binding" "FLAG" "FLAG-LoxP-SNAP" "FLAG-SNAP-tag" "FLAG-SNAP-tagged" "FLAG-epitope-tagged" "FLAG-tag" "FLCN-1" "FLCN-dificient" "FLT3-ITD" "FLT3-ITD-D835Y" "FLT3-ITD-dependent" "FLT3-ITD-mediated" "FLT3-ITD-positive" "FLT3L" "FLuc-only" "FM" "FMCDs" "FMS-like" "FNIII" "FO" "FOPflash" "FOXA1-dependency" "FOXC-2" "FOXO" "FOXO1A3" "FOXO3-GFP-transfected" "FOXO3a-miR-622" "FPE" "FRB" "FSL-1" "FUCCI" "FVB-MMTV-ErbB2" "Fa-CI" "Fancd2" "Fancd2-single" "FaraAMP" "FaraATP" "Farnesyl-transferase" "Fatostain" "Fayyad-Kazan" "Fbxl5-mediated" "Fbxo1717" "Fbxw7" "Fbxw7α-SOX10" "Fbxw7αin" "Fbxw7β" "Fbxw7γ" "Fc" "Fc=1.08±0.02" "Fc=1.08±0.04" "Fcγ" "FcγR" "FcγRI" "FcγRII" "FcγRIIA131H" "FcγRIII" "FcγRIIIA" "FcγRIIIA158F" "FcγRIIIA158V" "FcγRIIIA " "FcγRs" "Fe" "Fe(II)-dependent" "Fenugreek" "Ferlay" "Fernandez" "Ferroportin" "Ferroportin-1" "Fichorova" "Fifty-seven" "Fifty-three" "Fig.S6C" "First-line" "Fission-deficient" "Flag" "Flag-Omomyc" "Flag-tag" "Flcn" "Flcn-null" "Flow-FISH" "Flow-cytometry" "Flow-cytometry-based" "Flt–3" "Fluc" "Fluorizoline" "Fm" "Fms-Like" "Fms-like" "Fogh" "Follow-up" "Formin" "Forty-eight" "Forty-five" "Forty-nine" "Forty-one" "Forty-seven" "Forty-six" "Forty-three" "Forty-two" "Fos-B" "Fos-L1" "Fos-L2" "Fosl1" "Foundation-7" "Four-two" "Foxa-dependent" "Fpm" "Fragile–X" "Fraumeni" "Freed-Pastor" "French" "Freud" "Freud1" "Fu" "Fus" "F‐actin" "F–K" "F–S6J" "G-765C" "G-899C" "G-LISA" "G-actin" "G-allele" "G-quadruplexes" "G-rich" "G-strand" "G-trap" "G0" "G0-G1" "G007-LK" "G1" "G1-G0" "G1-S" "G1-arrest" "G12C" "G13D" "G13R" "G1–S" "G2" "G2-M" "G2-and" "G302–G303–G304–G305" "G60–T75" "G6p" "GA" "GA+AA" "GA+GG" "GABA)–the" "GABP" "GADD45-α" "GADD45α" "GAR" "GAS5-plasmid" "GAS7A" "GAS7B" "GAS7C" "GAS9" "GBC" "GC-MS" "GC-boxes" "GCD-0941" "GCK733" "GCa" "GEC" "GECs" "GEF-GTPase" "GEF-mediated" "GFP-Atg8p" "GFP-CL1" "GFP-E-cadherin-expressing" "GFP-FLAG-USP4-FL" "GFP-cODC" "GFP-immunoprecipitates" "GFP-immunoprecipitation" "GFP-immunoprecipitations" "GFP-lentiviral" "GFP-only" "GFPHTT72Q" "GFP‐PH" "GG" "GG+GA" "GGGTTA-3" "GH-treatment" "GI50s" "GIST-like" "GIST_11" "GIST_124" "GIST_131" "GIST_150" "GIST_174" "GIST_178" "GIST_188" "GK733-induced" "GLE2p-binding" "GMB" "GMR-Gal4" "GNF2" "GNF4877" "GNF5" "GNF6324" "GNF7156" "GP900" "GPIZ-shDAB2IP" "GR-CDH1" "GR-null" "GR-siIGF1R" "GRCh37" "GRO-seq" "GSE12803" "GSE14520" "GSE2034" "GSE20712" "GSE22058" "GSE24-2" "GSE24.2" "GSE24.2-NLS1.3" "GSE24.2-NLS2.3" "GSE24759" "GSE26375" "GSE26511" "GSE30285" "GSE34184" "GSE37754" "GSE4-NLS1" "GSE4-NLS1-DA" "GSE41313" "GSE5846" "GSE61967" "GSE6919" "GSE71471" "GSK" "GSK3-by" "GSK3β-PS9" "GSK3β-S9" "GSK‐3–β" "GST-ARE-Luciferase" "GST-LC" "GST-R5BD" "GST-SC" "GST-chimeras" "GST-pull" "GT" "GTEx" "GVGD" "GWAS030" "Gain-of-function" "Gal" "Gal-3" "Gal-3C" "GalNAc" "Garicinol" "Gasther-1" "GeMDBJ" "Geiss-Friedlander" "Gel-Pro" "Geltrex" "GeneChip" "Genome-wide" "Genome–phenome" "Genotype-Tissue" "Genotype-phenotype" "Geoffroy" "German" "Germany" "Germline" "Ghahramani" "Giemsa" "Gleason" "Gli" "Gli-1" "Gli1" "Gln54Lysfs" "Gln66-Lys77" "Glu-rich" "Google" "Goosecoid" "Gori" "GppCp" "GppNp" "Gpxs" "Gr-1" "Granta" "Granta519" "Grb2" "Grb2-p85-TGF-RII" "Growth-arrest-specific" "Gu" "Guan" "Gy" "Gy-irradiated" "Gómez-Lechón" "GαS" "Gαs" "Gβ" "H&E" "H-L-H" "H-Ras" "H-RasY64A" "H-RasY64A·GTPγS" "H-RasY64A·GppNp" "H-Ras·GDP" "H-Ras·GTP" "H-Ras·GTPγS" "H-Score" "H-Scores" "H-bond" "H-bonds" "H-score" "H-scores" "H1" "H1-H1" "H1650ER" "H1975" "H1993" "H2-S3" "H2AK15" "H2DIDS" "H3" "H3-H4" "H3122CR1" "H3K18" "H3K18ac" "H3K27" "H3K36" "H3K56" "H3K56Ac" "H3K9" "H3K9Myr" "H3R2" "H3R8" "H4" "H4K16" "H4K16Ac" "H4K20" "H4R3" "H6" "H9-hESC-derived" "HA-1077" "HA-Huh7.5.1" "HA-NLS-PKM2" "HA-mock" "HA-tag" "HAHBD" "HAT + " "HA–Strep-Tactin" "HB-2" "HBPol" "HBe-Ag" "HBx-HCCR" "HBx-HCCR-E-cadherin" "HCC1195" "HCC1833" "HCE8693" "HCT116-DR5KO" "HCT116-KD2" "HCT116-KD3" "HCmel10" "HCmel3" "HCmel3-R" "HCmel3-R-2514" "HCmel3-R-2515" "HCmel3-R-3037" "HCmel3-Rs" "HD" "HD-DH-PH-Cat" "HDAC-4" "HDAC8–substrate" "HEL-R" "HEMa-LP" "HEMn" "HEMn-MP" "HEN-1" "HER" "HER2+-E-CSC" "HER2-equivocal" "HER2-negative" "HER2-normal" "HER2-positivity" "HER2-targeting" "HER2e" "HERPUD2" "HESCs" "HFD-induced" "HFF" "HFKs" "HGF-induced" "HIAP" "HIF1a-AS1" "HIF1α-AS1" "HK" "HK‐2" "HL-7702" "HLA-B8-DR3" "HLECs" "HME" "HMG-CoA-reductase" "HMLE" "HMN-176" "HMN-214" "HMR-1275" "HN" "HOMA-IR" "HOSE" "HOXB13-dependency" "HPMVECs" "HPRC" "HPRT" "HPV-1" "HPV-5" "HPV-8" "HPV16-E6" "HR-PFS" "HR2" "HR=0.002" "HR=0.42" "HRCT" "HRE-1" "HRE-2" "HRMECs" "HRMGs" "HSC–70" "HSP-70" "HSP1AL" "HSP2cTg" "HSP70-1" "HSP70-2" "HSP90-Src-mediated" "HSP90α" "HSPA1-Lys561" "HSPB2NTg" "HSPB2cKO" "HSPB2cTg" "HSPB2wt" "HSQC" "HT29-KD6" "HT29-lucD6" "HT29-lucD6-COX2" "HT29-lucD6-EV" "HT3-E6" "HTB-177" "HULC-107-mut" "HaloPlex" "Han" "Hans" "Hardy-Weinberg" "Hardy–Weinberg" "HeCOG" "HeH-C57BL" "Hedgehog-GLI1" "Heilongjiang" "Hela" "HemECs" "HemSC" "HemSCs" "Henan" "Henríquez-Hernández" "Hep3B-ERα" "Hep3B-miR-214" "HepG2-shERα" "HepJ5" "Her2" "Her2-enriched" "Her2-negative" "Her2-positive" "Her2Neu" "Hergovich" "Heteroduplex" "Hi-Q" "Hickey" "High-level" "Hippo" "Hippo-ERBB" "Hippo-YAP" "Hippo-independent" "His-PDK1" "His-USP7" "His-p300" "His2240Leufs*4" "His2261Leufs" "Hispanic" "Histone2AX" "Histopathology" "Hodgkin" "Hoechst" "Holm–Sidak's" "Honda" "Hong" "Honoraria" "HphI" "Hsa-miR-628-3p" "Hsa-miR29a" "Hsa-miRNA-139-5p" "Hsp90α" "HspB10" "HuH" "HuH-7R" "Huang" "Human-1" "Hwang" "HyperCVAD" "Hz" "Hε" "I-II" "I-III" "I-IV" "I1018F" "I157T" "I2" "I83-E95" "IAPH" "IASLC" "IC-50" "IC50" "IC50s" "IC50s=10-15" "ICI-118,551" "IDH-1" "IDs" "IEF" "IFU" "IG20" "IGF1-treatment" "IGF1R-beta" "IGH" "IHC-negative" "IHC3+" "IHC 3+" "II-1" "II-2" "II-3" "II-4" "II-5" "II-7" "II-III" "II-IV" "IIA" "III-1" "III-2" "III-7" "III-IV" "IIIA" "IIIB" "IIIB-IV" "IIIC" "IIIa" "IIb" "IIb-IIIa" "II–III" "II–IV" "IKBα" "IL-1F6" "IL-1F8" "IL-1F9" "IL-1RAcP" "IL-1βwere" "IL-22RA1" "IL-36" "IL-36-mediated" "IL-36α" "IL-36β" "IL-36γ" "IL-36γsecretion" "IL-6-STAT3-miR-24" "IL-6Rα" "IL-6–or" "IL20R" "IL20R2" "IL213" "IL218" "IL22R1" "IL2RG-SGM3" "ILP2" "ILs" "IM-MS" "INA" "INTRA-TUMOR" "IQ" "IRC-083864" "IRE-protein" "IRES-like" "IRESs" "IRP1-IRE" "IRS-1–PI3-K–PDK1" "ISCU1" "ISH-negative" "ISH-positive" "ISVs" "ITAF" "ITAF-like" "ITAFs" "ITC" "ITG4A" "ITGA10-11" "ITGA2-4" "ITGAVB3" "IVIS-SPECTRUM" "IVS" "IVS14" "IVS14 " "IVS2+1G" "IWR-1" "IWR-1significantly" "Identifier" "Ig" "IgA" "IgG-like" "IgG1" "Iliopoulos" "Illumina" "Imaris" "Imidazole" "Immunochemistry" "Immunohistochemistry" "Importin" "In-cell" "Inc" "Index" "Infinium" "Int" "Inter-group" "Inter-individual" "Inter-observer" "Inter-study" "Invitrogen" "Ion-Mobility" "Iκ-Bα" "IκB-bound" "IκBKγ" "I–III" "I–IV" "J-aggregates" "JAK-STAT3-VEGF" "JAK1-3" "JAK2-V617F" "JAK2-V617F-Y931C" "JAK2-V617F-addicted" "JAK2-V617F-dependent" "JAK2-V617F-driven" "JAK2-V617F-induced" "JAK2-V617F-mediated" "JAK2-V617F-positive" "JAK2-V617F-transformed" "JAM-L" "JARID1" "JEC" "JEKO" "JEKO-1-R" "JEKO-1R" "JEKO1" "JEKO1-R" "JFH1-infected" "JGCA" "JH1" "JJC" "JKY" "JKY-2-169" "JQ1" "JVM-13" "Jagged-1" "Japanese" "Jaspla" "Jeb" "Jeb-like" "Jeb " "Jed4" "Jeff" "Jeko1" "Jemal" "Jewish" "Jf" "Jiang" "Joerger" "Junbo" "Jurkat-HA-FOXP3" "Jurkat-shTCERG1" "Justin" "K-RasG12V" "K-RasG12V·GTPγS" "K-Ras·GTPγS" "K-fibre" "K-fibre-stabilising" "K-fibres" "K-rat" "K11" "K16" "K18" "K202–S276" "K3326X" "K34c" "K381A" "K45" "K45R" "K54" "K54R" "K56" "K63" "K63-only" "K632S5" "K9" "KAT5-dependence" "KAT5i" "KD2" "KD3" "KD6" "KDM4" "KDM5" "KEGG" "KG" "KMTs" "KN-92" "KNS-62" "KO-AA" "KO-DD" "KPC" "KPS" "KR" "KRAS-12" "KRAS-G12G12C" "KRAS-G13D" "KRAS-LCS" "KRAS-LCS6" "KRAS-driven" "KRAS-non-cancer" "KT-MT" "KT–MT" "Kaiser" "Kanai" "Kandioler" "Kang" "Kaplan" "Kaplan-Meier" "Kaplan–Meier" "Kaposi" "Kappel" "Kd" "Keap1" "Keap1-Cul3E3" "Keap1-sulfenic" "Keap1–Cys" "Kelch-interactors" "Kelch-like" "Kelch‐like" "KeratinoSens" "Keratinosens" "Ki-67" "Ki-67-positive" "Ki-67–positive" "Ki67" "Ki8751" "Killer" "Kim" "Kip" "Kirsten" "Kit-8" "Knock-down" "Knocking-down" "Korean" "Korkaya" "Koulich" "Kruppel-like" "Kruskal-Wallis" "Kruskal–Wallis" "Krüppel-like" "Ku" "Ku80-defective" "Kudlow" "K‐Ras" "K‐Ras‐mediated" "L-Ala-Gln" "L-Gln" "L-Myc" "L-OHP" "L-OPA1" "L-alanyl-glutamine" "L-isoapartyl" "L-isoaspartate" "L-type" "L1" "L2" "L4" "L52R" "L7" "L858R" "L983F" "LACE" "LACE-Bio" "LADCs" "LAMTOR-2" "LC-3II" "LC3-I" "LC3B-I" "LC3B-II" "LC3I" "LC3II" "LCLs" "LCM-RPPA" "LCMT1" "LDHb" "LDL-cholesterol" "LEF" "LEOPARD" "LETM1" "LETMD1" "LEV" "LFS" "LHSAR" "LHSAR+FOXA1+HOXB13" "LIM" "LINC00273" "LINE‐1" "LISA" "LKB1-depicient" "LLL12" "LMP1transcription" "LMP2A" "LN299" "LNCaP" "LNCaP-7B7" "LO" "LOC100506688" "LOH" "LOVD" "LOX-5" "LPC-Mig" "LPHN2" "LPS" "LR-hTERT" "LRRFS" "LS-102" "LTR" "LTT" "LUMIER" "LUMinescence-based" "LV-cofilin-shRNA" "LV-control-siRNA" "LV-shRNA" "LXRα" "LY293111" "LY3023414" "LY6161" "Lallemand-Breitenbach" "Lambert" "Laminin" "Lamp1-mCherry" "Lane1-2" "Lange" "Langerhans" "Lap" "Lap#12" "Lap#6" "Lap#6-CM" "Large-scale" "Latin" "Latin-America" "Lauren" "Le" "Lef1" "Leica" "Leu132-Cys133-Arg134" "Leu→Leu" "Lhermitte-Duclos" "Li" "Li-Fraumeni" "Li-Fraumeni-like" "Lifepool" "Lineweaver–Burk" "Liu" "Liu-Chittenden" "LncRNA-GAS5" "LoD" "Loewe" "Log-rank" "Lombardo" "Long-Evans" "Lou" "Lov" "Low-complexity" "Low-dose" "Low-frequency" "Low-level" "LoxP" "LoxP-sites" "LtSz-scid" "Lu" "LuCaP35" "Luc" "Luc-GFP" "Luc-MET-3" "Luc-P1" "Luc-P1-MT" "Luc-P1-WT" "Luminal-A" "Luminal-B" "Luminex" "Lv-cofilin1-shRNA" "Lv-control-shRNA" "Lymph-node" "Lynparza" "Lys-11" "Lys-27" "Lys-29" "Lys-33" "Lys-48" "Lys-561" "Lys-63" "Lys120" "Lys3326Ter" "Lys376Glu" "Lys54Argfs" "Lys561-containing" "M+7" "M-CSC" "M-CSC-like" "M-CSCs" "M-H" "M-MSP" "M-states" "M0-2" "M15" "M15A" "M1L" "M2L" "M6" "MAD-MB-231" "MADE1" "MAGE-B18-LNX1" "MALDI-TOF" "MALDI-TOF-MS" "MAP1S-deficiency-triggered" "MAP1Smediated" "MAP1Sregulated" "MAP1Sspecific" "MAP1b-LC" "MARCKSknockdown" "MARCKS‐GFP" "MARK" "MAVER1" "MBA-MB-231" "MCAO" "MCC-32" "MCE-7" "MCF10a-normal" "MCF7shp53" "MCF7vector" "MCF‐7" "MCP-TERT-labeling" "MCS4" "MDA-MB-23" "MDA-MB-231cells" "MDA-MB231-pLKO1" "MDA-MB231-shBLT1" "MDA-MBN-231cells" "MDA-MD-453" "MDA_MB231" "MDA‐MB‐231" "MDA‐MB‐231cells" "MDM2-C" "MDV-R" "ME180-MXIV" "ME180-shYAP" "MEAF6-SEPSEC" "MED8A" "MEK-ERK" "MESACUP" "MESENCHYMAL" "MET-related" "MET4" "MFS" "MHH" "MHH-ES-1" "MHz" "MI192" "MI192 " "MICoA" "MIGR" "MIM1" "MIP-1-α" "MIP-1â" "MIP-1αand" "MIP-DILI" "MJ-56" "ML141" "ML323" "MLH6" "MLL-AF9-expressing" "MM-15" "MM-74" "MM15" "MM27" "MM54a" "MM65" "MM85" "MMTV" "MMTV-ErbB2" "MMTV-PyMT" "MNA" "MOIs" "MPM-p3" "MPN-like" "MPS" "MPs" "MR" "MREs" "MS" "MS-PCR" "MSC4" "MSC7" "MSI-H" "MST2-promoted" "MTF16" "MTMR8" "MTases" "MU" "MUT1" "MUT2" "MUT3" "MV4-11cells" "MVID-like" "MVP1" "MXD" "MYCBNP2" "MYO3B" "MZ" "MZ7" "MZB1" "Ma-Mel-102" "Ma-Mel-15" "Ma-Mel-27" "Ma-Mel-48" "Ma-Mel-54a" "Ma-Mel-85" "Mad-homology-1" "Mad-homology-2" "Madin-Darby" "Magainin1" "Mal" "Malaysia" "MammaPrint" "Mannheim" "Mantel-Cox" "Marburg" "Mark53" "Marshall" "Masson" "Material" "Matic" "Matsushima-Nishiu" "Maxi" "Maxi-EBV" "May-Grünwald" "May-Grünwald-Giemsa" "Mayo" "McLaughlin" "Mediator" "Medici" "Meier" "Mel-RM" "Meleda" "Melnikow" "Merck" "Merkel" "Meso-Scale-Discovery" "Meta-regression" "Methods" "Methyl-Met" "Methyl-Profiler" "Mexican" "Mexicans" "Mexico" "Mi2" "MiR-101" "MiR-103" "MiR-141-3p" "MiR-18a" "MiR-208b" "MiR-22" "MiR-22-deficient" "MiR-33a" "MiR-484" "MiR-494" "MiaPaca‐2" "Michael" "Michaelis-Menten" "Micro-CT" "MicroRNA-7" "Microfilaments" "Mild-inflammatory" "Millipore" "Mir-548" "Mir22" "Mir22hg" "Mira-900" "MitoTracker" "Mn" "MoDCs" "Moderate" "Monocyte-derived" "Moog-Lutz" "Mooney" "Morgillo" "Mourtada-Maarabouni" "Mukhopadhyay" "Multidomain" "Munc18-2–dependent" "Munc18-like" "Muranen" "Mut" "Mut865" "MutIL6R-2" "MutSTAT3" "Mutationtaster2" "Mutect" "Mv1Lu-pcDNA3cells" "Myc-Max-DNA" "Myc-RhoA-Q63L" "Myc-Skp2" "Myo5B-GTD" "Myo5B-LC" "MyoII-mediated" "Myosin" "Myr-Akt" "Mø" "MβCD" "M–O" "N-ARBS" "N-HSQC" "N-LMP1" "N-RAS-G12V" "N-SH2" "N-acetyl" "N-acetylgalactosamine-specific" "N-acetylglucosaminyl-transferases" "N-domain" "N-glycosidase" "N-glycosylated" "N-labeled" "N-methyl-nitrosourea-treated" "N-methylate" "N-methylation" "N0" "N1" "N1+N2" "N1-O" "N1-guanine-N3-cytosine" "N1a" "N1b" "N2" "N375" "N400" "N9" "N981I" "NA" "NAAIRS" "NADPH" "NALM-19" "NAMDR2B" "NB-4" "NC-miR" "NCCIT-R" "NCCTG" "NCI" "NCI-60" "NCI-H1819" "NCI-H1915" "NCT" "NCT00258245" "NCT00525200" "NCT00755885" "NCT01244191" "NCT01431209" "NCT01456325" "NCT01514266" "NCT01740323" "NCT01795768" "NCT01858168" "NCT01889238" "NCT01905592" "NCT01945775" "NCT01967095" "NCT01974765" "NCT01990209" "NCT02000375" "NCT02000622" "NCT02044120" "NCT02091960" "NCT02116777" "NCT02140723" "NCT02144051" "NCT02157792" "NCT02163694" "NCT02215096" "NCT02223923" "NCT02264678" "NCT02296203" "NCT02316496" "NCT02348281" "NCT02370706" "NCT02407054" "NCU" "NCX4040" "NCsi" "NEXT-2" "NF-κB-mediated" "NF-κB1" "NF-κBα" "NF1-associated" "NGR-A2" "NGS-wild-type" "NH" "NHDFs" "NH " "NI" "NK-kB" "NK-κB" "NKIRAS1" "NKT-like" "NKTCL" "NLS2" "NLST" "NMS-P937" "NMSCs" "NOD-SCID" "NOD-like" "NOD–SCID" "NON" "NOX-ROS-EGFR-PI3K-ERK1" "NOX-derived" "NQO" "NR" "NRF2-triggerd" "NRG1-null" "NRG1–ErbB2–ErbB3" "NS-ML" "NS-like" "NSAID" "NSC-95397" "NT-proBNP" "NTERA-2R" "NU1025" "NVP-AUY922-AG" "Nagel" "Najafi-Shoushtari" "Nakagawa" "Nano" "Nano-LC" "Nedd4" "Neh" "Neh3–5" "Neh4" "Neh5" "Neh6" "Neh7" "Nelson" "Neo" "Nestin" "Netherlands" "Neural-Wiskott" "Next-Generation-Sequencing" "Next-generation" "Nfe2I2" "Nhe4–5" "Ninety-three" "Ninety‐eight" "Nkx2" "Noonan" "Normal-AR" "North-Central" "Norton" "Norton-Simon" "Notch" "Notch-mediated" "Nox-driven" "Nrf" "Nrf2-100" "Nrf2-100-FLuc2" "Nrf2-100-Fluc" "Nrf2-100-Fluc2" "Nrf2-100-Luc2" "Nrf2-100-Luciferase" "Nrf2-ARE" "Nrf2-FLuc2" "Nrf2-activator" "Nrf2-activators" "Nrf2-oxidative" "Nrf2-regulatory" "Nrf2-response" "Nrf2‐mediated" "Nrf2‐regulated" "Nrf2–ARE" "Nrf‐2" "Nu" "NuRD" "Numb" "Numbl" "Nutlinpre-treatment" "Nutullin-3" "Nε" "O-linked" "O-methyl" "O-methylate" "O-methylating" "O-methylation" "O-purification" "O-purified" "O6-BG" "O6-MeG" "O6-alkylguanine" "O6-methlyguanine-DNA-methyltransferase" "O6-methylguanine" "O6-methylguanine-DNA" "O6-position" "O6BG" "OAP" "OB" "OB-fold" "OC" "OCI-LY18" "OCUM‐2M" "OD490" "OGDDs" "OHTAM" "OKD48-Luc" "OLAR5" "OMIM" "OMIM2483000" "ON018910" "ON01910" "ONNO" "ONO12380" "ONYX-015" "OP449" "OPA1-ΔS1" "OPB-31121" "OPB-51602" "OPCs" "OR=0.73" "OR=0.79" "OR=0.84" "OR=0.93" "OR=0.94" "OR=0.97–1.09" "OR=1.05" "OR=1.06" "OR=1.08" "OR=1.18" "OR=1.20" "OR=1.21" "OR=1.26" "OR=1.45" "OR=2.02" "OR = 0.93" "OR = 0.94" "OSBPL3" "OSEC2" "OX" "OX-refractory" "Ohba" "Olfr1508" "Olfr68" "Oligonucleotide" "OmniExpressExome-8v1" "On-TARGETplus" "Onco" "Oncodrivers" "Oncology" "Oncomine" "One-hundred" "One-third" "Ortiz-Zapater" "OspB-mTORC1" "OspC3" "OspE" "OspF" "Overholtzer" "Ozcan" "Oε2" "P1" "P1-3" "P24" "P24L" "P26" "P26–114,113" "P28–12,591" "P2X" "P2Y" "P58" "P58A" "P6.1" "P7" "P72" "P72R" "P91" "P91L" "P91L–Y306F" "P943_946" "P9–13" "P=0.002" "P=0.003" "P=0.01" "PAM50" "PAM50-based" "PANC-1" "PANERB" "PANTHER" "PARP-DNA" "PARP1-DNA" "PARP5a" "PARP9" "PARPi" "PARylation-dependent" "PB-Cre" "PBD-phosphopeptide" "PBIP1-p-T78" "PBX-family" "PBXIP1" "PCDHGA11" "PCR-Sanger" "PCs" "PCs " "PD-20corr" "PD20" "PD20KR" "PD331" "PD980589" "PDBj" "PDGFRα-mutant" "PDGF‐induced" "PDI-like" "PDK-1binding" "PE-B-1" "PEC" "PECs" "PET-CT" "PF-004777736" "PF-04691502" "PF-0477736" "PFGE" "PFT-α" "PFT-μ" "PG" "PGE2-mediated" "PGL" "PHA-680626" "PHA-II" "PHA666762" "PHT-427" "PI3K-AKT1" "PI3K-CA" "PI3K-like" "PI3KC2G" "PI3KC3" "PI3KCA" "PI45P2" "PIK3CA-E545G" "PIK3CA-E545K" "PIK3CA1-mutant" "PIK3CAhel" "PIK3CAkin" "PIK3CAmut" "PIK3CAwt" "PIK3KCA" "PIKKs" "PIM1L" "PIM1S" "PIMs" "PITA" "PK45-p" "PK59" "PKCβII" "PKH67" "PKM1" "PKM2-NLS" "PKM2-NLS-mutant" "PLC‐δ" "PLHS-Pmab" "PLHSpT" "PLHSpT-Pmab" "PLK-1to" "PLK-1with" "PLK-2" "PLK-4" "PLK-5" "PLK1-R136G" "PLK1-R136G&T210D" "PMK-1" "PMN-like" "POH1-E2F1" "POH1–E2F1" "POOREST" "PP2A-mediated" "PP2A–c-Myc–dependent" "PP2A–mediated" "PPAR-α" "PPAR-β" "PPAR-δ" "PPAR-δ-dependent" "PPAR-δ-specific" "PR-619" "PR-negative" "PRKKA1" "PRMT5-MEP50-containing" "PRMT5-Methylosome" "PRMTs" "PROGNOSTIC-PREDICTIVE" "PROMO" "PROVEAN" "PTCLnos" "PTD-A2" "PTD-A2–injected" "PTD-A2–treated" "PTTG-shRNA1" "PTTG-shRNA2" "PTs" "PV" "PXBIP1" "PaC" "PaTu899S" "PacMetUT1" "Pair-wise" "Pam2CGDPKHPKSF" "Pan-CDK" "Pan-Cancer" "Panc‐1" "Par3-Par6-aPKC" "Parkinson" "Partition-defective" "Pax7" "Pax7-Cre" "Pax7CT2" "Pax7nGFP" "Pc " "Peak-like" "Pearson" "Periodic-Acid-Schiff" "Petitjean" "Pfizer" "Pgd" "Pgp" "Pgp-1" "Ph-treatment" "Philadelphia" "Phosphoinositide-3" "Phospho‐MARCKS" "Physcion-6PGD" "Physcion-treated" "Pi-Pi" "Pillai" "Pin1-CPEB1" "Pit-Oct-Unc" "Plumbaginaceae" "Pluripotency-associated" "Pmab" "Pogue-Geile" "Poisson" "Pol" "Pol1" "PolII" "Polo-Like" "Polo-box" "Poloboxtide" "Poloxipan" "Poly-L-Ornithine" "PolyPhen" "PolyPhen-2" "PolyPhen2" "Polymerase1" "Polyphen2" "Post-UVB" "Post-operative" "Post-transcriptional" "Post-translational" "Postmenopausal-levels" "Ppant" "Prestwick" "Pro+Arg" "Pro-inflammatory" "Pro1180fs" "ProA-FLAG-tag" "Prohibitins" "Proline-Rich" "Promonin-1" "Protein" "Protein-RNA" "Pseudo-hypoxic" "Pthα" "Puerto" "Pull-down" "Puquitinib" "PvuII" "Pérez-Vallés" "Q-FISH" "Q-MSP" "Q382A" "Q546L" "Q61R" "QGY-7703-miR-214" "QW" "R-5-P" "R-CHOP" "R-CHOP-treated" "R-Hyper" "R-MA" "R-based" "R-enantiomer" "R-enantiomer-selective" "R-enantiomers" "R-etodolac" "R-forms" "R-ketorolac" "R-naproxen" "R0" "R1" "R156A" "R156A-mutant" "R1905" "R1–R4" "R2" "R23X" "R251X" "R299Q" "R3" "R385A" "R4" "R5" "R579X" "R5BD" "R653-Q855" "R7T1" "RANK-ligand" "RASSF1-1α" "RASSF1C" "RASSF7–10" "RASSF8" "RASSF8-RNAi" "RASSF8-RNAi–transduced" "RASSSF1A" "RAS‐GAP" "RB05" "RB45" "RESISTANCE" "RFP‐PH" "RFP‐tagged" "RFTN1" "RGLs" "RH-SENP3" "RHT1" "RHT2" "RHZ" "RIGER" "RII" "RIP-DTA" "RMH" "RMS-1" "RNA" "RNA-130a" "RNA-PolII" "RNA-SIRT1" "RNA-like" "RNA-protein" "RNA22" "RNAP" "RNAhybrid" "RNAseq" "RNA–RNA" "RNU48" "RNV" "RNaseP" "RO3280" "ROCK-actin" "ROCK-to-MLCK" "ROCK1-co-transfected" "ROCK1-to-MLCK" "ROCK2-to-MLCK" "ROS-generation-inducing" "RPI-Pred" "RPI-prediction" "RPISeq" "RPISeq-RF" "RPISeq-SMV" "RPISeq-SVM" "RPMI" "RPMI-1640" "RPRR-X" "RPRRX-S" "RRL-F" "RRL-O" "RRx" "RRx-001" "RS4-11" "RTA-408" "RTK" "RTK-ligand" "RTOG" "RT‐PCR" "RUNX1-RUNX1T1" "RUNX1T1" "RUV" "RVVFLEPLKD" "Rab5-CA" "Rab5-DN" "Rab5-GTP" "Rab5S34N" "RabGGTA" "Rac1" "Rac1‐GTP" "Rad3" "Rad3-related" "Radix" "Raf-MEK-ERK-mediated" "Raf1-driven" "Rahman" "Raimondi" "Rap-plus-Spa" "Ras-Sos" "Ras-homologous" "Ras-like" "Ras2p" "RasY64A" "RasY64A·GTPγS" "Ras·GDP" "Ras·GTP" "Ras·GTPγS" "Rat‐specific" "Rb" "Rb-null" "Rbx1-Cullin1-Skp1-F-box" "Rbx1-mediated" "Re-analysis" "Re-evaluation" "Re-expression" "Re-growth" "Real-Time-PCR" "Reduction-oxidation" "Renilla" "Ret" "Rett" "Revacept" "Reverse-phase" "Rhex-1" "Rho-family" "RhoA-GTP" "Rhod" "Rhod2" "Ribeiro" "Ribo-seq" "Rican" "Rictor-KO" "Riesenberg" "Rluc" "Rossmann" "Rossmann-fold" "Roux" "Ru-5-P" "Ru-5-P-dependent" "RxRxxS" "Rxr" "Rxrα" "RxxS" "S-1" "S-H" "S-adenosyl" "S-checkpoint" "S-enantiomer" "S-enantiomers" "S-forms" "S-ibuprofen" "S-ketorolac" "S-methionine" "S-naproxen" "S-phase-expressed1" "S-transferases" "S1" "S1-treated" "S127" "S143A" "S143D" "S143E" "S16" "S16-STMN1" "S1981" "S1981-ATM" "S1C" "S1D" "S1E" "S1G" "S1H" "S2215F" "S245" "S25" "S291fs" "S2B" "S2C" "S2D" "S2E" "S2a–c" "S3" "S3-6PGD" "S3-A" "S3-B" "S3-resistance" "S307D" "S317" "S345" "S38" "S38-phospho-STMN1" "S386A" "S3B" "S3C" "S3D" "S3E" "S3F" "S3G" "S3H" "S3I" "S4" "S4-B" "S432A" "S432D" "S432E" "S4A" "S4B" "S4C" "S4D" "S4G" "S4S" "S4S8p" "S5C" "S5D" "S5E" "S5G" "S5H" "S6" "S63" "S6A" "S6B" "S6C" "S6G" "S6RP" "S7" "S7A" "S7C" "S8" "S8-A" "S8-B" "S8-C" "S8b" "S9" "S9-S10" "S9A" "S9B" "S9d" "S9–S10" "SA-β-Gal-positive" "SAβGal" "SBE13" "SBI-0061739" "SBI-0069272" "SBI-061739" "SBI-0640599" "SBI-0640601" "SCCOHT-1" "SCG10-like" "SCS" "SCV000255937" "SCV000255938" "SCV000255939" "SCV000255940" "SCV000255941" "SCaBER" "SCs" "SD4" "SDH-intact" "SDHA-D" "SDHX" "SDK2" "SDX-301" "SDX-308" "SENP" "SENPs" "SEPTIN11" "SERDs" "SET-FUCRW" "SET-PEB-1" "SET-PP2Ac" "SET-RW" "SET-immunoprecipitant" "SET2-R" "SFRS15" "SGKs" "SH-groups" "SH10" "SH2-pseudokinase" "SHH-medulloblastoma" "SHR-C" "SHR-H" "SHR-L" "SILEC10" "SIRT" "SISH" "SK-Mel-37" "SK-N-BE2" "SK-N-DZ" "SK6" "SKA2-luc" "SKH-I" "SLC16A14" "SLFN" "SLFN11" "SLFNs" "SLURP-1" "SLURP1" "SMiNS-like" "SMiNSc-like" "SN12PM6" "SNAP-tag" "SNF2-family" "SNORD12" "SNORD12b" "SNORD12c" "SNP-array" "SNP-arrays" "SNP6.0" "SNPase-ARMS" "SNPs" "SNU-2535" "SNV" "SNVs" "SNX-7018" "SNX-7081" "SNX-7081+2-FaraA" "SNX-7081-induced" "SNX-7081-mediated" "SNX-7081-treated" "SOX" "SOX2-MYC-directly" "SPIN4" "SPS1-related" "SPSS" "SR" "SRC-NFKB" "SRCC" "SRCCs" "SRD" "SRD-13A" "SRE" "SRE2" "SREBP-mediated" "SRM-MS" "SRM-MS-negative" "SRM-MS-positive" "SSPNN" "STA-7346" "STA7346" "STAG–RAD21" "STAT" "STAT3-mediated" "STAT3-null" "STAT3WT" "STAU" "STIMA-1" "STMN-like" "STMN1-S38-phosphorylation" "STS-2" "STUbL" "STUbLs" "SUN-387" "SUPB-15" "SUV39" "SV40-driven" "SVM" "SW-1353" "SW-1990" "SW-480" "SW-620" "SW-837" "SW156" "SW480-D2" "SW480-D2-scram" "SW480-D2-scramble" "SW480-D2-si-IκB" "SW480-D2-si-IκB-α" "SW480-D4" "SW480-con" "SW480-con-scramble" "SW480ADH" "SWISS-MODEL" "SWissDock" "SXL4" "SYF-c-Src-TrkB" "SYF-cSrc-TrkB" "SZ" "SZ-4" "Sahiwals" "Saliva-Based" "Salvesen" "Sanchez-Tillo" "Sanger" "Santini" "Sarcomatoid" "Sato" "Saudi" "Sc-1" "Schiff" "Schimmel" "Schlafen" "Scorpion" "Sec1" "Self-renewal" "Semi-quantification" "Sen" "Ser-4" "Ser-473" "Ser-8" "Ser10" "Ser1139ArgfsX16" "Ser19-CHK2" "Ser1981" "Ser21" "Ser235" "Ser240" "Ser307" "Ser33" "Ser33,37" "Ser4" "Ser432-specific" "Ser5" "Ser67-Arg69" "Ser8-phosphorylated" "Ser9" "Sevenless" "Seventy-seven" "Seventy-two" "Seventy‐nine" "Sh" "Sh-TAZ-1" "ShMOLLI" "Shanxi" "Shen" "Short-term" "SiIGF1R" "SiNS-like" "SiNSc-like" "Sica" "Sichuan" "SinceUHRF1over‐expression" "Single-molecule" "Single-nucleotide" "Sirius" "Sirtuin-7" "Site-II" "Sixty-eight" "Sixty-nine" "Sixty-six" "Sixty-three" "Sixty-two" "Skp1" "Skp1-Cul1-F-box" "Skp1-Cullin1-F" "Skp1-Cullin1-Rbx1-F" "Skp1–6-OAP" "Skp2‐mediated" "Skrzypczak" "Slc25a3" "Sloan" "Slp4a–Stx3" "Slpa4" "Smad-E2F" "Smad3" "Smad3-phosphoisoforms" "Small-Cell" "Small-interfering" "Snail" "Snap23a" "Snijders" "Society" "Sodium-chloride" "Solid-Phase" "Sp1" "Sp1-1" "Sp1-3" "Spanish" "Spearman" "Spengler" "Squalene" "Src" "Src-PY418" "Src-dependent" "Src-family" "Src-mediated" "Src-signaling" "Sriramachandran" "Stat" "Stat1" "Stathmin" "Stathmin-1" "Stathmin-2" "Strep" "Strep-Tactin" "Structure-based" "Sts-1" "Sts-1-CBL" "Sts-2" "Student-Newman" "Stx3_1-247" "Stx3–Munc18-2" "Sub-G1" "Sudol" "Suit‐2" "Sv" "Swiss" "Switch" "Switzerland" "SykPTK" "Syns-driven" "S‐phase" "T+8473C" "T+C" "T-AOC" "T-ARBS" "T-C-C-C" "T-C-T-C" "T-DM1" "T-LGL" "T-PLL" "T-Rex-HEK293T" "T-T-T-C" "T-allele" "T-circle" "T-circles" "T-complex" "T-helper" "T-lymphoid" "T-precursor-stage" "T0" "T1" "T1+T2" "T1-relaxation" "T145A" "T1989" "T1c" "T2-relaxation" "T202" "T210-loop" "T3" "T3+T4" "T306" "T306D" "T3–T4" "T4" "T7-Hsc70" "T7-tagged" "T790M-EGFR" "TAE-684" "TAK-960" "TAK-960-mediated" "TAK-960-treated" "TAT-A2" "TATA" "TATA-less" "TBB" "TBC1D30" "TBX-YAP" "TC+CC" "TCER-1" "TCS2" "TD19" "TEA" "TEFb" "TEN-domain-truncated" "TERT-hTR" "TERT-∆PAL" "TF556PS" "TFIIH-repair" "TGE" "TGF-R" "TGF-RI" "TGF-RII" "TGF-RIII" "TGFβRII" "TKD" "TKI-resistance" "TKM-080301" "TL4" "TM" "TM251" "TMA-1005" "TMEM51" "TN" "TNBCs" "TNF-1α" "TNF-β" "TNSK2" "TOP" "TOP-like" "TOP2A-expressor" "TOPflash" "TORopathies" "TPA-induced" "TPF" "TPF-regents" "TRAF2-mediated" "TRAP-C1" "TRF-1" "TROSY" "TRUB" "TS-1" "TSG-motif" "TSKN2" "TSNs" "TSVC" "TT+TC" "TTAGGG-3" "TTAGGGs" "TULA-2" "TURP" "TVC" "TWIST1" "TX" "TXNR1" "TXNRD3" "Tactin" "Taihang" "Taiwanese" "Taken" "Talalay" "Tango6" "Tanimoto" "Tankyrase-2" "TaqMan" "TaqMeth" "TargetScan" "Tatham" "Tattoli" "Tc22" "Tcf" "Tcf-regulated" "Telomerase-mediated" "Temozolomide" "Temporal-spatial" "Tet-Off" "Tet-On" "Tet-off" "Tetra-primer-ARMS" "Texas" "Tg" "Th17" "Th2" "Th2-cyotkine" "Th2-effector" "Th22" "ThPOK" "Theileria" "Thirty-eight" "Thirty-five" "Thirty-four" "Thirty-three" "Thr-37" "Thr-46" "Thr-kinase" "Thr14" "Thr202" "Thr21-RPA32" "Thr306" "Thr308" "Thr4" "Thr41" "Three-dimensional" "Thy1" "Thy1.1" "Thy1.1-DP" "Thy1.1-double" "Time-lapse" "Tissue-specificity" "Toll-like" "Topo" "Topo-1" "Toremifene" "Tox" "Tra-1-60" "Tra-1-81" "Trans-Lentiviral" "Transwell" "Treg-like" "Trevigen" "Tricin" "Trigonella" "TrkB-shRNAs" "Troponin-I" "TrxR1-null" "Tumor-suppressive" "Tweenty-one" "Twenty-five" "Twenty-four" "Twenty-four-hour" "Twenty-one" "Twenty-one-week" "Twenty-seven" "Twenty-six" "Twenty-three" "Twenty‐eight" "Twist-AP1" "Two-hundred" "Ty" "Tyr1007" "Tyr15" "Tyr204" "Tyr705" "U-138MG" "U-2973" "U-MSP" "U-rich" "U0216" "U251" "U2O2" "U3" "U343" "U4" "U6" "U75302" "UBASH3B" "UBL2" "UCSC" "UCSF" "UDP-glucuronosyl" "UFB" "UFBs" "UHFR1" "UHRF1depletion" "UHRF1expression" "UHRF1over‐expression" "UHRF1suppression" "UHRF1‐mediated" "UHRF1‐positive" "UICC" "UICC-TNM" "UK" "UMSCC23" "UNC-51-like" "UPS7-dependent" "US" "USA" "USP-Family" "USP-family" "USP13si" "USP35" "USP3si" "USP7-depenedent" "UTR-G" "UTRs" "UUAUUUAUU" "UV-light" "UV5" "Ub-AMC" "Ub-FANCD2" "Ub-FANCI" "Ub-K63R" "Ub-aldehyde" "Ubal" "Ubiquitin‐like" "Ubp6" "Uke1-R" "Ulrich" "Umapathy" "Uni-and" "Urso" "Usp1-Uaf-1" "Usp12" "V-C8" "V-E5" "V1" "V2" "V2.0" "V3" "V3-YAC" "V3.0" "V341fs" "V5-tagged" "V5–ALK" "V600E–mutant" "VAPAHCS" "VDAs" "VE-821-sensitivity" "VE1" "VE821" "VEGF-1" "VEGF-R" "VIL1" "VNN2" "VP24" "VPS13B" "Val1951" "VarScan" "VarioWatch" "Vazquez-Martin" "Vb" "Vehicle-treated" "Venn" "Ventana" "Veste3" "Vgll4" "Vivanco" "Vogelstein" "Vps9" "Vs" "WAR" "WBC" "WEE" "WERI-Rb-1" "WHI" "WHI-P154" "WHIP-154" "WKY-C" "WM1552" "WMM" "WP-1066" "WST-1" "WT-C464A" "WT-UTR" "WT129" "WT21" "WT865" "WW3" "Wakulich" "Wallis" "Walts" "Warburg" "Wee1" "Wee1i" "Weibull" "Weinberg" "Wenham" "Western-blot" "Whitlock-Witte" "Whitney" "Whole-exome" "Wijnhoven" "Wilcoxon" "Wilson" "Wnt-C59-treated" "Wolff-Parkinson-White" "Wright-Giemsa" "Wu" "X-box" "X-induced" "X-irradiation" "X-linked" "X-ray" "X-rays" "X-tile" "XC-302" "XDC-1787-C" "XRCC3-5" "XRCCs" "XTT" "XbaI" "Xeno-transplantation" "Xiao" "Xinchang" "Xp11.22" "Xq" "Xq11.2-q12" "Xq12" "Xq21.2" "Xu" "Y-box" "Y-intercept" "Y-linked" "Y1203fs" "Y204" "Y2H" "Y32–Y40" "Y931C" "Y931C-expressing" "YAP1-dependent" "YB-1–and" "YES" "YT521-B" "Yan" "Yang" "Yat-sen" "Yee" "Yeh" "Yes-associated" "Yin" "York" "Yu" "Z-DEVD-FMK" "Z-stacking" "Z-stacks" "ZC3H7A" "ZD-1839" "ZFAND5" "ZFAS1-miRNA" "ZFP36L3" "ZNF592" "ZPFM1" "ZPFM2" "Zender" "Zeneca" "Zeng" "Zernicka-Goetz" "Zhang" "Zhao" "Zhejiang" "Zhou" "Zn" "Zn-finger" "ZnCl" "ZnF1" "a-FOXO1A" "a-pFOXO1A" "aOR" "aOR=1.38" "aOR=1.50" "aOR=1.73" "aPKC" "aa181–310" "aa1–200" "aa201–437" "aa36-345" "aak" "aak-1" "aak-2" "abdominal-B" "aberrancies" "above-discussed" "above-referenced" "absorbance" "acetyl-11-keto-beta-boswellic" "acetyllysine" "acetyltransferase-deacetylase" "acid-Schiff" "acid–Schiff" "acinar-predominant" "acinar-to-ductal" "acro-renal-ocular" "actin-cytoskeleton" "activatingPIK3CA" "activation-loop" "activator-like" "activators" "active-site" "acute-phase" "acyl" "acyl-carnitine" "acyl-carnitines" "adduct" "adduct-repair" "adducts" "adenine-to-cytosine" "adenine-uridine" "adeno" "adeno-squamous" "adenosyl" "adenylate-uridylate-rich" "adenylyl" "adherens" "adherens-1" "adhesiveness" "ado-trastuzumab" "adult-onset" "advanced-stage" "affinity-regulating" "agar" "age-associated" "age-dependency" "age-dependent" "age-of-initial" "age-of-onset" "aggregate-prone" "ago-NC" "agomir" "agomirs" "agonism" "agonists" "alanine-rich" "alanine‐rich" "alanyl" "aldo-keto" "algorithm" "algorithms" "alkyl" "all-time" "allele-specifically" "alleles" "allograft" "alpha-B" "alpha-helical" "alternative-spliced" "amino-acid" "amino-terminal" "amino-terminal-associated" "amino-terminal-occluded" "amino-terminus" "aminoacids" "aminopyrazines" "amplicon" "amplicons" "analytes" "and9" "andDAB2IP" "andFMNL2" "andGli1" "andKEAP1gene" "andKRAS" "andMDA" "andMDM2" "andOma1" "andPTB" "andPhb2" "andUHRF1restored" "androgen-deprivation" "androgen‐dependent" "androgen‐independent" "aneuploidy" "angeloylplenolin" "angiogenesis-associated" "angiography" "angiostatic-angiogenic" "angiotensinII" "annulata" "anoikis-like" "anoikis-sensitivity" "anorexia" "anorexia-cachexia" "anoïkis" "antagomir" "antagomir-9-3p" "anthracycline-regimens" "antibodies" "antibody-drug" "antigen-6" "antigen-driven" "antigens" "antioxidant-chemotherapy" "antiplatelet" "anti‐tumourigenic" "apical-basal" "apico-basal" "aplasia" "apocrine" "apocyanin" "apoptotic-miRNAs" "app" "appropriateness" "arachidonate" "arginine-rich" "arisen" "arrest-specific" "arsenic-mediated" "artic" "asVE-821" "aspartatecarbamoyltransferase-dihydroorotase" "aspartyl" "at-risk" "at4" "atenolol" "atg-18" "ation" "atomic-force" "aureus" "auto-ADP-ribosylation" "auto-PARylation" "auto-activation" "auto-inhibited" "auto-modification" "auto-regulatory" "autophagy-like" "autophagy-lysosome" "autosomal-dominant" "autosomal-recessive" "axial" "axon" "aza-deocycitidine" "a–c" "a–d" "a–e" "b-AP15" "baf" "bars=10" "basal-like" "basal-type" "base-call" "base-extension" "base-pair" "base-pairs" "base-specificity" "basic-helix-loop-helix-leucine" "begun" "benzo" "benzthiazole-N-oxide" "best-fit" "beta-oxidation" "beta-strand" "better-quality" "betweenESR1" "betweenUHRF1and" "bi" "bi-allelic" "bi-directional" "bi-functional" "biliverdin" "binding-protein" "bio-availability" "bio-marker" "bio-markers" "bio-synthesis" "biofluids" "bioinformatics-based" "biologically-distinct" "biomarker-studies" "biomarker-test" "biomass" "biomolecules" "biopsy-proven" "biosources" "biotin-GA" "biotin-miR-346" "biotinylated-ganetespib" "biotinylated-geldanamycin" "birth-and-death" "birthdate" "bisphosphate" "blast-like" "blockade-mediated" "blood-based" "blood-brain" "blood-brain-barrier" "blood-derived" "blood–brain" "blue-dead" "box-8" "box-containing" "box-lacking" "box1" "bp" "brainstem" "brake-point" "branched-chain" "break-apart" "break-induced" "breakage-fusion-bridge" "breakpoint" "breakpoints" "breast-ovarian" "broad-spectrum" "broader" "bucladesine" "build-up" "by-product" "by-products" "by100" "byUHRF1" "b " "c-Jun-induced" "c-MycER" "c-NHEJ" "c-Src-JAK2" "c-Src-deficient" "c-Src-mediated" "c-Src-shRNA" "c-Src-shRNAs" "c-neu" "c-nu" "cAMP-AM" "cATP" "cHER2" "cHER2-negative" "cMYC-MCF10A" "cMyc" "cNO" "cPARP" "calcium-calmodulin-dependent" "caliper" "callosum" "cancer-like" "cancer-relevant" "cancerous-noncancerous" "cancer‐related" "cancer‐specific" "candidate-gene" "cap-n-collar" "capase-3" "capase-8" "capillary-like" "capsase-3" "capsid" "capsule-like" "capture-based" "carbamoyl-phosphate" "carbonyl" "carbonyls" "carboxyl" "carboxyl-termini" "carboxyl-terminus" "carboxyl‐terminal" "carcinoma-metastatic" "cardia" "cardiac-restricted" "cardiac-specific" "cardiomyocytes" "cargo-selective" "cargos" "carnitine" "carotid" "carriers" "cartilage–bone" "case-control" "case-only" "casepase-3" "case–control" "caspas-3" "caspase-3-like" "caspase-8-null" "cassette-insertion" "castration-induced" "castration-sensitive" "catalyse" "catheter" "caveolar-mediated" "ccRCC" "ccRCCs" "ceRNAs" "celastrol-that" "cell-autonomous" "cell-context-specific" "cell-intrinsic" "cell-like" "cell-of-origin" "cell-permeable" "cell-permeable3" "cell-substratum" "cell-to-cell" "cells" "cell‐type" "centromere" "cerebellar-specific" "cerebellum" "cftDNA" "ch-TOG" "ch-TOG-TACC3" "chain-modified" "chaperone-like" "chemically-induced" "chemo" "chemo-preventive" "chemo-radiotherapy" "chemo-reagent" "chemo-reagents" "chemo-repellent" "chemo-response" "chemo-sensitivity" "chemoattractant" "chemoendocrine" "chemoradiotherapy" "chemoresistance" "chemoresistant" "chemotherapy-resistance" "chemotherapy-trastuzumab" "chemotherapy‐induced" "chemotypes" "chi-square" "chi-squared" "child-parent" "cholestasis-accelerated" "cholestasis-associated" "cholesterol-containing" "cholesterol-depleting" "cholesterol-lowering" "choroid" "chosen" "chr" "chr12p" "chr19" "chr19_37756707_37760335" "chr2" "chr3_129101148_129103476" "chr5" "chr5_1607662_1663720" "chr9" "chromatid" "chromatids" "chromatograms" "chromophobe" "chromosomally-inserted" "chromosome14q" "ciliate" "circuitry" "cis-element" "cis-regulatory" "cisplatin-naive" "cistrome" "cistrome-wide" "cistromes" "clade" "clear-cell" "clear-cut" "clear-evidence" "clearers" "clientele-specificity" "clinic-pathological" "clinic-pathologically" "clinical-pathological" "clinically-critical" "clinicians" "clinico" "clinico-pathologic" "clinico-pathological" "clinic–pathological" "closed-loop" "coactivator-1" "coactivator-1α" "cobblestone-like" "codominant" "codon" "codon-12" "codon-13" "codons" "cohorts" "coiled-coil" "cold-induced" "cold-shock" "coli" "collagens" "collectives" "colony-formation" "colony-forming" "comedo" "comedo-like" "common-B-ALL" "commonalities" "commonest" "comorbidities" "complex-2" "complex-proficient" "components-beads" "compounds-induced" "concentration-and" "concentration-dependently" "concentration-response" "conditional-null" "conformers" "confounders" "congenita" "contact-induced" "contact-inhibited" "context‐dependent" "continuum" "control-RET" "control-shRNA" "control-treated" "copper-dependent" "copy-containing" "copy-number" "core-binding" "core-complex" "coregulators" "correlatedwithmiR-29b" "cortico-striatal" "cost-effective" "cost-to-benefit" "counter-balance" "counter-protective" "covalently-modified" "covariate" "covariates" "coworkers" "cox-hazard" "coxibs" "co‐expression" "cribriform" "cross-cancer" "cross-compared" "cross-complementing" "cross-contamination" "cross-control" "cross-interaction" "cross-matching" "cross-reacting" "cross-reactivity" "cross-regulation" "cross-regulatory" "cross-resistance" "cross-sectional" "cross-sections" "cross-sensitivity" "cross-species" "cryotherapy" "ctDNA" "cullin-4" "cullin-RING" "cullin3–RING-box" "cut-off" "cut-off-dependent" "cut-offs" "cut-points" "cycD1" "cycE" "cyclapolin1" "cyclase-associated" "cycle-related" "cyclin-T" "cyclins" "cycloxygenase-2" "cyto" "cytodomain" "cytoskeletal-associated" "cytosol-like" "cytosol-to-nucleus" "c–e" "c–h" "d-f" "dL" "dRASSF8" "damage-associated" "damage-containing" "damage-dependent" "damage-independent" "damage-induced" "damage-inducer" "damage-inducible" "damage-inducing" "damage-responsive" "damage–induced" "dark-side" "dataset" "datasets" "day-to-day" "day14" "days" "dbSNP" "dbSNP131" "dbSNP137" "ddATP" "ddPCR" "de-acetylase" "de-conjugated" "de-conjugation" "de-differentiated" "de-fatty" "de-regulated" "de-regulation" "de-repression" "de-stabilization" "de-stabilize" "de-stabilizes" "de-ubiquitinases" "deacetylase-activating" "death-receptor" "decidua" "dedifferentiate" "deeper" "degrader" "degrons" "del-ex19" "del11q" "del17p" "del17p13" "del5395" "delE746-A750" "deletion-type" "delta169" "dense-band" "dense-membrane" "density-dependent" "deoxynucleotidyl" "deoxyuridine" "depolarization-dependent" "deprivation‐induced" "derived-bioactive" "dermal-epidermal" "desaturade-1" "desaturase-1" "desmoplasia" "detection-method" "deubiquitylates" "dextran-treated" "de‐regulated" "di-methylate" "di-methylation" "di-phosphorylated" "diM-α-KG" "diabetes-associated" "diamino-pyrimidine" "diaryl" "dideoxy" "dien-28-imidazolide" "diet-fed" "diet-induced" "diffraction-limited" "dihydrocelastrol-a" "dihydropteridinone" "dimers" "dimethyl-fumarate" "dimethyl-succinate" "dimethyl-α-KG" "dioxooleana-1,9" "dioxygenases" "dipeptidyl" "diphosphate" "diphosphates" "diploid" "dis" "dis-equilibrium" "discrepant" "disease-and" "disposal-like" "disrupted--in" "distant-stage" "disulfide-based" "dithiocarbamate" "diversity-mediated" "dl1520" "doi" "domain-1" "domain-like" "dominantly-inherited" "dosages" "dose-dependence" "dose-dependently" "dose-escalation" "dose-increasingly" "dose-independent" "dose-intensification" "dose-limiting" "dose-response" "dose–effect" "dose–response" "double-cysteine" "double-hit" "double-membrane" "double-minute" "double-mutant" "double-point-mutation" "double-strand" "double-thymidine" "down-modulate" "down-modulated" "down-modulation" "down-slanting" "down-stream" "downregulators" "downstream-regulator" "down‐regulated" "down‐regulation" "drawn" "drivesUHRF1expression" "droplet" "droplet-digital" "droplets" "drug-antioxidant" "drug-combination" "drug-drug" "drug-like" "drug-selection" "dsDNA" "dual-color" "dual-functional" "dual-labeled" "dual-labeling" "dual-labelled" "dual-regulating" "dual-stabilization" "dual-staining" "duct-Henle's" "duct-specific" "ductulo-lobular" "dupA" "duplexes" "dynamin-like" "dysgeneses" "dyslipidemias" "dysplasia" "dysplasias" "d–f" "eFluor670" "eGFP-fusion" "eGFP–HDAC3-expressing" "eGFP–HDAC3-overexpressing" "eIF4" "eLife" "eQTL" "earlier-stage" "early-mid" "early-onset" "early-stage" "early-treatment" "ebiNSc" "echinoderm" "echocardiography" "eclampsia-associated" "ectoderm" "ectopia" "edema" "effecter" "effectuates" "efficacy-of-standard" "eighty-five" "eldest" "electron-dense" "electron-lucent" "eleven-day" "eleven-nineteen" "emboli" "embolus" "embryoid" "embryonic-lethal" "empts" "enantiomer" "enantiomers" "end-diastolic" "end-product" "end-resection" "end-stage" "end-to-end" "endometrioid" "endometrium" "endotoxemia" "endpoint" "endpoints" "energy-efficient" "enhancer" "enhancer-binding" "enteropathy" "enzyme-substrate" "enzymes" "enzyme–activator" "enzyme–substrate" "eosin" "epidermoid" "epithelia" "epithelial-like" "epithelial-mesenchymal" "epithelial-mesenchymal-like" "epithelial-specific" "epithelial-stroma" "epithelial-to-mesenchymal" "epithelial‐to" "epithelial–mesenchymal" "epithelioid" "epithelioid-like" "epithelium" "epitopes" "erlotinb" "erytheroid-derived-2-like" "erythroid-2–related" "estrogen-and" "estrogen-deprived" "estrogen-receptor-α" "et" "eta" "et " "ever-changing" "ever-expanding" "evidenceofmiR-29b's" "ex" "ex-smoker" "ex-smokers" "ex-vivo" "ex12" "ex2" "ex3" "exercise-induced" "exocrine" "exon-intron" "exon11-mutated" "exons" "exosome" "expressers" "extra-hepatic" "extra-islet" "extra-nuclear" "extra-ribosomal" "extra-thymic" "extra-uterine" "extracellularly-delivered" "extrinsic–death" "ex " "e–08" "facilitated-tumor" "factor-1" "factor-1α" "factor-2" "factor-kB" "factor-kappa-B" "factor-kappaB" "factors" "fair-skinned" "false-discovery" "false-discovery-rate-corrected" "false-positives" "family-trio" "far-fetched" "farnesyl" "fast-migrating" "fat-pads" "fatigue-induced" "feedback-mediated" "female-derived" "female-specific" "female-type" "femtosecond" "fenoprofen" "ferroportin-1" "fiber-type-specific" "fibro-muscular" "fibroblast-like" "fibroblastoid" "fibroblastoid-like" "fibrofatty" "fibrosis-associated" "field-induced" "field-of-view" "filopodia-like" "fine-needle" "fine-tune" "fine-tuned" "fine-tuning" "finger-like" "first-degree" "first-generation" "first-in-class" "first-line" "five-drug" "five-fluorouracil" "five-transmembrane" "five-weeks" "five-year" "fixed-dose" "flag‐PIK3CA" "flash-frozen" "flat-mounts" "flavaglines" "flavonolignan" "flcn-1" "flow-cytometric" "flow-cytometry" "flow-mediated" "flowchart" "flow‐mediated" "flox" "fluorodeoxyglucose" "fluorophore" "fluorophores" "focus-forming" "foenum" "foenum-graecum" "foeto" "foeto–maternal" "fold-coverage" "fold-increase" "follicles" "follow-up" "follow-ups" "followed-up" "followup" "forMARCKS" "forebrain" "forestomach" "formalin-fixation" "forty-eight" "four-serine" "fourth-largest" "frame-shift" "frameshift" "frameshifts" "free-survival" "fresh-frozen" "front-back" "front-line" "front-to-back" "frozen" "fructose-2,6-bisphosophatase" "fs" "fsX16" "full-lenth" "full-term" "full-text" "fumarate" "fusion-activated" "gDNA" "gadolinium" "gain-and-loss-of-function" "gain-of-function" "gain-of-functions" "gain‐of‐function" "gallbladder" "ganglion-10" "gasotransmitters" "gastrectomy" "gastro" "gastro-esophageal" "gastro-intestinal" "gate-keeper" "gate-keepers" "gatekeeper" "geldanamycin-derivative" "gene-disease" "gene-expression-based" "gene-gene" "gene-panel" "gene-regulatory" "gene-therapeutic" "genes" "geneset" "genetic-association" "genetically-defined" "genetically-engineered" "gene–gene" "genome" "genome-wide" "genomes" "genotype" "genotype-phenotype" "genotypes" "genotype–phenotype" "geranylgeranyl" "geranylgeranyl-transferase" "germ-line" "gk378" "glia" "glia-like" "glucagon-like" "glucocorticoid-regulated" "glucose-1-phosphate" "glucose-6" "glutamate-cysteine" "glutamate-glutamine" "glutamate–cysteine" "glutamine-to-leucine" "glutamyl" "glycerol-3-phosphate" "glycine-rich" "gm" "goes" "gondii" "gp87" "gpdh" "gpdh-1" "gpdh-2" "graecum" "gram-scale" "granulo" "granulo-monocyte" "granulo-monocytic" "granulocyte-monocyte" "greater" "greatest" "green-fluorescent" "grip-like" "group11" "growth-arrest-specific" "growth-dependency" "growth-restrictive" "growth-suppressive" "gsy-1" "gt33" "guanine-mimetic" "guanine-to-thymidine" "gymnestrogenin" "hESCs" "hMSC" "hMSCs" "hMps1-MDM2-ubH2B" "hMps1with" "hNPCs" "hNQO1-ARE-Luc" "hRBM4" "hT" "hTER" "hTERT-cells" "hTRmin" "haeme" "haemolysis-associated" "half-ERE" "half-fold" "half-inhibitory" "half-life" "half-lives" "half-maximal" "half-siblings" "half-sisters" "half-site" "half-sites" "half-sized" "halo-like" "haplo-insufficiency" "haplotype" "haplotypes" "hard-to-find" "has-miR-1" "has-miR-142-5p" "has-miR-202" "has-miR-98" "has-miR29" "head-to-tail" "heart-specific" "heat-inducible" "heat-map" "heat-shock" "heatmap" "helices" "helix" "helix-loop-helix" "helixes" "helix–loop–helix" "hemagglutinin-epitope-tagged" "hematoxylin-eosin" "hemeoxygenase-1" "hemispherectomy" "heparin-agarose" "hepatocyte-derived" "hepatocyte-like" "hepatoid" "hepatotoxins" "hept-5-ene-2-carboxylic" "heptapeptide" "hetero" "hetero-dimeric" "hetero-dimers" "hetero-oligomerization" "hetero-tetramer" "heterodimers" "heteronucleotide" "heterozygote" "hg19" "hidden" "high-TIL" "high-ab" "high-affinity" "high-affinity-binding" "high-cellularity" "high-concentration" "high-confidence" "high-content" "high-copy" "high-degree" "high-density" "high-dose" "high-energy" "high-fat" "high-fat-diet" "high-glucose" "high-grade" "high-heterogeneity" "high-input" "high-input-power" "high-iron" "high-irradiance" "high-level" "high-levels" "high-mobility-group" "high-penetrance" "high-penetrant" "high-performance" "high-quality" "high-resistance" "high-resolution" "high-risk" "high-sensitivity" "higher-affinity" "higher-dose" "higher-order" "highest-scoring" "highly-activated" "highly-annotated" "highly-sensitive" "high‐risk" "hinge–hinge" "hippo-mediated" "histochemistry" "histologies" "histology" "histotype" "histotypes" "hnRNPA1-ESS" "hnRNPA1-ISS" "hnRNPs" "home-brew" "homeodomain" "homo-dimers" "homo-oligomers" "homogenates" "homolog" "homolog-5" "homologs" "homology-2" "homology-based" "homonucleotide" "homopurine" "homopyrimidine" "homozygote" "homozygotes" "hormonal-dependent" "hormone-naïve" "hospital-based" "hot-miR-138" "hot-spot" "hotspot" "hotspots" "hsCRP" "hsa-miR-101" "hsa-miR-125b" "hsa-miR-29a" "hsa-miR-29b" "hsa-miR-513a-5p" "hsa-miR-628-3p" "hsa-miR-9-1" "hsa-miR-9-2" "hsa-miR-9-3" "hsp-miR-98" "hyaloid" "hydrogels" "hydrogen-bond" "hydrogen-exchanger" "hydroxycholesterol" "hyper" "hyper-activation" "hyper-dissemination" "hyper-invasive" "hyper-proliferation" "hyper-γ-H2A" "hyperinsulinemia" "hyperoxia-CCN1" "hyperphosphatemia" "hyperpolarization-activated" "hyperresponsiveness" "hypo-acetylation" "hypo-expression" "hypo-phosphorylated" "hypocalcemia" "hypodermis" "hypoglycemia" "hypoxia-LY294002" "hypoxia-niche" "hypoxia-protective" "hypoxia-survival" "i-GSEA4GWAS" "iBMK" "iCOGs" "iEA" "iEA " "iGSEA4GWAS" "iNOS+p53" "iNSCs" "iNSCs-like" "iNSc" "iNSc-like" "iVSD" "iVSDs" "identifiers" "ie" "ii" "iii" "ill-defined" "imidazole-4-carboxamide" "immediate-early" "immune-cell-poor" "immune-cell-rich" "immune-depressed" "immune-driven" "immune-histochemical" "immune-histochemistry" "immune-mediated" "immune-related" "immuno-FISH" "immuno-histochemistry" "immuno-modulatory" "immunoarray" "immunoassay" "immunocytochemistry" "immunoglobulin" "immunoglobulin-like" "immunophenotype" "immunophenotypes" "immunoprecipitant" "immunosurveillance" "immunotherapies" "immunotherapy" "impedance" "in-depth" "in-frame" "in-house" "in-line" "in-nucleus" "in-situ" "in-stent" "in-vitro" "in-vivo" "inK-ras" "inMCF" "inNrf2" "inPhb2" "indel" "indels" "induced-fit" "induced-pluripotent" "infection-induced" "inflammation-associated" "inflammation-induced" "inflammation-promoting" "inflammatory-like" "inhibition-not" "inhibiton" "inhibitor-1" "inhibitor-NF-κB" "inhibitor-treated" "inhibitors" "input-power" "input-power-dependent" "inside-out" "insulin-AKT-mTOR" "insulin-activated" "insulin-dependent" "insulin-induced" "insulin-like" "insulin-mediated" "insulin-sensitive" "insulin-stimulated" "insulinoma-glucagonoma" "int-1" "integrin-cytoskeleton" "integrin-evoked" "intensity-modulated" "inter-cellular" "inter-chromosomal" "inter-domain" "inter-group" "inter-individual" "inter-malignancy" "inter-membrane" "inter-observer" "inter-relationship" "inter-strand" "inter-study" "inter-subset" "interacome" "interactome" "interactomes" "interconvert" "intercrosses" "intermediate-conformation" "intermediate-risk" "intermembrane" "internet" "interquartile" "interstitium" "interstrand" "intestinal-type" "intima" "intra-S" "intra-S-phase" "intra-domain" "intra-epithelial" "intra-islet" "intra-mitochondrial" "intra-ovarian" "intra-peritoneal" "intra-protein" "intra-residual" "intra-tissue" "intra-tumor" "intra-tumoral" "intracellular-domain" "intractableEML4-ALK" "intramitochondrial-calcium-dependent" "intrinsic–mitochondrial" "intron-2" "introns" "invariant" "invasion-associated" "invasion-inducing" "invasion-inhibition" "invasion-metastasis" "invasion-promoting" "in‐house" "ion-pair" "ionization-time" "irradiance" "irradiances" "irradiation-induced" "irradiation-treated" "ischaemia" "islet-derived" "iso-elasticity" "isoindolin-2-ylmethyl" "isothiocyanatostilbenes" "isotype" "isotypes" "isozymes" "iv" "jam-l" "kDa" "kappa-light-chain-enhancer" "karyotype" "karyotypes" "kb24" "kb33" "kbp" "kcal" "ketoprofen" "ketorolac" "kg" "kinase-null" "kinase1" "kinases" "kinase‐associated" "kinetochore-mitotic" "kinome" "kit-8" "km25" "knock-down" "knock-in" "knocked-down" "knockin" "knocking-down" "kruppel-like" "l-glutathione" "lHSP72" "lactose" "lambda" "lamina" "laminin-triggered" "large-cell" "large-scale" "larger-scale" "larger-sized" "laser-capture" "laser-damage" "laser-induced" "laser-irradiated" "late-onset" "late-passage" "late-stage" "lavage" "lavages" "layer-specific" "lead-like" "leave-one-out" "left-side" "lenti-ZFP36L1" "lenti-ZFP36L1-infected" "lenti-ctrl-infected" "lenti-shZFP36L1" "lenti-viral" "less-than-perfect" "let-7a" "let-7b" "let-7f" "let-7f-5p" "let-7i" "leukemia-1" "leukemia-2" "leukocoria" "life-long" "lifespan" "ligand-RTK" "ligand-less" "ligand-receptor" "light-chain" "line-to-line" "lineage-specific" "lineage-survival" "lipoproteins" "lipoxygenase-5" "liriodenine" "littermate" "littermates" "live-cell" "liver-carcinogenic" "lncPro" "lncRNA" "lncRNA+mRNA" "lncRNA-ATB" "lncRNA-GAS5" "lncRNA-anti-differentiation" "lncRNA‐DLEU1" "lncRNA‐related" "lncRNA–mRNA" "loCP" "localizations" "lock-and-key" "locked-nucleic" "loco-regional" "locus-specific" "log-additive" "log-fold" "log-normal" "log-rank" "log2" "long-chain" "long-lasting" "long-lived" "long-period" "long-range" "long-standing" "longer-lasting" "longer-term" "long‐term" "look-up" "loss-of-ATM-function" "loss-of-function" "loss-of-heterozygosity" "loss‐of‐function" "low-ER-staining" "low-HER-2-expressing" "low-MPS" "low-TIL" "low-abundance" "low-affinity" "low-complexity" "low-coverage" "low-density" "low-differentiation" "low-dose" "low-energy" "low-frequency" "low-grade" "low-input-power" "low-irradiance" "low-level" "low-levels" "low-passage" "low-penetrance" "low-penetrant" "low-penetrate" "low-power" "low-proliferative" "low-risk" "low-set" "low-to-null" "lower-bound" "lower-differentiated" "lower-differentiation" "lower-grade" "luciferase-reporter" "luminal-like" "luminal-to-basal" "luminal-type" "lumpectomy" "lupus-like" "lymph-node" "lymph-node-positive" "lymphoblastoid" "lymphoma-2" "lymphoma-extra" "m3p" "m5p" "mADC" "mADCs" "mAG" "mAG1" "mAb" "mAb135" "mAb48" "mAbs" "mCRC" "mCRCs" "mCRPC" "mGFP" "mHER2" "mHSP72" "mHTT" "mIR-200c-driven" "mJ" "mKO2" "mL·h" "mRNA" "mRNA-level" "mRNA-like" "mRNA-stability" "mRNAs" "mRNA‐ESR1" "mRNA–ncRNA" "mROS" "mSigDB" "mSin3A" "mT" "mT-mG" "mTOR-inhibitor" "mTOR-pathway" "mTOR1" "mTORopathies" "macro-metastasis" "macropulse" "macropulses" "macroscopicK" "magainin1" "magnesium-activated" "make-up" "malignances" "malignancy‐specific" "mammography" "mammosphere" "mammospheres" "mantGTP" "mastectomy" "master-c-Myc" "materials" "matrix-detachment" "mature-B-cell" "maximum-tolerated" "mdm2-C" "mdx" "mdx-βgeo" "mediated-ADCC" "medically-intractable" "medications" "medium-to-large" "medulla" "medullary-like" "mega-analysis" "megalencephaly-polymicrogyria-polydactyly-hydrocephalus" "melanogaster" "melittin-Sepharose" "mellitus" "membranaceus" "membrane-cytoskeletal" "membrane-permeable" "membrane‐associated" "membrane‐bound" "mesenchymal-CSCs" "mesenchymal-epithelial" "mesenchymal-like" "mesenchymal-related" "mesenchymal-to-epithelial" "mesenchymal–epithelial" "mesenchyme" "mesenchyme-like" "mesoderm" "mesylate" "metal-stress" "metalloproteinase-1" "metalloproteinase-released" "metastasis-repressive" "metastasis-suppressive" "metastatic-repressive" "methanesulfonate" "methide" "methides" "methionine–choline-deficient" "methoxy" "methyl-DNA" "methyl-Ile" "methyl-Met" "methyl-methanesulfonate" "methyladenine" "mevalonate" "mg3" "miR-1" "miR-1-based" "miR-101" "miR-101-transfected" "miR-103" "miR-107" "miR-107-induced" "miR-107-mediated" "miR-107-overexpressing" "miR-10a" "miR-122" "miR-122-mediated" "miR-124" "miR-124-1" "miR-125" "miR-125-5p" "miR-1254" "miR-125a" "miR-126" "miR-126a-3p" "miR-127" "miR-128" "miR-130a" "miR-132" "miR-133a" "miR-133b" "miR-135" "miR-135a" "miR-138" "miR-138-mediated" "miR-138-suppressed" "miR-139-3p" "miR-139-5p" "miR-139-5p-expressing" "miR-139-5p-expression" "miR-141" "miR-141-3p" "miR-142" "miR-142-3p" "miR-143" "miR-143-3p" "miR-144" "miR-144-SW1463" "miR-144-SW837" "miR-144-overexpressing" "miR-144-trans-fected" "miR-145" "miR-146a" "miR-146b-3p" "miR-148b" "miR-150" "miR-150-RET" "miR-150-RET-infected" "miR-150-expressing" "miR-155" "miR-155-3p" "miR-155-regulated" "miR-155-treated" "miR-15a" "miR-16" "miR-16-mediated" "miR-17" "miR-17-92" "miR-18" "miR-181" "miR-182" "miR-1826" "miR-183" "miR-185-3p" "miR-18a" "miR-18b" "miR-190" "miR-192" "miR-192-mediated" "miR-192-transfected" "miR-192-treated" "miR-193a-3p" "miR-195" "miR-195-5p-agomir-treated" "miR-196a-5p" "miR-197-3p" "miR-199" "miR-199a" "miR-199a2" "miR-199b" "miR-199b-5p" "miR-1NC" "miR-1inhbitor" "miR-1inhibitor" "miR-1mimic" "miR-200" "miR-200s" "miR-202-3p" "miR-203" "miR-204" "miR-205" "miR-208b" "miR-20a" "miR-210" "miR-210-3p" "miR-211" "miR-212" "miR-212-3p" "miR-212-induced" "miR-214" "miR-214-based" "miR-214-induced" "miR-214-inhibited" "miR-214-overexpressing" "miR-214–overexpressing" "miR-215" "miR-216b" "miR-219" "miR-219-1-3p" "miR-22" "miR-22-deficient" "miR-22-dependent" "miR-22-treated" "miR-221-mediated" "miR-223" "miR-224" "miR-22–deficient" "miR-22–sufficient" "miR-24" "miR-24-Bim" "miR-24-mediated" "miR-24-overexpressing" "miR-26a" "miR-26b" "miR-296" "miR-29b-AKT" "miR-29b-AKT-HK2" "miR-29b-mediatedcontrolof" "miR-29bmay" "miR-3" "miR-30" "miR-301b" "miR-302a" "miR-302c" "miR-30a" "miR-30c" "miR-3151" "miR-32" "miR-320" "miR-320b" "miR-320b-transfected" "miR-326" "miR-328" "miR-329" "miR-331-3p" "miR-33a" "miR-33a-induced" "miR-33a-overexpressing" "miR-33b" "miR-34" "miR-340" "miR-342-3p" "miR-346" "miR-346-activated" "miR-346-dependent" "miR-346-facilitated" "miR-346-induced" "miR-346-loop" "miR-346-mediated" "miR-34b" "miR-34c" "miR-361" "miR-361-3p" "miR-367" "miR-369-3p" "miR-369–3p" "miR-370" "miR-371-3p" "miR-372" "miR-373" "miR-376b" "miR-378a-3p" "miR-380-3p" "miR-382" "miR-410" "miR-424" "miR-433" "miR-450a" "miR-451" "miR-451-induced" "miR-454" "miR-455" "miR-455-3p" "miR-484" "miR-485-3p" "miR-486" "miR-487a" "miR-487b" "miR-490-3p" "miR-491-3p" "miR-494" "miR-495" "miR-499a-5p" "miR-502" "miR-503" "miR-505" "miR-506" "miR-508" "miR-510" "miR-511" "miR-512-3p" "miR-513a-5p" "miR-517a" "miR-517c" "miR-518b" "miR-518d" "miR-518f" "miR-519c" "miR-519d" "miR-519e" "miR-520b" "miR-520d-5p" "miR-522" "miR-523" "miR-545" "miR-548a" "miR-548a-5p" "miR-548b-5p" "miR-548c" "miR-548c-5p" "miR-548d" "miR-548d-5p" "miR-556-3p" "miR-561" "miR-570" "miR-576-3p" "miR-584" "miR-589" "miR-590-3p" "miR-597" "miR-598" "miR-599" "miR-618" "miR-622" "miR-622-associated" "miR-622-mediated" "miR-622-overexpressing" "miR-622-transfected" "miR-627" "miR-628-3p" "miR-629-HNF4-miR-124" "miR-652" "miR-654-3p" "miR-655" "miR-672" "miR-7-dependent" "miR-708" "miR-888" "miR-889" "miR-891a" "miR-9" "miR-9-2" "miR-9-3" "miR-9-3p" "miR-9-5p" "miR-9-5q" "miR-9-mediated" "miR-92" "miR-92a-1" "miR-92a-2" "miR-92a-2-3p" "miR-92a-2-5p" "miR-92a-3p" "miR-93" "miR-95" "miR-98" "miR-chips" "miR-control-SW1463" "miR-control-SW837" "miR-control-transfected" "miR103" "miR133a" "miR139-5p" "miR200c" "miR488" "miR92a-2-3p" "miR92a-2-3p-overexpressing" "miRDB" "miRNA" "miRNA-130a" "miRNA-15a" "miRNA-16" "miRNA-16-1" "miRNA-192" "miRNA-200" "miRNA-205" "miRNA-21" "miRNA-212" "miRNA-23a" "miRNA-29" "miRNA-346-mediated" "miRNA-372" "miRNA-451" "miRNA-9" "miRNAs" "miRNA‐mediated" "miRNA–lncRNA" "miRNA–mRNAnetwork" "miRNA–mRNA–lncRNA" "miRNA–mRNA–lncRNAinteraction" "miRNA–mRNA–lncRNAinteractions" "miRanda" "miRwalk" "miR‐106a" "miR‐106a~363" "miR‐130a‐3p" "miR‐141" "miR‐148b‐3p" "miR‐17" "miR‐17‐3p" "miR‐17‐5p" "miR‐17‐92" "miR‐18a‐5p" "miR‐19" "miR‐19a" "miR‐19a‐3p" "miR‐19b" "miR‐19b‐3p" "miR‐200c" "miR‐20a" "miR‐20b" "miR‐25‐3p" "miR‐363" "miR‐490" "miR‐490‐3p" "miR‐490‐5p" "miR‐92" "miR‐92a" "miR‐92‐3p" "miR‐93‐5p" "mice" "micro-CT" "micro-compartments" "micro-computed" "micro-disection" "micro-dissected" "micro-environment" "micro-injected" "micro-injuries" "micro-irradiation" "micro-metastases" "micro-molar" "micro-tumor" "micro-tumors" "microRNA-144" "microRNA-200" "microRNA-22" "microRNA-451" "microRNA-494" "microRNA-7" "microdomains" "microenvironment-induced" "microenvironment-niches" "micrographs" "microparticles" "micropipette" "microsatellite" "microsatellite-unstable" "microvasculature" "microvessel" "micro‐RNAs" "mid-anteroseptal" "mid-inferior" "mid-infero-lateral" "mid-inferolateral" "mid-life" "mid-myocardial" "mid-myocardium" "midbrain" "middle-ear" "migration-and" "mild-inflammatory" "mild-regenerating" "milliseconds" "mim1" "mimics" "mineralization-inducing" "mini-review" "minigenes" "minimal-subunit" "mir-214" "mir-548" "mir30-based" "mirPath" "mis-leading" "mis-sense" "missense" "mitEGFR-GFP" "mitochondria-targeting-EGFR" "mitochondrial-binding" "mitochondrial-dependent" "mitochondrial-mediated" "mitochondrial-related" "mitochondrial-targeting" "mitoses" "mitotic-phase" "mitotic-specific" "mixed-lineage" "mixed-type" "ml " "mobility-shift" "mock-ROCK1" "mock-infected" "mock-infection" "mock-irradiated" "mock-irradiation" "mock-treated" "moderate-inflammatory" "moderate-penetrance" "moderate-risk" "moderate-to-elevated" "moderate-to-high" "moderately-differentiated" "moderately-increased" "modes-of-action" "modest-to-weak" "mono-adducts" "mono-bound" "mono-methylate" "mono-protonated" "mono-site" "mono-therapy" "monoadducts" "monocyte-derived" "monocytic-like" "monocytic-specific" "monolayer" "monophosphate" "monopolar-phenotypic" "monotherapies" "monotherapy" "month-old" "mortality-to-incidence" "moth-eaten" "motif-containing" "motif-dependent" "motif-specific" "motifs" "motile" "motile-to-motile" "mp53BS" "mt-p53" "mucosa" "multi-cancer" "multi-case" "multi-chemotherapy" "multi-component" "multi-drug" "multi-focal" "multi-hit" "multi-institutional" "multi-lineage" "multi-organ" "multi-pathways" "multi-protein" "multi-punch" "multi-stage" "multi-step" "multi-targets" "multi-tissue" "multi-vesicular" "multicenter" "multicentre" "multigene" "multilineage" "multimers" "multiorgan" "multiphoton" "multiple-center" "multiple-hit" "multiple-punch" "multiple-species" "multiple-target" "multiprotein" "multistage" "multivariate" "muscle-resident" "muscle-specific" "muscularis" "mutant-NLS" "mutant-like" "mutant–substrate" "mutations" "myelo-monocytic" "myeloid-cell-rich" "myocardium" "myofiber" "myofibers" "myofibroblast-like" "myofibroblasts" "myristoyl" "myristoylation‐deficient" "n-collar" "n=12" "n=30" "n=5" "n=6" "nCB" "nCounter" "nabumetone" "nano-Gln" "nano-liposomes" "nano-molar" "nano-particle-mediated" "nanoparticulate" "nanosecond" "nascent-RNA" "naso-pharyngeal" "nation-wide" "naïve" "ncRNA–mRNA" "near-complete" "near-fatal" "near-infrared" "near-significance" "near-tetraploid" "nearest" "necropsy" "needle-catheter" "negative-control" "neo-adjuvant" "neo-vascular" "neoadjuvant" "neointima" "neoplasias" "nephrectomy" "nephron" "nephropathies" "nephropathy" "nervous-system" "nestin-positive" "neu" "neural-crest" "neurite" "neuro" "neuro-degenerative" "neuro-developmental" "neuro-hormones" "neuro-protective" "neuroendocrine" "neuron-like" "neuronally-differentiated" "neuropathology" "neurospheres" "neutropenia" "never-smokers" "newer" "next-generation" "next-generation-sequencing" "ngTMA" "nick-end" "nil-by-mouth" "no-cardia" "no-combination" "noncarriers" "nonmalignant" "nonresponders" "nonresponse" "nonsense-mediated" "nonsignificant" "nonsmall" "nonsmokers" "non‐coding" "non‐synonymous" "non‐tumour" "normal-large" "normal-resistance" "normally-reacting" "not-commonly" "nt" "nt+1351" "nts" "nuclear-to-cytoplasmic" "nucleates" "nucleo" "nucleo-cytoplasmatic" "nucleotide-dependent-‘specific’" "nultin3a" "n = 6" "ob" "occurrences" "oestrogen" "ofCDKN2Apromoter" "ofDAB2IP" "ofESR1" "ofK" "ofKEAP1" "ofKEAP1promoter" "ofKeap1" "ofMARCKS‐mediated" "ofPIK3CA" "ofRASSF1" "ofUHRF1fromPDACcells" "ofUHRF1is" "ofUHRF1reduced" "ofbim" "off-target" "offs" "ofnPTB" "ok524" "ok975" "old-style" "oligos" "oligosaccharide-binding" "omega-3" "omega-N" "omic" "omics" "on-going" "on-target" "on-the-fly" "once-daily" "oncodriver" "oncogene-driven" "oncomiR" "oncomirs" "oncoprotein-18" "oncotarget" "one-carbon" "one-ended" "one-letter" "one-month" "one-period" "one-site" "one-step" "one-third" "one-way" "one‐fourth" "oophorectomy" "open-label" "ortholog" "orthologue" "orthologues" "osm-11" "osm-7" "osmo-protective" "osteoblast-like" "osteoblasts" "osteomimicry" "otitis" "out-of-control" "out-of-expectation" "outer-membrane" "ovarian-specific" "ovariectomy" "over-accumulate" "over-activated" "over-activating" "over-diploid" "over-presence" "over-proliferation" "over-replication" "over-representation" "over-simplistic" "over-treated" "over-treatment" "over-winding" "overexpressors" "overnight-cultivated" "overuse" "overview" "over‐expressed" "over‐expression" "oxidative-reductive" "oxidative-stress-responsive" "oxido-reductase" "oxoG" "oxoglutarate" "oxoguanine" "oxygenase-1" "p18IN4" "p21CIP" "p21waf" "p38K" "p38MAPK" "p38MAPK-mediated" "p38β" "p53-LOH" "p53-antagonist" "p53-competent" "p53-defective" "p53-gene-specific" "p53-heterozygotic" "p53-independent" "p53-independently" "p53-null" "p53-pathway" "p53-proficient" "p53BR" "p53BRmt" "p53BS" "p53RE" "p53REs" "p53wt" "p70S6K-dependent" "p85α" "p=0.01" "p=0.02" "p=0.03" "p=0.09" "p=0.93" "pAKT" "pAKT2" "pAKT473" "pALK" "pALK-Y1604" "pATM" "pBOB" "pCM184" "pCMV-Klotho" "pCMV-Klotho-transfected" "pCMV6" "pCMV6-Klotho" "pCR" "pCdc2" "pChk1" "pChk1s" "pChk2" "pDCIS" "pDNA-PK" "pDNA-PKcs" "pDNA3.1" "pEGFP-AR" "pEGFP-V" "pEGFR" "pERK" "pERK5" "pEZX-PG04" "pFOXO1" "pFOXO1A" "pGADT7" "pGATA" "pGBKT7" "pGL3-1172" "pGL3-1733" "pGL3-202" "pGL3-320" "pGL3-320-mut" "pGL3-502" "pGL3-581" "pGL3-702" "pGL3-B-miR-101-L" "pGL3-B-miR-101-M" "pGL3-B-miR-101-MBS" "pGL3-B-miR-101-S" "pGL3-B-miR-101-W" "pGL3-B-miR-101-WBS" "pGL3-Basic-transfected" "pGL3-E-cadherinP" "pGL3-E2F1" "pGL3-E2F1-mut" "pGL3-E2F2" "pGL3-HCCR" "pGL3-HCCRP" "pGL3-PAI-1-3" "pGL3-basic" "pGSK" "pGSK-3" "pGSK3β1130" "pGeneClip-shTCERG1-C1" "pH" "pHBV1.2" "pHER2" "pHH3" "pJAK2" "pLEX" "pLEX-PTPN6" "pLKO" "pLL3.7" "pLYN" "pLasts1" "pLats1" "pLuc-979" "pMET" "pMIR-COX-2" "pMst1" "pN" "pN808S" "pRL-null" "pRRL-CMV-IRES-GFP" "pRuF" "pRuF-empty" "pS127-YAP" "pS127-YAP1" "pS184" "pS204-pS208" "pS210-CPEB1" "pS38-STMN1" "pS423" "pSMAD2" "pSPL3" "pSTAT3" "pSUPERp53" "pSer-Pro" "pSer307-specific" "pSerPro" "pSiCHECK2" "pSilencer" "pSilencer2.1" "pSilencer2.1-HCCR" "pSmad2" "pSmad2C" "pSmad3C" "pSmad3L" "pStage" "pT" "pT1-4" "pT306" "pT4" "pY" "pY1221" "pY1234" "pY31" "pY357-YAP1" "pY416-SRC" "pY527-SRC" "pY925" "pYAP" "pYAP-S127" "pYB1" "pachygyria" "pack-years" "paired-cell" "pairwise" "palmitoylcarnitine" "pan-AKT" "pan-DUB" "pan-HER" "pan-HER-TKI" "pan-MMP" "pan-PI3K" "pan-PIM" "pan-cadherin" "pan-caspase" "pan-inhibitor" "pan-nuclear" "pan-regulated" "pan-specific" "pan-upregulation" "pan-βAR" "pancreatitis" "pancreatitis-like" "para-medial" "para-medially" "paracrine" "paralog" "paralogues" "parenchyma" "parent-child" "parents" "parthanatos" "parvum" "pathobiology" "pathogen-associated" "pathogen-dependent" "pathophysiology" "pathway-proficient" "patients" "pattern-based" "pattern-recognition" "pcDNA-survivin" "pcDNA3-myc" "peak-like" "pectus" "peg-IFN" "penetrance" "penetrant" "peptide-1" "peptide-6" "peptide-like" "peptide-substrate-binding" "peptides" "per-allele" "perforin" "perhaps" "peri-operative" "peri-tumoral" "peritoneum" "person-time" "phAR1.6Luc" "phAR1.6Luc-UTR" "phAR1.6Luc-UTRm1" "phAR1.6Luc-UTRm2" "phAR1.6Luc-UTRm3" "phAR1.6Luc-UTRm4" "phAR1.6Luc-UTRm5" "phAR1.6Luc-UTRm6" "phAR1.6Luc-UTRΔm1" "phAR1.6Luc-Δm1" "pharmaco-mimetic" "phase-II" "phase-III" "phenotype-like" "phenylarsine" "phenylcarbamothioyl" "phosphatidylinositol-3-OH" "phospho-STMN1" "phosphodegron" "phosphoinositide-3" "phosphoinositide-3-OH" "phospholipid-binding" "phosphopeptide" "phosphopeptide-PBD" "phosphopeptides" "phosphor-AKT" "phosphoribosyl" "phosphorylation-consensus" "phosphorylation-dephosphorylation" "phosphorylation‐deficient" "phospho‐MARCKS" "photo-ablation" "photo-thermal" "photodamage" "photoproducts" "phs000424" "phyllodes" "physician-records" "physio-pathological" "physiology-relevant" "picosecond" "pifithrin-α" "pig-3" "pilaris" "pixel" "planus" "plasmon" "plasticity-inducing" "plate-like" "platelet-tumour" "platform-is" "platins-pemetrexed" "platinum-doublet" "platinum-resistant" "plexiform" "pll3.7" "plug-in" "pluripotency-associated" "plus-end" "pmel-1" "pmiR-RB-REPORT" "pmk-1" "point-mutants" "polarization-based" "polo-like" "poly-A" "poly-ADP" "poly-SUMOylation" "poly-T" "polyI" "polyQ" "polySUMO" "polySUMO2" "polyglutamine-repeat" "polymerase1" "polymicrogyria-like" "polymorphism" "polymorphisms" "polyploid" "polypyrimidine" "poor-differentiation" "poor-prognosis" "poor-risk" "poor-switching" "poorer" "poorly-differentiated" "population-representative" "positron" "positron-emission" "post-IR" "post-PCR" "post-TGFβ" "post-TPF" "post-UVB" "post-analytic" "post-carboplatin" "post-dose" "post-elution" "post-exposure" "post-implantation" "post-incubation" "post-infection" "post-initiation" "post-injury" "post-irradiation" "post-menopausal" "post-mitotic" "post-natal" "post-operative" "post-ovulatory" "post-radiation" "post-reimplantation" "post-release" "post-replication" "post-replicative" "post-stimulation" "post-tamoxifen" "post-therapy" "post-transcription" "post-transcriptional" "post-transcriptionally" "post-transduction" "post-transfection" "post-translation" "post-translational" "post-translationally" "post-transplantation" "post-treatment" "post-wash" "postradiotherapy" "postsurgery" "post‐transcriptional" "precancer" "precancers" "preimmune" "pretreatmentDAB2IPreduction" "pri-miR-101" "pri-miR-138" "pri-miR-346" "pri-miR-622" "pri-miR-9" "pri-miR-9-1" "pri-miR-9-2" "pri-miR-9-3" "primary-response" "primer-pair" "prior-responders" "priori" "pro-IL-1β" "pro-MMP9" "pro-MT1-MMP" "pro-NHEJ" "pro-angiogenesis" "pro-angiogenic" "pro-apoptosis" "pro-autophagic" "pro-cancer" "pro-caspase-3" "pro-caspase-8" "pro-differentiation" "pro-drug" "pro-drugs" "pro-fibrogenesis" "pro-fibrogenic" "pro-fibrotic" "pro-fibrotic-related" "pro-growth" "pro-inflammatory" "pro-luc" "pro-lymphangiogenic" "pro-metastasis" "pro-metastatic" "pro-oncogene" "pro-oncogenes" "pro-proliferative" "pro-survival" "pro-tumor" "pro-tumoral" "pro-tumorigenic" "proband" "probands" "probe-sets" "procaspase-3" "profiler" "progeny" "progesterone-receptor" "progression-free-survival" "progression‐free" "proliferator-activated" "proline-glutamate-serine-threonine" "promoter-associated" "promoter-binding" "promoter-mediated" "proof-of-concept" "proof-of-principle" "prospectively-collected" "prostaglandins" "prostasphere" "prostaspheres" "prostatectomy" "prostate‐specific" "protease-14" "protein-1" "protein-2" "protein-72" "protein-DNA" "protein-RNA" "protein-level" "protein-like" "protein-sulfenic" "proteins" "protein‐2" "protein‐coding" "protein–27" "proteome" "proteomes" "proteomics-based" "proteosome" "proven" "pseudo-EMT" "pseudo-hypoxia" "pseudo-phosphorylated" "pseudo-phosphorylation" "pseudo-substrate" "pseudosubstrate" "psiCheck" "psiCheck‐2" "psoriacin" "psoriasis-like" "publically-available" "pull-down" "pull-downs" "pulldown" "pulled-down" "pulse-chase" "pur" "pur-α" "pur-α-rich" "pygl-1" "pyrrolo-pyrazole" "p " "p = 0.02" "p = 0.09" "q3dx4" "qPCR" "qPCR-HRM" "qRT‐PCR" "quality-of-life" "quencher" "quinazolin-3-one" "quinonoid" "radiation-induced" "radiation-sensitive" "radiation‐based" "radio-chemoresistance" "radio-resistance" "radio-sensitivity" "radio-therapy" "radioresistance" "radioresistant" "random-effects" "rank-ordered" "rapalogs" "rarer" "ras2" "re-analysis" "re-analyzed" "re-appearance" "re-assessed" "re-assessment" "re-challenge" "re-classified" "re-classifies" "re-confirm" "re-confirmed" "re-differentiated" "re-distribute" "re-distribution" "re-enable" "re-encountering" "re-endothelialization" "re-endothelialize" "re-entered" "re-entry" "re-epithelialization" "re-establish" "re-established" "re-establishment" "re-evaluate" "re-evaluated" "re-evaluation" "re-examination" "re-examine" "re-exposure" "re-expressed" "re-expressing" "re-expression" "re-growth" "re-induce" "re-induced" "re-infected" "re-infection" "re-initiate" "re-introduction" "re-localization" "re-operation" "re-overexpression" "re-plated" "re-polymerization" "re-probed" "re-programming" "re-seeded" "re-seeding" "re-sensitize" "re-sensitized" "re-sensitizes" "re-stained" "re-start" "re-suspension" "re-synthesis" "re-testing" "re-transferring" "re-transplantation" "re-treatment" "re-uptake" "reactions–a" "reactive-immunoassay" "read-out" "readout" "readouts" "real‐time" "receiver-operating" "receptor-alpha" "receptor-gamma" "receptor-ligand" "receptor-α" "recombination-deficient" "recut" "red-colored" "red-fluorescent" "reducedDAB2IPdemonstrated" "reducedDAB2IPhas" "reduction-oxidation" "ref" "refractoriness" "regrowth" "regulator-1" "regulatorUHRF1suppresses" "regulators" "regulatory-associated" "regulatory-binding" "relatedness" "releasate" "relocalise" "repair-defective" "repeat-containing" "repeats-containing" "replication-associated" "replication-blocking" "replication-competent" "replication-dependent" "replication-induced" "repopulate" "repressors" "reprogramming-like" "research-outcomes" "resp" "respective-length" "responder" "responders" "retainingDAB2IP" "retro" "retro-orbitally" "retro-viral" "retrovirally-transduced" "retrovirus" "revealedDAB2IP" "reverse-phase" "reverse-transcription" "rginine" "rhAPO2L" "rhApo2L" "rhSLURP1" "rhabdoid" "ribose" "ribose-5-phosphate" "ribulose-5-phosphate" "rich-cell" "right-handed" "right-sided" "ring-finger" "ring-like" "risk-reducing" "risk-reductive" "round-shaped" "round-to-elongated" "rpt6" "rs1042522" "rs1043618" "rs1061581" "rs1078806" "rs1078806-rs2420946-rs2981579-rs2981582" "rs1078806C-rs2420946T-rs2981579T-rs2981582T" "rs1078806T-rs2420946C-rs2981579C-rs2981582C" "rs11237477" "rs11571833" "rs11705932" "rs1219648" "rs12597021" "rs12699477" "rs13361707" "rs1421896" "rs144848" "rs149330805" "rs1748" "rs1799794" "rs1801132" "rs1801274" "rs1966265" "rs2018199" "rs2075158" "rs2075800" "rs2227956" "rs2234693" "rs2234909" "rs2273773" "rs2293347" "rs2293347G" "rs2293347GA" "rs2293347GG" "rs2293347 " "rs2293607" "rs2420946" "rs2420946T" "rs2450140" "rs2510044" "rs2511156" "rs2530223" "rs2547547" "rs25487" "rs2736098" "rs2736108" "rs2853669" "rs2867461" "rs2867461G" "rs2867461 " "rs2972388" "rs2981579" "rs2981579T" "rs2981582" "rs2981582T" "rs3135848" "rs32954" "rs351855" "rs3758391" "rs3859027" "rs396991" "rs412658" "rs41290601" "rs4561483" "rs55637647" "rs55870064" "rs61764370" "rs6457452" "rs689466" "rs7107174" "rs712" "rs7705526" "rs78378222" "rs861539" "rs9340799" "run-away" "run-on" "run-to-run" "s10689-015-9841-9" "s12881-015-0240-8" "s12885-015-1661-7" "s12885-015-1701-3" "s12885-015-1721-z" "s12885-015-1731-x" "s12885-015-1740-9" "s12885-015-1763-2" "s12885-015-1772-1" "s12885-015-1778-8" "s12885-015-1779-7" "s12885-015-1817-5" "s12885-015-1872-y" "s12885-015-1880-y" "s12885-015-1890-9" "s12890-015-0127-7" "s12929-015-0196-1" "s12931-015-0286-3" "s12967-015-0680-0" "s12967-015-0685-8" "s12967-015-0721-8" "s13045-015-0206-5" "s13046-015-0239-1" "s13058-015-0643-7" "s13059-015-0791-1" "s13075-015-0828-6" "s13742-015-0088-z" "sCD40L" "sHSP" "sHSPs" "sIL-6R" "sMaf" "sT-antigen" "sT-antigens" "sTantigen" "saliva-derived" "salpingo" "salpingo-oophorectomy" "sarcomatoid" "scaffolding-like" "scenarii" "scramble-shRNA-treated" "scratch-wound" "sd" "se" "second-degree" "second-generation" "second-largest" "second-line" "secretome" "selenol–thiol" "selenosulfide" "self-activating" "self-aggregate" "self-antigens" "self-association" "self-defense" "self-defensive" "self-degradative" "self-digestion" "self-eliminate" "self-interact" "self-interaction" "self-oligomerization" "self-phosphorylation" "self-protective" "self-renew" "self-renewal" "self-report" "self-sustaining" "self-tolerance" "semi" "semi-conductor" "semi-conservative" "semi-quantify" "semi-quantitative" "semi-solid" "senescence-like" "senescent-specific" "sensitizer" "sensitizers" "sequence-specific" "sequence-specifically" "sequestering-tubulin" "serine-2" "serine-to-alanine" "sessile" "set-up" "seventy-five" "severe-inflammatory" "sgRNA" "sh-POH1-Tet-on" "sh-miR-33a" "sh386" "sh848" "shACC1" "shACSL4" "shAPRT" "shATM" "shBcl" "shBcl-2" "shBcl-xL" "shBub1" "shBub1-#1" "shBub1-#2" "shCBL" "shCBL-Vector" "shCOPR5" "shCon" "shDNA-PK" "shDR5" "shERK" "shERK1" "shERβ" "shETV4" "shFOXO3-treated" "shFOXO3a" "shGFP" "shHIF-1α" "shHO-1" "shLuc" "shNSC" "shNT" "shPTEN" "shR-CBL" "shR-hTERT" "shRNA" "shRNA-vector" "shSUPT" "shSUPT5H" "shSUPT5H-1" "shSUPT5H-2" "shSUPT5H-3" "shScramble" "shUBASH" "shUBASH-1" "shUBASH-2" "shYAP#1" "sham-irradiated" "shockwaves" "short-chain" "short-hairpin" "short-interfering" "short-term" "short-time" "shorter-term" "shp53" "sh‐PIK3CA" "si-1" "si-2" "si-E2F1-1" "si-E2F1-2" "si-GAS5" "si-HULC-1" "si-HULC-2" "si-IκB-α" "si-SPHK1-1" "si-SPHK1-2" "si-Survivin" "siALK" "siCDH2" "siCtrl" "siGFP" "siIGF1R" "siISCU" "siISCU1" "siISCU2" "siMITF" "siNQO1" "siPRMT6" "siR-R" "siRASSF1" "siRASSF1A" "siRNA" "siRNA-1886" "siRNA-transfection" "siRNA1" "siRNA2" "siRNA‐mediated" "siSART3" "siUSP4-2" "sickle-Antilles-haemoglobin" "side-by-side" "side-chain" "side-chains" "side-effect" "side-effects" "side-population" "sigmoid" "signal-to-noise" "signalling-competent" "silencers" "silico" "simplest" "single-base" "single-cell" "single-center" "single-dose" "single-driver" "single-drug" "single-hit" "single-institution" "single-letter" "single-molecule" "single-nucleotide" "single-particle" "single-plex" "single-repeat" "single-site" "single-step" "single-strand" "sip53-treated" "sirtuin" "site-II" "situ" "six-gene" "six-oncogenic" "six-residue" "sixty-eight" "slow-growing" "slowed-down" "slower-migrating" "smMIPs" "small-GTP" "small-angle" "small-bowel" "small-cell" "small-molecule" "small-molecules" "small-nucleolar-RNA" "small-study" "smaller-sized" "smear-like" "smokers" "sodium-bicarbonate" "sodium-chloride" "sodium-dicarboxylate" "sodium-hydrogen" "sodium-induced" "sodium-proton" "soft-agar" "sotrastaurin" "spatial-temporal" "sphere-derived" "sphere-forming" "spheroid-induced" "sphingosine" "spike-in" "spiked-in" "spin-down" "spindle-assembly" "spindle-cell" "spindle-checkpoint" "spindle-like" "spindle-type" "spirometry" "splice-related" "spot-count" "spp" "ss" "ssDNA" "stably-infected" "standard-fat-diet" "standard-of-care" "state-of-the-art" "stathmin-like" "status-dependent" "steady-state" "stellate" "stem-cell" "stem-junction" "stem-like" "stem-line" "stem-loop" "stemloid" "stemness" "step-up" "step-wise" "stepwise" "sterol-response-element-binding" "stilbene" "stiposome" "stn-1" "strand-breaks" "strand-invasion" "stress-activated" "stress-adaptation" "stress-adaption" "stress-associated" "stress-dependent" "stress-induced" "stress-inducible" "stress-mediated" "stress-responding" "stress-responses" "stress-stimulated" "stressful" "stromal-derived" "stromal-epithelial" "structure-activity" "structure-based" "structure–activity" "structure–function" "study-entry" "sub-G1" "sub-G1-phase" "sub-Saharan" "sub-acute" "sub-analysis" "sub-capsular" "sub-categories" "sub-category" "sub-cellular" "sub-class" "sub-classification" "sub-classifications" "sub-clones" "sub-cohort" "sub-diploid" "sub-domains" "sub-effective" "sub-families" "sub-fractionation" "sub-group" "sub-groups" "sub-lethal" "sub-lineage" "sub-maximal" "sub-nanosecond" "sub-nuclear" "sub-optimal" "sub-pathway" "sub-pathways" "sub-population" "sub-populations" "sub-region" "sub-retinal" "sub-sets" "sub-telomeric" "sub-type" "sub-unit" "sub-units" "subG1" "subclasses" "subdomain" "subfamilies" "sublineage" "sublineages" "sublines" "submicron" "submucosa" "subpopulations" "subsequent-line" "subset" "subsets" "substituents" "substoichiometric-associated" "substrate-binding" "substrate-binding-site" "substrate-recognition" "substrate-site" "subtype" "succinate-dehydrogenase" "sulfhydryl" "sulfur-based" "super-expressor" "super-expressors" "super-high" "super-imposed" "superactivate" "supernatant" "supernatants" "suppressorDAB2IPis" "supra-maximal" "supra-physiological" "survivors" "swing-arm" "switching-loop" "sylvestris" "synapse" "syndrome-like" "synergism" "synonimous-synonimous" "synthases-PG" "synthesis-independent" "system-wide" "t-SNARE" "t-circles" "t-rpS6" "t-tpS6" "t0" "tATP" "tBHQ-treatment" "tag-SNPs" "take-rate" "tamoxifen-inducibleGli1" "tamoxifen-inducibleNestin" "tan-shinone" "tankyrase1" "target-DNA" "target-capture-based" "target-gene" "telencephalon" "telomerase-mediated" "telomere-proximal" "telomere-telomerase" "telomeric-repeat" "telomeropathies" "template-complementary" "ten-eleven" "tet-off" "teto-DTA" "tetranor-PGEM" "tetraplegia" "tetraploid" "thatUHRF1‐mediated" "the16-week-old" "theAKT3" "theCDKN2Atumour" "theDAB2IP" "theK" "theKEAP1gene" "theKEAP1promoter" "theLINE‐1promoter" "theMCF‐7" "thenPTB" "therapy-induced" "therapy-refractory" "therapy-specific" "thermo" "thermo-elastic" "thiazoline" "thick-walled" "thiol-containing" "thiol-disulfide" "third-largest" "third-line" "thirty-five" "three-dimensional" "three-finger" "three-letter" "three-or-more" "three-order" "three-stage" "three-step" "three-stranded" "three-tube" "threonine-specific" "thrombocythemia" "thrombus" "thymidine-adenine" "thymidine-to-guanine" "time-average" "time-course" "time-dependency" "time-dependently" "time-invariant" "time-lapse" "time-point" "time-points" "time-series" "timepoint" "times-points" "tissue-resident" "tissue-susceptibility" "tissues" "titers" "tm1044" "tm1944" "tm1Wjl" "to-mesenchymal" "to150" "toPhb2" "toll-like" "topology" "total-STAT3" "total-YAP1" "toxicants" "trade-off" "trans-cellular" "trans-membrane" "trans-regulatory" "trans-tail" "trans-well" "transcript-1" "transcript-specific" "transcription-1" "transcription-quantitative" "transcriptome" "transcriptomes" "transcriptome‐wide" "transducedPhb2" "transducer" "transducing-β-like" "transferase-1" "transformation-like" "transmembrane-4" "transporter-1" "transporter-mediated" "transwell-invasion" "transwells" "trastuzumab-chemotherapy" "trastuzumab-chemotherapy-resistant" "treated-cells" "treatment-naïve" "treatment-period" "tri-lineage" "tri-potency" "tri-potentiality" "trichrome" "tricuspid" "trifluorothiazoline" "trimester" "triphosphate" "triple-hit" "triple-negative" "triple-point-mutation" "triple-staining" "triple‐negative" "triptans" "trisomy" "trisphosphate" "troponin-1" "troponin-I" "trunk-branch" "tube-like" "tubule" "tubules" "tubulin-RhoA" "tubulinopathies" "tumor-adjacent" "tumor-agnostic" "tumor-cytokine-miRNA" "tumor-driver" "tumor-like" "tumor-permissive" "tumor-specificity" "tumor-sphere" "tumor-spheres" "tumor-supportive" "tumor-suppressive" "tumor-surveillance" "tumorDAB2IPstatus" "tumorosphere" "tumorospheres" "tumors" "tumour-based" "tumour-causing" "tumour-mediated" "tumour-promoting" "tumour-suppressive" "tumour-suppressor" "twenty-first" "twenty-five" "twenty-four" "twenty-seven" "twenty-six" "two-base" "two-binding" "two-carbon" "two-chamber" "two-class" "two-color" "two-gene" "two-hairpin" "two-hit" "two-hybrid" "two-photon" "two-pronged" "two-sided" "two-site" "two-step" "two-tailed" "two-thirds" "two-times" "two-way" "two-week" "tympanostomy" "type-1" "type-2" "type-I" "typhimurium" "tyrosine-15-phosphorylated" "tyrosine-phosphorylation-regulated" "ubiquitin-7-amido-4-methylcoumarin" "ubiquitin-proteasome-mediated" "ubiquitin-proteosome" "ubiquitin-thioester" "ubiquitously-expressed" "ubiqutin" "uc001ver" "ultra-deep" "ultra-low" "ultra-short" "ultrafine" "ultrastructure" "un" "und" "under-appreciated" "under-expressed" "under-participation" "under-replicated" "under-representation" "under-treatment" "undergoes" "undergone" "underpinnings" "undertaken" "uni" "univariate" "unmet" "up-regulator" "up-stream" "up-to-date" "up‐regulated" "up‐regulation" "urea" "urothelium" "usedPhb2" "users" "utero" "uveal" "v-SNARE–like" "v1" "v10" "v2" "v2.0" "v3.0" "v4.0" "v6" "vascular-disrupting" "vaso" "vaso-occlusive" "vehicle-treated" "vera" "vesico-ureteral" "vessel-like" "vessel-specific" "vestigial-like" "vi" "villi" "viremia" "virotherapy" "vis-a-vis" "vitro" "vivo" "voltage-gradients" "vs.1" "vs.10.0" "vs.12.0" "vs.14.0" "vs.TT" "v‐Ras" "water-soluble" "web-based" "website" "websites" "weeks" "well-accepted" "well-annotated" "well-balanced" "well-being" "well-conserved" "well-defined" "well-designed" "well-developed" "well-differentiated" "well-differentiation" "well-documented" "well-measured" "well-moderately" "well-preserved" "well-recognized" "well-structured" "well-studied" "well-suited" "well-tolerated" "well‐regulated" "whileOma1" "white-skinned" "whole-cell" "whole-exome" "whole-genome" "whole-tumour" "wide-scale" "wide-spread" "widely-expressed" "wild‐type" "with-no-lysine" "withNCCN" "wks" "work-up" "workers" "workflow" "world-wide" "wound‐healing" "written" "wt-p53" "wt-p53-Huh7.5.1" "wtEGFR" "wtp53" "x-ray" "x10" "xL" "xeno" "xeno-estrogens" "xeno-transplantation" "xenograft-transplantation" "yellow-brown" "yellow-colored" "yet-to-be-identified" "z-score" "z-scores" "zero-transformation" "zinc-induced" "zipper-EF-hand-containing" "×10" "×S" "× 10" "× 10" "÷14" "ɛ-amino" "ʹend" "Αn" "Δ148–314" "Δ169" "Δ245–373" "Δ31–147" "Δ385–543" "Δ5" "ΔC" "ΔC11" "ΔC3-7" "ΔC7" "ΔCD" "ΔCt" "ΔE5" "ΔE8" "ΔE9" "ΔIgG" "ΔKD-1" "ΔKD-2" "ΔLRR" "ΔM" "ΔN" "ΔUBL2" "Δm1" "Δm2" "ΔΨm" "Δψm" "ΦxΦΦΦ" "α-8-oxoguanine" "α-IL23" "α-KG" "α-Me-COOH" "α-MyHC" "α-aminophosphonate" "α-carbon" "α-defensin2" "α-enolase" "α-granule" "α-helical" "α-helices" "α-helix" "α-methyl" "α-methylated" "α-motif" "α-myc" "α-myosin" "α-toxin" "α-β" "α10" "α11" "α1a-tubulin" "α2β1" "α3" "α3β1" "α4" "α4β1" "α6" "α7-nAChR" "α7-nAChR-deficient" "α7-nAChR-mediated" "α7-nAChRs" "α7-nicotinic" "αv" "β-adrenergic" "β-adrenoceptor" "β-carbon" "β-cat" "β-catenin-YAP" "β-cateninaxis" "β-chain" "β-defensin2" "β-helixes" "β-lactose" "β-oxidation" "β-sheet" "β-sheets" "β-site" "β-strand" "β-sympathomimetics" "β-tubulins" "β1-strand" "β1AR" "β1–β2" "β2-Adrenergic" "β2-MG" "β2-adrenergic" "β3" "β3-strand" "β4" "β6" "β8" "βGal" "βeta-catenin" "β‐actin" "γ-H2A" "γ-aminobutyric" "γ-glutamyltransferase" "γ2" "γ3" "γH2aX" "δ-dependent" "ε-amino" "κB" "κt" "μM–30" "μW" "μg" "μg " "μl" "μmol" "χ²" "ϕH2AX" "кB" " 000" "↓and" "∆N151" "∆PAL" "∆Ψ" "−0.1" "△CT"))
null
https://raw.githubusercontent.com/ddmcdonald/sparser/304bd02d0cf7337ca25c8f1d44b1d7912759460f/Sparser/code/s/tools/ns-stuff/old-unknown/ns-unknown-rd-items-phase3-16001-16400.lisp
lisp
(IN-PACKAGE :SP) (DEFPARAMETER SPARSER::*NS-RD-PHASE3-16001-16400* '(".1798_1799GT" ".1799_1800TG" ".444+1G" ".945_946" "474-+30" "4eBP1-S240" "4eBP1-T37" "A+C" "A-1195G" "A-1290G" "A-4" "A-5" "A-D" "A-related" "A-rich" "A-type" "A1" "A146T" "A167T" "A188T" "A1L" "A2" "A276D" "A2a" "A2b" "A30" "A305A" "A30P" "A369T" "A375P" "A5" "A533D" "A549-miR-622" "A549-pLKO" "A549-shDR5" "A550V" "A572V" "A573V" "A628S5" "A8" "A89S" "AA+GA" "ABCSG-90" "ABI" "ABI-3730" "ABI7900" "ABL-inhibitor" "AC" "AC-220" "AC-T" "AC-TH" "ACA-motif" "ACLY-induced" "ACLY-α-ketoglutarate-ETV4" "ACNU-induced" "ACO1" "ACSL4" "ACSL4-functional" "ACTR2" "ACh" "ADAM" "ADR-treatment" "ADRs" "AFMA070WD1" "AG" "AG+GG" "AG-014699" "AG-221" "AGC" "AGGAU" "AGGGT" "AG + GG" "AIIIa" "AJCC" "AKT-DN" "AKT-FOXG1-Reelin" "AKT-HK2" "AKT-mTOR" "AKT-mTOR-p70S6K" "AKT8055" "AKTS1" "ALK-DelGR" "ALK-ECD-Fc" "ALK-FAM150" "ALK-LTK" "ALK-R" "ALK-rearrangement" "ALK-rearrangements" "ALLGGEN" "ALLs" "AMGIO2" "AMIGO1" "AMIGO3" "AMIS" "AML-ETO-expressing" "AML-ETO-induced" "AML1-ETO" "AML1-ETO-depleted" "AML1-ETO-expressing" "AML1-ETO-induced" "AML1-ETO-knockdown" "AMPKα" "ANGPLT2" "ANKRD13" "ANKRD13A" "ANX" "ANX4" "ANXA3" "ANX–2" "ANX–4" "AO" "AOC" "AP-1-dependent" "AP-1-mediated" "AP1-dependent" "AP24163" "AP24534" "APACHE" "APACHE-II" "AR-AKT" "AR-FL" "AR-FL-overexpressing" "AR-V" "AR-V-targeted" "AR-V2" "AR-V3" "AR-V4" "AR-V9" "AR-Vs" "AR-positive" "AR-status" "AR45" "ARBS" "ARE-RNA" "ARE1~4" "ARE2" "ARE3" "ARE4" "ARMS-qPCR" "AS-NMD" "ASC-J9" "ASCL4" "ASCO" "ASF-ESE" "ASO-miR-346" "ASO-miR-346-treated" "AT10" "AT20" "AT7867" "ATAD2-MKK3" "ATB" "ATB-737" "ATC-28" "ATCC" "ATI-KD" "ATM-defective" "ATM-dependent" "ATM-specificity" "ATMIN-null" "ATP-competitive" "ATR-Substrate" "ATRi2" "ATS" "ATTS" "AUBPs" "AUG" "AUKB" "AZD" "AZD-2281" "AZD-6738" "AZD-7762" "AZD1208" "AZD1840" "AZD6378" "Abcam" "Abdel-Ghany" "Ac-Arg-His-Lys" "AcGFP" "Achilles" "Ad" "Ad-LacZ" "Ad-cycE" "Ad-cycE-infected" "Ad-cycE-treated" "Ad-induced" "Ad-mediated" "Ad12" "Ad5-Null" "Ad5-PKCδ-transfected" "Ad5-null" "Ad5-null-transfected" "AdGFP" "AdGFP-HBx-infected" "AdGFP-HCCR" "AdGFP-HCCR-infected" "AdSqLCs" "Adwt" "Affymetrix" "Africa" "African" "African-American" "African-Americans" "Africans" "African–American" "Ahn" "Ahr" "Ai" "Ai+Di" "Aigner" "Aki1" "Akt-CA" "Akt-PH-RFP" "Akt-PS473" "Akt-S473" "Akt-pathways" "Akt1" "Akti" "Akti-2" "Akti1" "Ala2Val" "Alexa" "AlexaFluor-488" "Alzheimer" "America" "American" "Americans" "Amigo" "Amino-acid" "Aminopyrazine" "Anderson" "Androgen-deprivation" "AngII" "Annexin-FITC" "Antagomir-9-3p" "Antagomirs" "Anthriscus" "Apgar" "Arg399Gln" "Aristolactam" "Armt1" "ArrayScan" "Article" "AsPC-1-pBABE-TAZ" "Ashkenazi" "Asian" "Asians" "Asp-N-generated" "Astra" "AstraZeneca" "Astragali" "Astragalus" "Atg5-Atg12" "Au-rich" "AuNP" "AuNPs" "Aukema" "Auranen" "Aurora-A-Borealis" "Aurora-a" "Australia" "Auto-Regulated" "AutoDock" "Aviel-Ronen" "AzadC" "Aβ" "A–5C" "A–C" "A–D" "B-2" "B-LMP1" "B-LMP1and" "B-NHL" "B-SLL" "B-lineage" "B-lymphoid" "B-malignancies" "B-miR-346" "B-regulated" "B-type" "B1" "B16-GFP-MAGE-C2" "B2" "B3" "B4" "BAF3-JAK2-V617F" "BAK-dependent" "BAL-L" "BALB" "BALF" "BAP-1" "BAX" "BCAR4" "BCSCs" "BC‐related" "BD" "BDL" "BEL7402" "BG" "BG-12" "BG-647-SiR" "BGJ398" "BH3-mimetic" "BH3-mimetics" "BH3-only" "BICseq" "BIMEL" "BIN-67" "BJ" "BK" "BK-SS" "BL-like" "BL1" "BLT1-NAD(P)H" "BLT1-NOX-ROS-EGFR-PI3K-ERK1" "BLT1-NOX-linked" "BMI" "BMN" "BMN-673" "BN82685" "BODIPY-493" "BODIPY-GTP-binding" "BPIFA1" "BRAC2" "BRAFV" "BRAFV600" "BRCA-2" "BRCA1-A" "BRCA2-null" "BRCAness" "BRD9" "BS" "BS153" "BSA-Au" "BT168" "BT275" "BT747" "BTC27" "BTC29" "BTCs" "BTZ-resistnat" "BTZ-susceptibility" "BV-176-treated" "BaF3-JAK2-V617F" "BaF3-JAK2-V617F-R" "Balb" "Bardoxolone" "Bardoxolone-methyl" "Barrios-Garcia" "Basal-type" "Bax" "Bay11-7802" "Bay117085" "Bay11–7802" "Bayes" "Bcl" "Bcl-2" "Bcl-xl" "Beesley" "Begg" "Beige" "Bel-7704" "Berkeley" "Berkeley-SS" "Bernasconi" "Bernier-Villamor" "Biacore" "BigDye" "Bim" "Bio" "Bio-6-OAP" "Bio-6-OAP-Skp1" "BioGRID" "Biomax" "Biosystems" "Birt-Hogg-Dubé" "Birt–Hogg–Dubé" "Blc-2" "Blenkiron" "Blood" "Blood-borne" "Bni-1" "Boehringer" "Bond-Max" "Bonferroni" "Bortezomib" "Boyden" "Braak" "Brattain" "Brazil" "BrdUrd" "Bre1" "Bric-a-brac" "Broad-Novartis" "Broad-spectrum" "Bruton" "Burkitt" "B–D" "B–S" "B–S7D" "C+202T" "C-124T" "C-146T" "C-5" "C-899G" "C-C" "C-PARP1" "C-T" "C-T-T-T" "C-glucose" "C-labeled" "C-labelled" "C-labelling" "C-methyl-Met" "C-phosphate-G" "C-rich" "C-serine" "C-terminally" "C0" "C1" "C124R" "C147R" "C18" "C19ORF5" "C2" "C2-TRIM28" "C20" "C2089" "C28" "C2BBel" "C3" "C3H" "C57BK" "C6" "C62" "C62S" "C7ORF60" "CA16" "CA19" "CA19-9" "CA199" "CA19–9" "CACCAGTAATATGC-3" "CACGTG" "CACNA2D" "CAECs" "CAIRO-2" "CAL-101" "CAP" "CAP18" "CARD16" "CAS-1" "CASMC" "CASMCs" "CASP3DN" "CASP8AP2" "CAV1-interaction" "CAV1-interactions" "CB17-Prkdc" "CBF-AML" "CBF-AMLs" "CBF-fusion" "CBFB-MYH11-expressing" "CBFB-MYH11-induced" "CBL-depleted" "CBL-mutant" "CBRH-7919" "CC+CG" "CC-chemokine" "CCAAT" "CCAAT-enhancer-binding" "CCAT2" "CCD" "CCD66" "CCDC66" "CCDs" "CCID" "CCIDs" "CCL" "CCL227" "CCR4-NOT-deadenylase" "CCT031374" "CD-C451A" "CD-C464A" "CD-transfected" "CD102" "CD133-integrin-Par" "CD133WT" "CD133ΔC11" "CD133ΔC3" "CD133ΔC3-7" "CD133ΔC7" "CD133ΔE5" "CD135" "CD168" "CD25 + " "CD28null" "CD28nullCD8 + " "CD28 + " "CD317" "CD326" "CD44 + " "CD4 + " "CD4 +  " "CD52" "CD74‐positive" "CD8 + " "CD90" "CDC25s" "CDDO-Im" "CDK2-mediated" "CDK6-Del" "CDK6-Del-directed" "CDKNA2A" "CEER" "CELSR" "CELSR1" "CENP-1" "CENPJ" "CEP17" "CEP8" "CEU" "CFpac‐1" "CG" "CGA-arginine" "CGK733-inducecd" "CGP3" "CGP53353" "CH25OH" "CHASM" "CHD7" "CHDs" "CHEK2*1100delC" "CHI3L1" "CHOP-like" "CI=1.09–1.24" "CI=1.16–1.37" "CID2950007" "CIMP" "CIP2A–PP2A–c-Myc–dependent" "CJ" "CK1δ" "CKB" "CKB-C283S" "CKD" "CKLF-like" "CL1–5" "CLASH" "CLB-GAR" "CLDs" "CMTM1-8" "CMTMs" "CMV6-Klotho" "CN03" "CN03treatment" "CNS2-deficient" "CNS2-mediated" "CNVer" "CNVs" "CNVseq" "CONSORT" "COPD-PH" "COX-2–1195" "COX-2–765" "COX-2–homozygous" "COX-2–null" "COX-PG" "COX3" "CPEB3" "CPEB4" "CPEBs" "CR-0560" "CR0004" "CR0010" "CR1515" "CR1744" "CRFS" "CRISPR" "CRISPR-Cas9" "CRISPR-Cas9-based" "CRISPR-Cas9-mediated" "CRL-1848" "CSC-like" "CSCS" "CSCs" "CSDC2" "CSDE1" "CSK" "CT+CC" "CT+TT" "CT04" "CTC" "CTD" "CU" "CU-element" "CV" "CVAD" "CVs" "CWR22rv1" "CXB1" "CXCL" "CXCL-12" "CXCL12-mediated" "CXCL14" "CYT-387" "CaMKK" "CaMKKβ" "CaP8" "CaP8 " "Café-au-lait" "Cajal-Retzius" "Caki2" "Caki‐1" "Cancer" "Cardiac-specific" "Carney-Stratakis" "Case1" "Case6" "Casitas" "Catlett-Falcone" "Caucasians" "Cav1" "Cbl_hi" "Cbl_lo" "CdLS-like" "Cdc42" "Cdc42Q61L" "Cdc42‐GTP" "Cdk1" "CellSearch" "Cells" "Cellworks" "Centipeda" "ChIP-PCR" "ChIP-qPCR" "ChIP–quantitative" "ChT" "ChT-L" "Chan" "Chang" "Chaoshan" "Charlson" "CheR-like" "Chem" "Cheminformatics-based" "Chen" "Cheng" "CherryLacR" "Chi-square" "Chi-squared" "Chiron99021" "Chk-1" "Chou" "Chou-Talalay" "Chr5" "Christopher" "Chung" "Cip" "Cip1" "ClG" "ClinicalTrials" "Clinico-pathological" "CoA-Cy3" "CoA-Cy5" "CoA-biotin" "CoA-fluorophore" "Collagen1a1" "College" "Colo-206" "Colonoscopies" "Con" "Con-injected" "Con-treated" "Cornelia" "Corp" "Cox-regression" "Cpeb4-mediated" "Cre-recombinase" "Cre-transducedPhb2" "CreERT2" "Crohn" "Cross-sectional" "Cr " "Cse4" "Ct" "Ctrl" "Cu" "Cul3" "Cullin1" "Cullin1-myc-ΔC" "Cullin1-myc-ΔN" "Cx43-mRFP" "Cybulski" "Cyclapolin1" "Cyp450" "Cyr61-PI3K" "Cys-Sec" "Cys-pair" "CytoSelect" "Cytoscape" "Cytox" "Czech" "Cα" "C‐kinase" "C‐to" "C–Cdc20–substrate" "C–E" "D-3" "D-aspartate" "D-aspartyl" "D10" "D10A" "D10Y" "D17S945" "D2" "D233–K202–S276" "D25N" "D283-effLuc" "D3" "D54" "D6" "DAAs" "DAB21P" "DAB2IPloss" "DAB2IP‐deficient" "DAB2IP‐knockdown" "DAB2IP‐reduced" "DAB2IP‐reduction" "DAB2IP‐retained" "DAF-16" "DAP-81" "DAVID" "DAZAP" "DBF4B" "DC-3" "DC-C" "DCC-2036" "DCLK1" "DEmiRs" "DFG-in" "DG" "DH-PH" "DHPLC" "DIANA-miR" "DIANA-miRPath" "DIANA-microT" "DIANA-mirPath" "DKC" "DLEU1" "DLG" "DLG-motif" "DNA-DNA" "DNA-DSBs" "DNA-DSBs-related" "DNA-End" "DNA-binding" "DNA-damage-induced" "DNA-methyltransferase" "DNA-protein" "DNAH7" "DNAJA2" "DNAJC10" "DNA–DNA" "DNA–PK-dependent" "DNA–protein" "DNM3os" "DNMT-1between" "DNMT3" "DOC‐2" "DOI" "DOX-DNA" "DPL" "DPP3" "DPT" "DR5-mediated" "DRB5" "DRFI" "DSBs" "DTX" "DUB-cofactor" "DUF89" "Daniela" "Dapi" "Darwinian-like" "Davicioni" "Davis" "DcRs" "De-conjugation" "De-differentiated" "Decidual-stromal-cell-derived" "Defensin2" "Diaphanous‐related" "Dictostylium" "Dnd1" "Dohmen" "Dong" "Doppler" "Dose-response" "Double-hit" "Dovizio" "Doyle" "Drip" "Drozd" "DsRed-Rab5-positive" "Dunn" "E-CSC-like" "E-CSCs" "E-FRET" "E-box" "E-box-containing" "E-boxes" "E-cadherin-1" "E-cadherin-like" "E-regulated" "E1-like" "E1308X" "E169del" "E1978X" "E1b" "E1b55K" "E2-signaling" "E2-ubiqitination" "E2419" "E260Term" "E260term" "E2F-regulated" "E2F1-4" "E2F1-His" "E2F1-K63" "E2F1-binding" "E2F1-downstream" "E2F1-driven" "E2F1-mediated" "E2F1-related" "E2F1-target" "E2F3a" "E2F3b" "E2β" "E3-ligase" "E3-like" "E3-ubiquitin" "E3-ubiqutin" "E380A" "E5" "E596QS" "E6" "E6-expressing" "E6-induced" "E6-mediated" "E6-stimulated" "E6E7" "E7" "E7449-dose" "E746-A750" "E748-A752" "E7directly" "E9-pSPL3" "E9.5" "EADC" "EAV1" "EAV1-exressiong" "EAV3" "EBNA1itself" "EBPb" "EBPα-complex" "EBPε" "EBV-LMP1" "EBarrays" "EC109-RASSF8" "EC109-RASSF8-RNAi" "EC109-miR-101" "EC50" "EC9706-miR-101" "ECFP2" "ECFP4" "ECH‐associated" "ECM-receptor" "ECOG-PS" "ED" "ED-1" "EEA1-containing" "EF" "EF-24" "EG" "EGAS00001001302" "EGF-Src-β4" "EGF-TM7" "EGF-like" "EGFP" "EGFP-Fbxw7a" "EGFR-AKT" "EGFR-AKT-mTOR" "EGFR-NSCLC" "EGFR-PI3-kinase-ERK1" "EGFR-PI3K-ERK1" "EGFR-TKIs-naïve" "EGFR-TKIs-resistance" "EGFR-TKIs-resistant" "EGFRvIII" "EGanimals" "EJ-1" "EKR1" "EL" "ELF" "ELF-EMF" "ELF-EMF-dependent" "ELF-EMF-exposed" "ELF-EMF-exposure" "ELF-EMF-induced" "ELISPOT" "EMF-ELF" "EML-4ALK" "EML-ALK" "EML4-ALK-induced" "EML4-ALK-mediated" "EML4-ALK-rearranged" "EMQA" "EMQA-paclitaxel" "EMT-CTCs" "EMT-like" "EMT-suppressive" "ENSMUSP00000005504" "ENSMUSP00000130379" "ENaC" "EORTC" "EPITHELIAL" "EPSM" "ER-CDH1" "ER-positive" "ER-siIGF1R" "ER-α36" "ER-α66" "ERD7" "ERE-luciferase" "EREs" "ERGIC3" "ERK-dependent" "ERMS" "ERS" "ERp29\\MGMT" "ERα-and" "ERα-negative" "ERα-replete" "ERα-splice" "ER‐positive" "ES7" "ES8" "ESC-like" "ESEs" "ESMO" "ETGE" "ETO-treatment" "ETV5" "EU" "EVTs" "EVs" "EWSC" "EWSCs" "Early-stage" "East-Asian" "EdU-incorporation" "Edu" "Edward" "Effects" "Egger" "Egypt" "Eighty-nine" "Ell-OE" "Ell3-OE" "Emodin-3-methyl" "End1" "Endothelial-specific" "English" "EpRE" "EpREs" "Epcam" "Epithelial-mesenchymal" "Epithelial-to-mesenchymal" "Epstein-Barr" "Epstein–Barr" "ErbB" "ErbB2–ErbB3" "ErbB2–ErbB3-mediated" "ErbB3" "ErbB4-mediated" "Estrogen" "Estrogen-and" "Europe" "European" "Europeans" "Evans" "Ewing’s" "Ex2-28C" "ExAC" "Exosomes" "Eμ-Myc" "F+I" "F-FDG" "F-SNP" "F-actin" "F-purification" "F-purified" "F26IIB" "F9" "F9-derived" "FA-Lys" "FA-chromatin" "FA-histone" "FA-like" "FADH" "FAF2" "FAK-Tyr" "FAK-mediated" "FAM150A-ALK" "FAM150A-HA" "FAM150A " "FAM150B-ALK" "FAM150B-HA" "FAM150B " "FAM150ba" "FAM150bb" "FANC-proficient" "FANCC-proficient" "FANCD2-siRNA-depleted" "FANCP" "FANCcore" "FAs" "FBOX5" "FBX011" "FCFP2" "FCFP4" "FCFP6" "FERM" "FERM-domain" "FEV1" "FEZF1" "FFBF" "FG-Sh-TAZ-1" "FGF-2and" "FGF2-dependentstimulation" "FGF2R" "FGF2Rα" "FGFR-3" "FGFs" "FHs" "FIB-4" "FIGO" "FISH" "FISH-negative" "FISH-positive" "FKB12-rapamycin-binding" "FLAG" "FLAG-LoxP-SNAP" "FLAG-SNAP-tag" "FLAG-SNAP-tagged" "FLAG-epitope-tagged" "FLAG-tag" "FLCN-1" "FLCN-dificient" "FLT3-ITD" "FLT3-ITD-D835Y" "FLT3-ITD-dependent" "FLT3-ITD-mediated" "FLT3-ITD-positive" "FLT3L" "FLuc-only" "FM" "FMCDs" "FMS-like" "FNIII" "FO" "FOPflash" "FOXA1-dependency" "FOXC-2" "FOXO" "FOXO1A3" "FOXO3-GFP-transfected" "FOXO3a-miR-622" "FPE" "FRB" "FSL-1" "FUCCI" "FVB-MMTV-ErbB2" "Fa-CI" "Fancd2" "Fancd2-single" "FaraAMP" "FaraATP" "Farnesyl-transferase" "Fatostain" "Fayyad-Kazan" "Fbxl5-mediated" "Fbxo1717" "Fbxw7" "Fbxw7α-SOX10" "Fbxw7αin" "Fbxw7β" "Fbxw7γ" "Fc" "Fc=1.08±0.02" "Fc=1.08±0.04" "Fcγ" "FcγR" "FcγRI" "FcγRII" "FcγRIIA131H" "FcγRIII" "FcγRIIIA" "FcγRIIIA158F" "FcγRIIIA158V" "FcγRIIIA " "FcγRs" "Fe" "Fe(II)-dependent" "Fenugreek" "Ferlay" "Fernandez" "Ferroportin" "Ferroportin-1" "Fichorova" "Fifty-seven" "Fifty-three" "Fig.S6C" "First-line" "Fission-deficient" "Flag" "Flag-Omomyc" "Flag-tag" "Flcn" "Flcn-null" "Flow-FISH" "Flow-cytometry" "Flow-cytometry-based" "Flt–3" "Fluc" "Fluorizoline" "Fm" "Fms-Like" "Fms-like" "Fogh" "Follow-up" "Formin" "Forty-eight" "Forty-five" "Forty-nine" "Forty-one" "Forty-seven" "Forty-six" "Forty-three" "Forty-two" "Fos-B" "Fos-L1" "Fos-L2" "Fosl1" "Foundation-7" "Four-two" "Foxa-dependent" "Fpm" "Fragile–X" "Fraumeni" "Freed-Pastor" "French" "Freud" "Freud1" "Fu" "Fus" "F‐actin" "F–K" "F–S6J" "G-765C" "G-899C" "G-LISA" "G-actin" "G-allele" "G-quadruplexes" "G-rich" "G-strand" "G-trap" "G0" "G0-G1" "G007-LK" "G1" "G1-G0" "G1-S" "G1-arrest" "G12C" "G13D" "G13R" "G1–S" "G2" "G2-M" "G2-and" "G302–G303–G304–G305" "G60–T75" "G6p" "GA" "GA+AA" "GA+GG" "GABA)–the" "GABP" "GADD45-α" "GADD45α" "GAR" "GAS5-plasmid" "GAS7A" "GAS7B" "GAS7C" "GAS9" "GBC" "GC-MS" "GC-boxes" "GCD-0941" "GCK733" "GCa" "GEC" "GECs" "GEF-GTPase" "GEF-mediated" "GFP-Atg8p" "GFP-CL1" "GFP-E-cadherin-expressing" "GFP-FLAG-USP4-FL" "GFP-cODC" "GFP-immunoprecipitates" "GFP-immunoprecipitation" "GFP-immunoprecipitations" "GFP-lentiviral" "GFP-only" "GFPHTT72Q" "GFP‐PH" "GG" "GG+GA" "GGGTTA-3" "GH-treatment" "GI50s" "GIST-like" "GIST_11" "GIST_124" "GIST_131" "GIST_150" "GIST_174" "GIST_178" "GIST_188" "GK733-induced" "GLE2p-binding" "GMB" "GMR-Gal4" "GNF2" "GNF4877" "GNF5" "GNF6324" "GNF7156" "GP900" "GPIZ-shDAB2IP" "GR-CDH1" "GR-null" "GR-siIGF1R" "GRCh37" "GRO-seq" "GSE12803" "GSE14520" "GSE2034" "GSE20712" "GSE22058" "GSE24-2" "GSE24.2" "GSE24.2-NLS1.3" "GSE24.2-NLS2.3" "GSE24759" "GSE26375" "GSE26511" "GSE30285" "GSE34184" "GSE37754" "GSE4-NLS1" "GSE4-NLS1-DA" "GSE41313" "GSE5846" "GSE61967" "GSE6919" "GSE71471" "GSK" "GSK3-by" "GSK3β-PS9" "GSK3β-S9" "GSK‐3–β" "GST-ARE-Luciferase" "GST-LC" "GST-R5BD" "GST-SC" "GST-chimeras" "GST-pull" "GT" "GTEx" "GVGD" "GWAS030" "Gain-of-function" "Gal" "Gal-3" "Gal-3C" "GalNAc" "Garicinol" "Gasther-1" "GeMDBJ" "Geiss-Friedlander" "Gel-Pro" "Geltrex" "GeneChip" "Genome-wide" "Genome–phenome" "Genotype-Tissue" "Genotype-phenotype" "Geoffroy" "German" "Germany" "Germline" "Ghahramani" "Giemsa" "Gleason" "Gli" "Gli-1" "Gli1" "Gln54Lysfs" "Gln66-Lys77" "Glu-rich" "Google" "Goosecoid" "Gori" "GppCp" "GppNp" "Gpxs" "Gr-1" "Granta" "Granta519" "Grb2" "Grb2-p85-TGF-RII" "Growth-arrest-specific" "Gu" "Guan" "Gy" "Gy-irradiated" "Gómez-Lechón" "GαS" "Gαs" "Gβ" "H&E" "H-L-H" "H-Ras" "H-RasY64A" "H-RasY64A·GTPγS" "H-RasY64A·GppNp" "H-Ras·GDP" "H-Ras·GTP" "H-Ras·GTPγS" "H-Score" "H-Scores" "H-bond" "H-bonds" "H-score" "H-scores" "H1" "H1-H1" "H1650ER" "H1975" "H1993" "H2-S3" "H2AK15" "H2DIDS" "H3" "H3-H4" "H3122CR1" "H3K18" "H3K18ac" "H3K27" "H3K36" "H3K56" "H3K56Ac" "H3K9" "H3K9Myr" "H3R2" "H3R8" "H4" "H4K16" "H4K16Ac" "H4K20" "H4R3" "H6" "H9-hESC-derived" "HA-1077" "HA-Huh7.5.1" "HA-NLS-PKM2" "HA-mock" "HA-tag" "HAHBD" "HAT + " "HA–Strep-Tactin" "HB-2" "HBPol" "HBe-Ag" "HBx-HCCR" "HBx-HCCR-E-cadherin" "HCC1195" "HCC1833" "HCE8693" "HCT116-DR5KO" "HCT116-KD2" "HCT116-KD3" "HCmel10" "HCmel3" "HCmel3-R" "HCmel3-R-2514" "HCmel3-R-2515" "HCmel3-R-3037" "HCmel3-Rs" "HD" "HD-DH-PH-Cat" "HDAC-4" "HDAC8–substrate" "HEL-R" "HEMa-LP" "HEMn" "HEMn-MP" "HEN-1" "HER" "HER2+-E-CSC" "HER2-equivocal" "HER2-negative" "HER2-normal" "HER2-positivity" "HER2-targeting" "HER2e" "HERPUD2" "HESCs" "HFD-induced" "HFF" "HFKs" "HGF-induced" "HIAP" "HIF1a-AS1" "HIF1α-AS1" "HK" "HK‐2" "HL-7702" "HLA-B8-DR3" "HLECs" "HME" "HMG-CoA-reductase" "HMLE" "HMN-176" "HMN-214" "HMR-1275" "HN" "HOMA-IR" "HOSE" "HOXB13-dependency" "HPMVECs" "HPRC" "HPRT" "HPV-1" "HPV-5" "HPV-8" "HPV16-E6" "HR-PFS" "HR2" "HR=0.002" "HR=0.42" "HRCT" "HRE-1" "HRE-2" "HRMECs" "HRMGs" "HSC–70" "HSP-70" "HSP1AL" "HSP2cTg" "HSP70-1" "HSP70-2" "HSP90-Src-mediated" "HSP90α" "HSPA1-Lys561" "HSPB2NTg" "HSPB2cKO" "HSPB2cTg" "HSPB2wt" "HSQC" "HT29-KD6" "HT29-lucD6" "HT29-lucD6-COX2" "HT29-lucD6-EV" "HT3-E6" "HTB-177" "HULC-107-mut" "HaloPlex" "Han" "Hans" "Hardy-Weinberg" "Hardy–Weinberg" "HeCOG" "HeH-C57BL" "Hedgehog-GLI1" "Heilongjiang" "Hela" "HemECs" "HemSC" "HemSCs" "Henan" "Henríquez-Hernández" "Hep3B-ERα" "Hep3B-miR-214" "HepG2-shERα" "HepJ5" "Her2" "Her2-enriched" "Her2-negative" "Her2-positive" "Her2Neu" "Hergovich" "Heteroduplex" "Hi-Q" "Hickey" "High-level" "Hippo" "Hippo-ERBB" "Hippo-YAP" "Hippo-independent" "His-PDK1" "His-USP7" "His-p300" "His2240Leufs*4" "His2261Leufs" "Hispanic" "Histone2AX" "Histopathology" "Hodgkin" "Hoechst" "Holm–Sidak's" "Honda" "Hong" "Honoraria" "HphI" "Hsa-miR-628-3p" "Hsa-miR29a" "Hsa-miRNA-139-5p" "Hsp90α" "HspB10" "HuH" "HuH-7R" "Huang" "Human-1" "Hwang" "HyperCVAD" "Hz" "Hε" "I-II" "I-III" "I-IV" "I1018F" "I157T" "I2" "I83-E95" "IAPH" "IASLC" "IC-50" "IC50" "IC50s" "IC50s=10-15" "ICI-118,551" "IDH-1" "IDs" "IEF" "IFU" "IG20" "IGF1-treatment" "IGF1R-beta" "IGH" "IHC-negative" "IHC3+" "IHC 3+" "II-1" "II-2" "II-3" "II-4" "II-5" "II-7" "II-III" "II-IV" "IIA" "III-1" "III-2" "III-7" "III-IV" "IIIA" "IIIB" "IIIB-IV" "IIIC" "IIIa" "IIb" "IIb-IIIa" "II–III" "II–IV" "IKBα" "IL-1F6" "IL-1F8" "IL-1F9" "IL-1RAcP" "IL-1βwere" "IL-22RA1" "IL-36" "IL-36-mediated" "IL-36α" "IL-36β" "IL-36γ" "IL-36γsecretion" "IL-6-STAT3-miR-24" "IL-6Rα" "IL-6–or" "IL20R" "IL20R2" "IL213" "IL218" "IL22R1" "IL2RG-SGM3" "ILP2" "ILs" "IM-MS" "INA" "INTRA-TUMOR" "IQ" "IRC-083864" "IRE-protein" "IRES-like" "IRESs" "IRP1-IRE" "IRS-1–PI3-K–PDK1" "ISCU1" "ISH-negative" "ISH-positive" "ISVs" "ITAF" "ITAF-like" "ITAFs" "ITC" "ITG4A" "ITGA10-11" "ITGA2-4" "ITGAVB3" "IVIS-SPECTRUM" "IVS" "IVS14" "IVS14 " "IVS2+1G" "IWR-1" "IWR-1significantly" "Identifier" "Ig" "IgA" "IgG-like" "IgG1" "Iliopoulos" "Illumina" "Imaris" "Imidazole" "Immunochemistry" "Immunohistochemistry" "Importin" "In-cell" "Inc" "Index" "Infinium" "Int" "Inter-group" "Inter-individual" "Inter-observer" "Inter-study" "Invitrogen" "Ion-Mobility" "Iκ-Bα" "IκB-bound" "IκBKγ" "I–III" "I–IV" "J-aggregates" "JAK-STAT3-VEGF" "JAK1-3" "JAK2-V617F" "JAK2-V617F-Y931C" "JAK2-V617F-addicted" "JAK2-V617F-dependent" "JAK2-V617F-driven" "JAK2-V617F-induced" "JAK2-V617F-mediated" "JAK2-V617F-positive" "JAK2-V617F-transformed" "JAM-L" "JARID1" "JEC" "JEKO" "JEKO-1-R" "JEKO-1R" "JEKO1" "JEKO1-R" "JFH1-infected" "JGCA" "JH1" "JJC" "JKY" "JKY-2-169" "JQ1" "JVM-13" "Jagged-1" "Japanese" "Jaspla" "Jeb" "Jeb-like" "Jeb " "Jed4" "Jeff" "Jeko1" "Jemal" "Jewish" "Jf" "Jiang" "Joerger" "Junbo" "Jurkat-HA-FOXP3" "Jurkat-shTCERG1" "Justin" "K-RasG12V" "K-RasG12V·GTPγS" "K-Ras·GTPγS" "K-fibre" "K-fibre-stabilising" "K-fibres" "K-rat" "K11" "K16" "K18" "K202–S276" "K3326X" "K34c" "K381A" "K45" "K45R" "K54" "K54R" "K56" "K63" "K63-only" "K632S5" "K9" "KAT5-dependence" "KAT5i" "KD2" "KD3" "KD6" "KDM4" "KDM5" "KEGG" "KG" "KMTs" "KN-92" "KNS-62" "KO-AA" "KO-DD" "KPC" "KPS" "KR" "KRAS-12" "KRAS-G12G12C" "KRAS-G13D" "KRAS-LCS" "KRAS-LCS6" "KRAS-driven" "KRAS-non-cancer" "KT-MT" "KT–MT" "Kaiser" "Kanai" "Kandioler" "Kang" "Kaplan" "Kaplan-Meier" "Kaplan–Meier" "Kaposi" "Kappel" "Kd" "Keap1" "Keap1-Cul3E3" "Keap1-sulfenic" "Keap1–Cys" "Kelch-interactors" "Kelch-like" "Kelch‐like" "KeratinoSens" "Keratinosens" "Ki-67" "Ki-67-positive" "Ki-67–positive" "Ki67" "Ki8751" "Killer" "Kim" "Kip" "Kirsten" "Kit-8" "Knock-down" "Knocking-down" "Korean" "Korkaya" "Koulich" "Kruppel-like" "Kruskal-Wallis" "Kruskal–Wallis" "Krüppel-like" "Ku" "Ku80-defective" "Kudlow" "K‐Ras" "K‐Ras‐mediated" "L-Ala-Gln" "L-Gln" "L-Myc" "L-OHP" "L-OPA1" "L-alanyl-glutamine" "L-isoapartyl" "L-isoaspartate" "L-type" "L1" "L2" "L4" "L52R" "L7" "L858R" "L983F" "LACE" "LACE-Bio" "LADCs" "LAMTOR-2" "LC-3II" "LC3-I" "LC3B-I" "LC3B-II" "LC3I" "LC3II" "LCLs" "LCM-RPPA" "LCMT1" "LDHb" "LDL-cholesterol" "LEF" "LEOPARD" "LETM1" "LETMD1" "LEV" "LFS" "LHSAR" "LHSAR+FOXA1+HOXB13" "LIM" "LINC00273" "LINE‐1" "LISA" "LKB1-depicient" "LLL12" "LMP1transcription" "LMP2A" "LN299" "LNCaP" "LNCaP-7B7" "LO" "LOC100506688" "LOH" "LOVD" "LOX-5" "LPC-Mig" "LPHN2" "LPS" "LR-hTERT" "LRRFS" "LS-102" "LTR" "LTT" "LUMIER" "LUMinescence-based" "LV-cofilin-shRNA" "LV-control-siRNA" "LV-shRNA" "LXRα" "LY293111" "LY3023414" "LY6161" "Lallemand-Breitenbach" "Lambert" "Laminin" "Lamp1-mCherry" "Lane1-2" "Lange" "Langerhans" "Lap" "Lap#12" "Lap#6" "Lap#6-CM" "Large-scale" "Latin" "Latin-America" "Lauren" "Le" "Lef1" "Leica" "Leu132-Cys133-Arg134" "Leu→Leu" "Lhermitte-Duclos" "Li" "Li-Fraumeni" "Li-Fraumeni-like" "Lifepool" "Lineweaver–Burk" "Liu" "Liu-Chittenden" "LncRNA-GAS5" "LoD" "Loewe" "Log-rank" "Lombardo" "Long-Evans" "Lou" "Lov" "Low-complexity" "Low-dose" "Low-frequency" "Low-level" "LoxP" "LoxP-sites" "LtSz-scid" "Lu" "LuCaP35" "Luc" "Luc-GFP" "Luc-MET-3" "Luc-P1" "Luc-P1-MT" "Luc-P1-WT" "Luminal-A" "Luminal-B" "Luminex" "Lv-cofilin1-shRNA" "Lv-control-shRNA" "Lymph-node" "Lynparza" "Lys-11" "Lys-27" "Lys-29" "Lys-33" "Lys-48" "Lys-561" "Lys-63" "Lys120" "Lys3326Ter" "Lys376Glu" "Lys54Argfs" "Lys561-containing" "M+7" "M-CSC" "M-CSC-like" "M-CSCs" "M-H" "M-MSP" "M-states" "M0-2" "M15" "M15A" "M1L" "M2L" "M6" "MAD-MB-231" "MADE1" "MAGE-B18-LNX1" "MALDI-TOF" "MALDI-TOF-MS" "MAP1S-deficiency-triggered" "MAP1Smediated" "MAP1Sregulated" "MAP1Sspecific" "MAP1b-LC" "MARCKSknockdown" "MARCKS‐GFP" "MARK" "MAVER1" "MBA-MB-231" "MCAO" "MCC-32" "MCE-7" "MCF10a-normal" "MCF7shp53" "MCF7vector" "MCF‐7" "MCP-TERT-labeling" "MCS4" "MDA-MB-23" "MDA-MB-231cells" "MDA-MB231-pLKO1" "MDA-MB231-shBLT1" "MDA-MBN-231cells" "MDA-MD-453" "MDA_MB231" "MDA‐MB‐231" "MDA‐MB‐231cells" "MDM2-C" "MDV-R" "ME180-MXIV" "ME180-shYAP" "MEAF6-SEPSEC" "MED8A" "MEK-ERK" "MESACUP" "MESENCHYMAL" "MET-related" "MET4" "MFS" "MHH" "MHH-ES-1" "MHz" "MI192" "MI192 " "MICoA" "MIGR" "MIM1" "MIP-1-α" "MIP-1â" "MIP-1αand" "MIP-DILI" "MJ-56" "ML141" "ML323" "MLH6" "MLL-AF9-expressing" "MM-15" "MM-74" "MM15" "MM27" "MM54a" "MM65" "MM85" "MMTV" "MMTV-ErbB2" "MMTV-PyMT" "MNA" "MOIs" "MPM-p3" "MPN-like" "MPS" "MPs" "MR" "MREs" "MS" "MS-PCR" "MSC4" "MSC7" "MSI-H" "MST2-promoted" "MTF16" "MTMR8" "MTases" "MU" "MUT1" "MUT2" "MUT3" "MV4-11cells" "MVID-like" "MVP1" "MXD" "MYCBNP2" "MYO3B" "MZ" "MZ7" "MZB1" "Ma-Mel-102" "Ma-Mel-15" "Ma-Mel-27" "Ma-Mel-48" "Ma-Mel-54a" "Ma-Mel-85" "Mad-homology-1" "Mad-homology-2" "Madin-Darby" "Magainin1" "Mal" "Malaysia" "MammaPrint" "Mannheim" "Mantel-Cox" "Marburg" "Mark53" "Marshall" "Masson" "Material" "Matic" "Matsushima-Nishiu" "Maxi" "Maxi-EBV" "May-Grünwald" "May-Grünwald-Giemsa" "Mayo" "McLaughlin" "Mediator" "Medici" "Meier" "Mel-RM" "Meleda" "Melnikow" "Merck" "Merkel" "Meso-Scale-Discovery" "Meta-regression" "Methods" "Methyl-Met" "Methyl-Profiler" "Mexican" "Mexicans" "Mexico" "Mi2" "MiR-101" "MiR-103" "MiR-141-3p" "MiR-18a" "MiR-208b" "MiR-22" "MiR-22-deficient" "MiR-33a" "MiR-484" "MiR-494" "MiaPaca‐2" "Michael" "Michaelis-Menten" "Micro-CT" "MicroRNA-7" "Microfilaments" "Mild-inflammatory" "Millipore" "Mir-548" "Mir22" "Mir22hg" "Mira-900" "MitoTracker" "Mn" "MoDCs" "Moderate" "Monocyte-derived" "Moog-Lutz" "Mooney" "Morgillo" "Mourtada-Maarabouni" "Mukhopadhyay" "Multidomain" "Munc18-2–dependent" "Munc18-like" "Muranen" "Mut" "Mut865" "MutIL6R-2" "MutSTAT3" "Mutationtaster2" "Mutect" "Mv1Lu-pcDNA3cells" "Myc-Max-DNA" "Myc-RhoA-Q63L" "Myc-Skp2" "Myo5B-GTD" "Myo5B-LC" "MyoII-mediated" "Myosin" "Myr-Akt" "Mø" "MβCD" "M–O" "N-ARBS" "N-HSQC" "N-LMP1" "N-RAS-G12V" "N-SH2" "N-acetyl" "N-acetylgalactosamine-specific" "N-acetylglucosaminyl-transferases" "N-domain" "N-glycosidase" "N-glycosylated" "N-labeled" "N-methyl-nitrosourea-treated" "N-methylate" "N-methylation" "N0" "N1" "N1+N2" "N1-O" "N1-guanine-N3-cytosine" "N1a" "N1b" "N2" "N375" "N400" "N9" "N981I" "NA" "NAAIRS" "NADPH" "NALM-19" "NAMDR2B" "NB-4" "NC-miR" "NCCIT-R" "NCCTG" "NCI" "NCI-60" "NCI-H1819" "NCI-H1915" "NCT" "NCT00258245" "NCT00525200" "NCT00755885" "NCT01244191" "NCT01431209" "NCT01456325" "NCT01514266" "NCT01740323" "NCT01795768" "NCT01858168" "NCT01889238" "NCT01905592" "NCT01945775" "NCT01967095" "NCT01974765" "NCT01990209" "NCT02000375" "NCT02000622" "NCT02044120" "NCT02091960" "NCT02116777" "NCT02140723" "NCT02144051" "NCT02157792" "NCT02163694" "NCT02215096" "NCT02223923" "NCT02264678" "NCT02296203" "NCT02316496" "NCT02348281" "NCT02370706" "NCT02407054" "NCU" "NCX4040" "NCsi" "NEXT-2" "NF-κB-mediated" "NF-κB1" "NF-κBα" "NF1-associated" "NGR-A2" "NGS-wild-type" "NH" "NHDFs" "NH " "NI" "NK-kB" "NK-κB" "NKIRAS1" "NKT-like" "NKTCL" "NLS2" "NLST" "NMS-P937" "NMSCs" "NOD-SCID" "NOD-like" "NOD–SCID" "NON" "NOX-ROS-EGFR-PI3K-ERK1" "NOX-derived" "NQO" "NR" "NRF2-triggerd" "NRG1-null" "NRG1–ErbB2–ErbB3" "NS-ML" "NS-like" "NSAID" "NSC-95397" "NT-proBNP" "NTERA-2R" "NU1025" "NVP-AUY922-AG" "Nagel" "Najafi-Shoushtari" "Nakagawa" "Nano" "Nano-LC" "Nedd4" "Neh" "Neh3–5" "Neh4" "Neh5" "Neh6" "Neh7" "Nelson" "Neo" "Nestin" "Netherlands" "Neural-Wiskott" "Next-Generation-Sequencing" "Next-generation" "Nfe2I2" "Nhe4–5" "Ninety-three" "Ninety‐eight" "Nkx2" "Noonan" "Normal-AR" "North-Central" "Norton" "Norton-Simon" "Notch" "Notch-mediated" "Nox-driven" "Nrf" "Nrf2-100" "Nrf2-100-FLuc2" "Nrf2-100-Fluc" "Nrf2-100-Fluc2" "Nrf2-100-Luc2" "Nrf2-100-Luciferase" "Nrf2-ARE" "Nrf2-FLuc2" "Nrf2-activator" "Nrf2-activators" "Nrf2-oxidative" "Nrf2-regulatory" "Nrf2-response" "Nrf2‐mediated" "Nrf2‐regulated" "Nrf2–ARE" "Nrf‐2" "Nu" "NuRD" "Numb" "Numbl" "Nutlinpre-treatment" "Nutullin-3" "Nε" "O-linked" "O-methyl" "O-methylate" "O-methylating" "O-methylation" "O-purification" "O-purified" "O6-BG" "O6-MeG" "O6-alkylguanine" "O6-methlyguanine-DNA-methyltransferase" "O6-methylguanine" "O6-methylguanine-DNA" "O6-position" "O6BG" "OAP" "OB" "OB-fold" "OC" "OCI-LY18" "OCUM‐2M" "OD490" "OGDDs" "OHTAM" "OKD48-Luc" "OLAR5" "OMIM" "OMIM2483000" "ON018910" "ON01910" "ONNO" "ONO12380" "ONYX-015" "OP449" "OPA1-ΔS1" "OPB-31121" "OPB-51602" "OPCs" "OR=0.73" "OR=0.79" "OR=0.84" "OR=0.93" "OR=0.94" "OR=0.97–1.09" "OR=1.05" "OR=1.06" "OR=1.08" "OR=1.18" "OR=1.20" "OR=1.21" "OR=1.26" "OR=1.45" "OR=2.02" "OR = 0.93" "OR = 0.94" "OSBPL3" "OSEC2" "OX" "OX-refractory" "Ohba" "Olfr1508" "Olfr68" "Oligonucleotide" "OmniExpressExome-8v1" "On-TARGETplus" "Onco" "Oncodrivers" "Oncology" "Oncomine" "One-hundred" "One-third" "Ortiz-Zapater" "OspB-mTORC1" "OspC3" "OspE" "OspF" "Overholtzer" "Ozcan" "Oε2" "P1" "P1-3" "P24" "P24L" "P26" "P26–114,113" "P28–12,591" "P2X" "P2Y" "P58" "P58A" "P6.1" "P7" "P72" "P72R" "P91" "P91L" "P91L–Y306F" "P943_946" "P9–13" "P=0.002" "P=0.003" "P=0.01" "PAM50" "PAM50-based" "PANC-1" "PANERB" "PANTHER" "PARP-DNA" "PARP1-DNA" "PARP5a" "PARP9" "PARPi" "PARylation-dependent" "PB-Cre" "PBD-phosphopeptide" "PBIP1-p-T78" "PBX-family" "PBXIP1" "PCDHGA11" "PCR-Sanger" "PCs" "PCs " "PD-20corr" "PD20" "PD20KR" "PD331" "PD980589" "PDBj" "PDGFRα-mutant" "PDGF‐induced" "PDI-like" "PDK-1binding" "PE-B-1" "PEC" "PECs" "PET-CT" "PF-004777736" "PF-04691502" "PF-0477736" "PFGE" "PFT-α" "PFT-μ" "PG" "PGE2-mediated" "PGL" "PHA-680626" "PHA-II" "PHA666762" "PHT-427" "PI3K-AKT1" "PI3K-CA" "PI3K-like" "PI3KC2G" "PI3KC3" "PI3KCA" "PI45P2" "PIK3CA-E545G" "PIK3CA-E545K" "PIK3CA1-mutant" "PIK3CAhel" "PIK3CAkin" "PIK3CAmut" "PIK3CAwt" "PIK3KCA" "PIKKs" "PIM1L" "PIM1S" "PIMs" "PITA" "PK45-p" "PK59" "PKCβII" "PKH67" "PKM1" "PKM2-NLS" "PKM2-NLS-mutant" "PLC‐δ" "PLHS-Pmab" "PLHSpT" "PLHSpT-Pmab" "PLK-1to" "PLK-1with" "PLK-2" "PLK-4" "PLK-5" "PLK1-R136G" "PLK1-R136G&T210D" "PMK-1" "PMN-like" "POH1-E2F1" "POH1–E2F1" "POOREST" "PP2A-mediated" "PP2A–c-Myc–dependent" "PP2A–mediated" "PPAR-α" "PPAR-β" "PPAR-δ" "PPAR-δ-dependent" "PPAR-δ-specific" "PR-619" "PR-negative" "PRKKA1" "PRMT5-MEP50-containing" "PRMT5-Methylosome" "PRMTs" "PROGNOSTIC-PREDICTIVE" "PROMO" "PROVEAN" "PTCLnos" "PTD-A2" "PTD-A2–injected" "PTD-A2–treated" "PTTG-shRNA1" "PTTG-shRNA2" "PTs" "PV" "PXBIP1" "PaC" "PaTu899S" "PacMetUT1" "Pair-wise" "Pam2CGDPKHPKSF" "Pan-CDK" "Pan-Cancer" "Panc‐1" "Par3-Par6-aPKC" "Parkinson" "Partition-defective" "Pax7" "Pax7-Cre" "Pax7CT2" "Pax7nGFP" "Pc " "Peak-like" "Pearson" "Periodic-Acid-Schiff" "Petitjean" "Pfizer" "Pgd" "Pgp" "Pgp-1" "Ph-treatment" "Philadelphia" "Phosphoinositide-3" "Phospho‐MARCKS" "Physcion-6PGD" "Physcion-treated" "Pi-Pi" "Pillai" "Pin1-CPEB1" "Pit-Oct-Unc" "Plumbaginaceae" "Pluripotency-associated" "Pmab" "Pogue-Geile" "Poisson" "Pol" "Pol1" "PolII" "Polo-Like" "Polo-box" "Poloboxtide" "Poloxipan" "Poly-L-Ornithine" "PolyPhen" "PolyPhen-2" "PolyPhen2" "Polymerase1" "Polyphen2" "Post-UVB" "Post-operative" "Post-transcriptional" "Post-translational" "Postmenopausal-levels" "Ppant" "Prestwick" "Pro+Arg" "Pro-inflammatory" "Pro1180fs" "ProA-FLAG-tag" "Prohibitins" "Proline-Rich" "Promonin-1" "Protein" "Protein-RNA" "Pseudo-hypoxic" "Pthα" "Puerto" "Pull-down" "Puquitinib" "PvuII" "Pérez-Vallés" "Q-FISH" "Q-MSP" "Q382A" "Q546L" "Q61R" "QGY-7703-miR-214" "QW" "R-5-P" "R-CHOP" "R-CHOP-treated" "R-Hyper" "R-MA" "R-based" "R-enantiomer" "R-enantiomer-selective" "R-enantiomers" "R-etodolac" "R-forms" "R-ketorolac" "R-naproxen" "R0" "R1" "R156A" "R156A-mutant" "R1905" "R1–R4" "R2" "R23X" "R251X" "R299Q" "R3" "R385A" "R4" "R5" "R579X" "R5BD" "R653-Q855" "R7T1" "RANK-ligand" "RASSF1-1α" "RASSF1C" "RASSF7–10" "RASSF8" "RASSF8-RNAi" "RASSF8-RNAi–transduced" "RASSSF1A" "RAS‐GAP" "RB05" "RB45" "RESISTANCE" "RFP‐PH" "RFP‐tagged" "RFTN1" "RGLs" "RH-SENP3" "RHT1" "RHT2" "RHZ" "RIGER" "RII" "RIP-DTA" "RMH" "RMS-1" "RNA" "RNA-130a" "RNA-PolII" "RNA-SIRT1" "RNA-like" "RNA-protein" "RNA22" "RNAP" "RNAhybrid" "RNAseq" "RNA–RNA" "RNU48" "RNV" "RNaseP" "RO3280" "ROCK-actin" "ROCK-to-MLCK" "ROCK1-co-transfected" "ROCK1-to-MLCK" "ROCK2-to-MLCK" "ROS-generation-inducing" "RPI-Pred" "RPI-prediction" "RPISeq" "RPISeq-RF" "RPISeq-SMV" "RPISeq-SVM" "RPMI" "RPMI-1640" "RPRR-X" "RPRRX-S" "RRL-F" "RRL-O" "RRx" "RRx-001" "RS4-11" "RTA-408" "RTK" "RTK-ligand" "RTOG" "RT‐PCR" "RUNX1-RUNX1T1" "RUNX1T1" "RUV" "RVVFLEPLKD" "Rab5-CA" "Rab5-DN" "Rab5-GTP" "Rab5S34N" "RabGGTA" "Rac1" "Rac1‐GTP" "Rad3" "Rad3-related" "Radix" "Raf-MEK-ERK-mediated" "Raf1-driven" "Rahman" "Raimondi" "Rap-plus-Spa" "Ras-Sos" "Ras-homologous" "Ras-like" "Ras2p" "RasY64A" "RasY64A·GTPγS" "Ras·GDP" "Ras·GTP" "Ras·GTPγS" "Rat‐specific" "Rb" "Rb-null" "Rbx1-Cullin1-Skp1-F-box" "Rbx1-mediated" "Re-analysis" "Re-evaluation" "Re-expression" "Re-growth" "Real-Time-PCR" "Reduction-oxidation" "Renilla" "Ret" "Rett" "Revacept" "Reverse-phase" "Rhex-1" "Rho-family" "RhoA-GTP" "Rhod" "Rhod2" "Ribeiro" "Ribo-seq" "Rican" "Rictor-KO" "Riesenberg" "Rluc" "Rossmann" "Rossmann-fold" "Roux" "Ru-5-P" "Ru-5-P-dependent" "RxRxxS" "Rxr" "Rxrα" "RxxS" "S-1" "S-H" "S-adenosyl" "S-checkpoint" "S-enantiomer" "S-enantiomers" "S-forms" "S-ibuprofen" "S-ketorolac" "S-methionine" "S-naproxen" "S-phase-expressed1" "S-transferases" "S1" "S1-treated" "S127" "S143A" "S143D" "S143E" "S16" "S16-STMN1" "S1981" "S1981-ATM" "S1C" "S1D" "S1E" "S1G" "S1H" "S2215F" "S245" "S25" "S291fs" "S2B" "S2C" "S2D" "S2E" "S2a–c" "S3" "S3-6PGD" "S3-A" "S3-B" "S3-resistance" "S307D" "S317" "S345" "S38" "S38-phospho-STMN1" "S386A" "S3B" "S3C" "S3D" "S3E" "S3F" "S3G" "S3H" "S3I" "S4" "S4-B" "S432A" "S432D" "S432E" "S4A" "S4B" "S4C" "S4D" "S4G" "S4S" "S4S8p" "S5C" "S5D" "S5E" "S5G" "S5H" "S6" "S63" "S6A" "S6B" "S6C" "S6G" "S6RP" "S7" "S7A" "S7C" "S8" "S8-A" "S8-B" "S8-C" "S8b" "S9" "S9-S10" "S9A" "S9B" "S9d" "S9–S10" "SA-β-Gal-positive" "SAβGal" "SBE13" "SBI-0061739" "SBI-0069272" "SBI-061739" "SBI-0640599" "SBI-0640601" "SCCOHT-1" "SCG10-like" "SCS" "SCV000255937" "SCV000255938" "SCV000255939" "SCV000255940" "SCV000255941" "SCaBER" "SCs" "SD4" "SDH-intact" "SDHA-D" "SDHX" "SDK2" "SDX-301" "SDX-308" "SENP" "SENPs" "SEPTIN11" "SERDs" "SET-FUCRW" "SET-PEB-1" "SET-PP2Ac" "SET-RW" "SET-immunoprecipitant" "SET2-R" "SFRS15" "SGKs" "SH-groups" "SH10" "SH2-pseudokinase" "SHH-medulloblastoma" "SHR-C" "SHR-H" "SHR-L" "SILEC10" "SIRT" "SISH" "SK-Mel-37" "SK-N-BE2" "SK-N-DZ" "SK6" "SKA2-luc" "SKH-I" "SLC16A14" "SLFN" "SLFN11" "SLFNs" "SLURP-1" "SLURP1" "SMiNS-like" "SMiNSc-like" "SN12PM6" "SNAP-tag" "SNF2-family" "SNORD12" "SNORD12b" "SNORD12c" "SNP-array" "SNP-arrays" "SNP6.0" "SNPase-ARMS" "SNPs" "SNU-2535" "SNV" "SNVs" "SNX-7018" "SNX-7081" "SNX-7081+2-FaraA" "SNX-7081-induced" "SNX-7081-mediated" "SNX-7081-treated" "SOX" "SOX2-MYC-directly" "SPIN4" "SPS1-related" "SPSS" "SR" "SRC-NFKB" "SRCC" "SRCCs" "SRD" "SRD-13A" "SRE" "SRE2" "SREBP-mediated" "SRM-MS" "SRM-MS-negative" "SRM-MS-positive" "SSPNN" "STA-7346" "STA7346" "STAG–RAD21" "STAT" "STAT3-mediated" "STAT3-null" "STAT3WT" "STAU" "STIMA-1" "STMN-like" "STMN1-S38-phosphorylation" "STS-2" "STUbL" "STUbLs" "SUN-387" "SUPB-15" "SUV39" "SV40-driven" "SVM" "SW-1353" "SW-1990" "SW-480" "SW-620" "SW-837" "SW156" "SW480-D2" "SW480-D2-scram" "SW480-D2-scramble" "SW480-D2-si-IκB" "SW480-D2-si-IκB-α" "SW480-D4" "SW480-con" "SW480-con-scramble" "SW480ADH" "SWISS-MODEL" "SWissDock" "SXL4" "SYF-c-Src-TrkB" "SYF-cSrc-TrkB" "SZ" "SZ-4" "Sahiwals" "Saliva-Based" "Salvesen" "Sanchez-Tillo" "Sanger" "Santini" "Sarcomatoid" "Sato" "Saudi" "Sc-1" "Schiff" "Schimmel" "Schlafen" "Scorpion" "Sec1" "Self-renewal" "Semi-quantification" "Sen" "Ser-4" "Ser-473" "Ser-8" "Ser10" "Ser1139ArgfsX16" "Ser19-CHK2" "Ser1981" "Ser21" "Ser235" "Ser240" "Ser307" "Ser33" "Ser33,37" "Ser4" "Ser432-specific" "Ser5" "Ser67-Arg69" "Ser8-phosphorylated" "Ser9" "Sevenless" "Seventy-seven" "Seventy-two" "Seventy‐nine" "Sh" "Sh-TAZ-1" "ShMOLLI" "Shanxi" "Shen" "Short-term" "SiIGF1R" "SiNS-like" "SiNSc-like" "Sica" "Sichuan" "SinceUHRF1over‐expression" "Single-molecule" "Single-nucleotide" "Sirius" "Sirtuin-7" "Site-II" "Sixty-eight" "Sixty-nine" "Sixty-six" "Sixty-three" "Sixty-two" "Skp1" "Skp1-Cul1-F-box" "Skp1-Cullin1-F" "Skp1-Cullin1-Rbx1-F" "Skp1–6-OAP" "Skp2‐mediated" "Skrzypczak" "Slc25a3" "Sloan" "Slp4a–Stx3" "Slpa4" "Smad-E2F" "Smad3" "Smad3-phosphoisoforms" "Small-Cell" "Small-interfering" "Snail" "Snap23a" "Snijders" "Society" "Sodium-chloride" "Solid-Phase" "Sp1" "Sp1-1" "Sp1-3" "Spanish" "Spearman" "Spengler" "Squalene" "Src" "Src-PY418" "Src-dependent" "Src-family" "Src-mediated" "Src-signaling" "Sriramachandran" "Stat" "Stat1" "Stathmin" "Stathmin-1" "Stathmin-2" "Strep" "Strep-Tactin" "Structure-based" "Sts-1" "Sts-1-CBL" "Sts-2" "Student-Newman" "Stx3_1-247" "Stx3–Munc18-2" "Sub-G1" "Sudol" "Suit‐2" "Sv" "Swiss" "Switch" "Switzerland" "SykPTK" "Syns-driven" "S‐phase" "T+8473C" "T+C" "T-AOC" "T-ARBS" "T-C-C-C" "T-C-T-C" "T-DM1" "T-LGL" "T-PLL" "T-Rex-HEK293T" "T-T-T-C" "T-allele" "T-circle" "T-circles" "T-complex" "T-helper" "T-lymphoid" "T-precursor-stage" "T0" "T1" "T1+T2" "T1-relaxation" "T145A" "T1989" "T1c" "T2-relaxation" "T202" "T210-loop" "T3" "T3+T4" "T306" "T306D" "T3–T4" "T4" "T7-Hsc70" "T7-tagged" "T790M-EGFR" "TAE-684" "TAK-960" "TAK-960-mediated" "TAK-960-treated" "TAT-A2" "TATA" "TATA-less" "TBB" "TBC1D30" "TBX-YAP" "TC+CC" "TCER-1" "TCS2" "TD19" "TEA" "TEFb" "TEN-domain-truncated" "TERT-hTR" "TERT-∆PAL" "TF556PS" "TFIIH-repair" "TGE" "TGF-R" "TGF-RI" "TGF-RII" "TGF-RIII" "TGFβRII" "TKD" "TKI-resistance" "TKM-080301" "TL4" "TM" "TM251" "TMA-1005" "TMEM51" "TN" "TNBCs" "TNF-1α" "TNF-β" "TNSK2" "TOP" "TOP-like" "TOP2A-expressor" "TOPflash" "TORopathies" "TPA-induced" "TPF" "TPF-regents" "TRAF2-mediated" "TRAP-C1" "TRF-1" "TROSY" "TRUB" "TS-1" "TSG-motif" "TSKN2" "TSNs" "TSVC" "TT+TC" "TTAGGG-3" "TTAGGGs" "TULA-2" "TURP" "TVC" "TWIST1" "TX" "TXNR1" "TXNRD3" "Tactin" "Taihang" "Taiwanese" "Taken" "Talalay" "Tango6" "Tanimoto" "Tankyrase-2" "TaqMan" "TaqMeth" "TargetScan" "Tatham" "Tattoli" "Tc22" "Tcf" "Tcf-regulated" "Telomerase-mediated" "Temozolomide" "Temporal-spatial" "Tet-Off" "Tet-On" "Tet-off" "Tetra-primer-ARMS" "Texas" "Tg" "Th17" "Th2" "Th2-cyotkine" "Th2-effector" "Th22" "ThPOK" "Theileria" "Thirty-eight" "Thirty-five" "Thirty-four" "Thirty-three" "Thr-37" "Thr-46" "Thr-kinase" "Thr14" "Thr202" "Thr21-RPA32" "Thr306" "Thr308" "Thr4" "Thr41" "Three-dimensional" "Thy1" "Thy1.1" "Thy1.1-DP" "Thy1.1-double" "Time-lapse" "Tissue-specificity" "Toll-like" "Topo" "Topo-1" "Toremifene" "Tox" "Tra-1-60" "Tra-1-81" "Trans-Lentiviral" "Transwell" "Treg-like" "Trevigen" "Tricin" "Trigonella" "TrkB-shRNAs" "Troponin-I" "TrxR1-null" "Tumor-suppressive" "Tweenty-one" "Twenty-five" "Twenty-four" "Twenty-four-hour" "Twenty-one" "Twenty-one-week" "Twenty-seven" "Twenty-six" "Twenty-three" "Twenty‐eight" "Twist-AP1" "Two-hundred" "Ty" "Tyr1007" "Tyr15" "Tyr204" "Tyr705" "U-138MG" "U-2973" "U-MSP" "U-rich" "U0216" "U251" "U2O2" "U3" "U343" "U4" "U6" "U75302" "UBASH3B" "UBL2" "UCSC" "UCSF" "UDP-glucuronosyl" "UFB" "UFBs" "UHFR1" "UHRF1depletion" "UHRF1expression" "UHRF1over‐expression" "UHRF1suppression" "UHRF1‐mediated" "UHRF1‐positive" "UICC" "UICC-TNM" "UK" "UMSCC23" "UNC-51-like" "UPS7-dependent" "US" "USA" "USP-Family" "USP-family" "USP13si" "USP35" "USP3si" "USP7-depenedent" "UTR-G" "UTRs" "UUAUUUAUU" "UV-light" "UV5" "Ub-AMC" "Ub-FANCD2" "Ub-FANCI" "Ub-K63R" "Ub-aldehyde" "Ubal" "Ubiquitin‐like" "Ubp6" "Uke1-R" "Ulrich" "Umapathy" "Uni-and" "Urso" "Usp1-Uaf-1" "Usp12" "V-C8" "V-E5" "V1" "V2" "V2.0" "V3" "V3-YAC" "V3.0" "V341fs" "V5-tagged" "V5–ALK" "V600E–mutant" "VAPAHCS" "VDAs" "VE-821-sensitivity" "VE1" "VE821" "VEGF-1" "VEGF-R" "VIL1" "VNN2" "VP24" "VPS13B" "Val1951" "VarScan" "VarioWatch" "Vazquez-Martin" "Vb" "Vehicle-treated" "Venn" "Ventana" "Veste3" "Vgll4" "Vivanco" "Vogelstein" "Vps9" "Vs" "WAR" "WBC" "WEE" "WERI-Rb-1" "WHI" "WHI-P154" "WHIP-154" "WKY-C" "WM1552" "WMM" "WP-1066" "WST-1" "WT-C464A" "WT-UTR" "WT129" "WT21" "WT865" "WW3" "Wakulich" "Wallis" "Walts" "Warburg" "Wee1" "Wee1i" "Weibull" "Weinberg" "Wenham" "Western-blot" "Whitlock-Witte" "Whitney" "Whole-exome" "Wijnhoven" "Wilcoxon" "Wilson" "Wnt-C59-treated" "Wolff-Parkinson-White" "Wright-Giemsa" "Wu" "X-box" "X-induced" "X-irradiation" "X-linked" "X-ray" "X-rays" "X-tile" "XC-302" "XDC-1787-C" "XRCC3-5" "XRCCs" "XTT" "XbaI" "Xeno-transplantation" "Xiao" "Xinchang" "Xp11.22" "Xq" "Xq11.2-q12" "Xq12" "Xq21.2" "Xu" "Y-box" "Y-intercept" "Y-linked" "Y1203fs" "Y204" "Y2H" "Y32–Y40" "Y931C" "Y931C-expressing" "YAP1-dependent" "YB-1–and" "YES" "YT521-B" "Yan" "Yang" "Yat-sen" "Yee" "Yeh" "Yes-associated" "Yin" "York" "Yu" "Z-DEVD-FMK" "Z-stacking" "Z-stacks" "ZC3H7A" "ZD-1839" "ZFAND5" "ZFAS1-miRNA" "ZFP36L3" "ZNF592" "ZPFM1" "ZPFM2" "Zender" "Zeneca" "Zeng" "Zernicka-Goetz" "Zhang" "Zhao" "Zhejiang" "Zhou" "Zn" "Zn-finger" "ZnCl" "ZnF1" "a-FOXO1A" "a-pFOXO1A" "aOR" "aOR=1.38" "aOR=1.50" "aOR=1.73" "aPKC" "aa181–310" "aa1–200" "aa201–437" "aa36-345" "aak" "aak-1" "aak-2" "abdominal-B" "aberrancies" "above-discussed" "above-referenced" "absorbance" "acetyl-11-keto-beta-boswellic" "acetyllysine" "acetyltransferase-deacetylase" "acid-Schiff" "acid–Schiff" "acinar-predominant" "acinar-to-ductal" "acro-renal-ocular" "actin-cytoskeleton" "activatingPIK3CA" "activation-loop" "activator-like" "activators" "active-site" "acute-phase" "acyl" "acyl-carnitine" "acyl-carnitines" "adduct" "adduct-repair" "adducts" "adenine-to-cytosine" "adenine-uridine" "adeno" "adeno-squamous" "adenosyl" "adenylate-uridylate-rich" "adenylyl" "adherens" "adherens-1" "adhesiveness" "ado-trastuzumab" "adult-onset" "advanced-stage" "affinity-regulating" "agar" "age-associated" "age-dependency" "age-dependent" "age-of-initial" "age-of-onset" "aggregate-prone" "ago-NC" "agomir" "agomirs" "agonism" "agonists" "alanine-rich" "alanine‐rich" "alanyl" "aldo-keto" "algorithm" "algorithms" "alkyl" "all-time" "allele-specifically" "alleles" "allograft" "alpha-B" "alpha-helical" "alternative-spliced" "amino-acid" "amino-terminal" "amino-terminal-associated" "amino-terminal-occluded" "amino-terminus" "aminoacids" "aminopyrazines" "amplicon" "amplicons" "analytes" "and9" "andDAB2IP" "andFMNL2" "andGli1" "andKEAP1gene" "andKRAS" "andMDA" "andMDM2" "andOma1" "andPTB" "andPhb2" "andUHRF1restored" "androgen-deprivation" "androgen‐dependent" "androgen‐independent" "aneuploidy" "angeloylplenolin" "angiogenesis-associated" "angiography" "angiostatic-angiogenic" "angiotensinII" "annulata" "anoikis-like" "anoikis-sensitivity" "anorexia" "anorexia-cachexia" "anoïkis" "antagomir" "antagomir-9-3p" "anthracycline-regimens" "antibodies" "antibody-drug" "antigen-6" "antigen-driven" "antigens" "antioxidant-chemotherapy" "antiplatelet" "anti‐tumourigenic" "apical-basal" "apico-basal" "aplasia" "apocrine" "apocyanin" "apoptotic-miRNAs" "app" "appropriateness" "arachidonate" "arginine-rich" "arisen" "arrest-specific" "arsenic-mediated" "artic" "asVE-821" "aspartatecarbamoyltransferase-dihydroorotase" "aspartyl" "at-risk" "at4" "atenolol" "atg-18" "ation" "atomic-force" "aureus" "auto-ADP-ribosylation" "auto-PARylation" "auto-activation" "auto-inhibited" "auto-modification" "auto-regulatory" "autophagy-like" "autophagy-lysosome" "autosomal-dominant" "autosomal-recessive" "axial" "axon" "aza-deocycitidine" "a–c" "a–d" "a–e" "b-AP15" "baf" "bars=10" "basal-like" "basal-type" "base-call" "base-extension" "base-pair" "base-pairs" "base-specificity" "basic-helix-loop-helix-leucine" "begun" "benzo" "benzthiazole-N-oxide" "best-fit" "beta-oxidation" "beta-strand" "better-quality" "betweenESR1" "betweenUHRF1and" "bi" "bi-allelic" "bi-directional" "bi-functional" "biliverdin" "binding-protein" "bio-availability" "bio-marker" "bio-markers" "bio-synthesis" "biofluids" "bioinformatics-based" "biologically-distinct" "biomarker-studies" "biomarker-test" "biomass" "biomolecules" "biopsy-proven" "biosources" "biotin-GA" "biotin-miR-346" "biotinylated-ganetespib" "biotinylated-geldanamycin" "birth-and-death" "birthdate" "bisphosphate" "blast-like" "blockade-mediated" "blood-based" "blood-brain" "blood-brain-barrier" "blood-derived" "blood–brain" "blue-dead" "box-8" "box-containing" "box-lacking" "box1" "bp" "brainstem" "brake-point" "branched-chain" "break-apart" "break-induced" "breakage-fusion-bridge" "breakpoint" "breakpoints" "breast-ovarian" "broad-spectrum" "broader" "bucladesine" "build-up" "by-product" "by-products" "by100" "byUHRF1" "b " "c-Jun-induced" "c-MycER" "c-NHEJ" "c-Src-JAK2" "c-Src-deficient" "c-Src-mediated" "c-Src-shRNA" "c-Src-shRNAs" "c-neu" "c-nu" "cAMP-AM" "cATP" "cHER2" "cHER2-negative" "cMYC-MCF10A" "cMyc" "cNO" "cPARP" "calcium-calmodulin-dependent" "caliper" "callosum" "cancer-like" "cancer-relevant" "cancerous-noncancerous" "cancer‐related" "cancer‐specific" "candidate-gene" "cap-n-collar" "capase-3" "capase-8" "capillary-like" "capsase-3" "capsid" "capsule-like" "capture-based" "carbamoyl-phosphate" "carbonyl" "carbonyls" "carboxyl" "carboxyl-termini" "carboxyl-terminus" "carboxyl‐terminal" "carcinoma-metastatic" "cardia" "cardiac-restricted" "cardiac-specific" "cardiomyocytes" "cargo-selective" "cargos" "carnitine" "carotid" "carriers" "cartilage–bone" "case-control" "case-only" "casepase-3" "case–control" "caspas-3" "caspase-3-like" "caspase-8-null" "cassette-insertion" "castration-induced" "castration-sensitive" "catalyse" "catheter" "caveolar-mediated" "ccRCC" "ccRCCs" "ceRNAs" "celastrol-that" "cell-autonomous" "cell-context-specific" "cell-intrinsic" "cell-like" "cell-of-origin" "cell-permeable" "cell-permeable3" "cell-substratum" "cell-to-cell" "cells" "cell‐type" "centromere" "cerebellar-specific" "cerebellum" "cftDNA" "ch-TOG" "ch-TOG-TACC3" "chain-modified" "chaperone-like" "chemically-induced" "chemo" "chemo-preventive" "chemo-radiotherapy" "chemo-reagent" "chemo-reagents" "chemo-repellent" "chemo-response" "chemo-sensitivity" "chemoattractant" "chemoendocrine" "chemoradiotherapy" "chemoresistance" "chemoresistant" "chemotherapy-resistance" "chemotherapy-trastuzumab" "chemotherapy‐induced" "chemotypes" "chi-square" "chi-squared" "child-parent" "cholestasis-accelerated" "cholestasis-associated" "cholesterol-containing" "cholesterol-depleting" "cholesterol-lowering" "choroid" "chosen" "chr" "chr12p" "chr19" "chr19_37756707_37760335" "chr2" "chr3_129101148_129103476" "chr5" "chr5_1607662_1663720" "chr9" "chromatid" "chromatids" "chromatograms" "chromophobe" "chromosomally-inserted" "chromosome14q" "ciliate" "circuitry" "cis-element" "cis-regulatory" "cisplatin-naive" "cistrome" "cistrome-wide" "cistromes" "clade" "clear-cell" "clear-cut" "clear-evidence" "clearers" "clientele-specificity" "clinic-pathological" "clinic-pathologically" "clinical-pathological" "clinically-critical" "clinicians" "clinico" "clinico-pathologic" "clinico-pathological" "clinic–pathological" "closed-loop" "coactivator-1" "coactivator-1α" "cobblestone-like" "codominant" "codon" "codon-12" "codon-13" "codons" "cohorts" "coiled-coil" "cold-induced" "cold-shock" "coli" "collagens" "collectives" "colony-formation" "colony-forming" "comedo" "comedo-like" "common-B-ALL" "commonalities" "commonest" "comorbidities" "complex-2" "complex-proficient" "components-beads" "compounds-induced" "concentration-and" "concentration-dependently" "concentration-response" "conditional-null" "conformers" "confounders" "congenita" "contact-induced" "contact-inhibited" "context‐dependent" "continuum" "control-RET" "control-shRNA" "control-treated" "copper-dependent" "copy-containing" "copy-number" "core-binding" "core-complex" "coregulators" "correlatedwithmiR-29b" "cortico-striatal" "cost-effective" "cost-to-benefit" "counter-balance" "counter-protective" "covalently-modified" "covariate" "covariates" "coworkers" "cox-hazard" "coxibs" "co‐expression" "cribriform" "cross-cancer" "cross-compared" "cross-complementing" "cross-contamination" "cross-control" "cross-interaction" "cross-matching" "cross-reacting" "cross-reactivity" "cross-regulation" "cross-regulatory" "cross-resistance" "cross-sectional" "cross-sections" "cross-sensitivity" "cross-species" "cryotherapy" "ctDNA" "cullin-4" "cullin-RING" "cullin3–RING-box" "cut-off" "cut-off-dependent" "cut-offs" "cut-points" "cycD1" "cycE" "cyclapolin1" "cyclase-associated" "cycle-related" "cyclin-T" "cyclins" "cycloxygenase-2" "cyto" "cytodomain" "cytoskeletal-associated" "cytosol-like" "cytosol-to-nucleus" "c–e" "c–h" "d-f" "dL" "dRASSF8" "damage-associated" "damage-containing" "damage-dependent" "damage-independent" "damage-induced" "damage-inducer" "damage-inducible" "damage-inducing" "damage-responsive" "damage–induced" "dark-side" "dataset" "datasets" "day-to-day" "day14" "days" "dbSNP" "dbSNP131" "dbSNP137" "ddATP" "ddPCR" "de-acetylase" "de-conjugated" "de-conjugation" "de-differentiated" "de-fatty" "de-regulated" "de-regulation" "de-repression" "de-stabilization" "de-stabilize" "de-stabilizes" "de-ubiquitinases" "deacetylase-activating" "death-receptor" "decidua" "dedifferentiate" "deeper" "degrader" "degrons" "del-ex19" "del11q" "del17p" "del17p13" "del5395" "delE746-A750" "deletion-type" "delta169" "dense-band" "dense-membrane" "density-dependent" "deoxynucleotidyl" "deoxyuridine" "depolarization-dependent" "deprivation‐induced" "derived-bioactive" "dermal-epidermal" "desaturade-1" "desaturase-1" "desmoplasia" "detection-method" "deubiquitylates" "dextran-treated" "de‐regulated" "di-methylate" "di-methylation" "di-phosphorylated" "diM-α-KG" "diabetes-associated" "diamino-pyrimidine" "diaryl" "dideoxy" "dien-28-imidazolide" "diet-fed" "diet-induced" "diffraction-limited" "dihydrocelastrol-a" "dihydropteridinone" "dimers" "dimethyl-fumarate" "dimethyl-succinate" "dimethyl-α-KG" "dioxooleana-1,9" "dioxygenases" "dipeptidyl" "diphosphate" "diphosphates" "diploid" "dis" "dis-equilibrium" "discrepant" "disease-and" "disposal-like" "disrupted--in" "distant-stage" "disulfide-based" "dithiocarbamate" "diversity-mediated" "dl1520" "doi" "domain-1" "domain-like" "dominantly-inherited" "dosages" "dose-dependence" "dose-dependently" "dose-escalation" "dose-increasingly" "dose-independent" "dose-intensification" "dose-limiting" "dose-response" "dose–effect" "dose–response" "double-cysteine" "double-hit" "double-membrane" "double-minute" "double-mutant" "double-point-mutation" "double-strand" "double-thymidine" "down-modulate" "down-modulated" "down-modulation" "down-slanting" "down-stream" "downregulators" "downstream-regulator" "down‐regulated" "down‐regulation" "drawn" "drivesUHRF1expression" "droplet" "droplet-digital" "droplets" "drug-antioxidant" "drug-combination" "drug-drug" "drug-like" "drug-selection" "dsDNA" "dual-color" "dual-functional" "dual-labeled" "dual-labeling" "dual-labelled" "dual-regulating" "dual-stabilization" "dual-staining" "duct-Henle's" "duct-specific" "ductulo-lobular" "dupA" "duplexes" "dynamin-like" "dysgeneses" "dyslipidemias" "dysplasia" "dysplasias" "d–f" "eFluor670" "eGFP-fusion" "eGFP–HDAC3-expressing" "eGFP–HDAC3-overexpressing" "eIF4" "eLife" "eQTL" "earlier-stage" "early-mid" "early-onset" "early-stage" "early-treatment" "ebiNSc" "echinoderm" "echocardiography" "eclampsia-associated" "ectoderm" "ectopia" "edema" "effecter" "effectuates" "efficacy-of-standard" "eighty-five" "eldest" "electron-dense" "electron-lucent" "eleven-day" "eleven-nineteen" "emboli" "embolus" "embryoid" "embryonic-lethal" "empts" "enantiomer" "enantiomers" "end-diastolic" "end-product" "end-resection" "end-stage" "end-to-end" "endometrioid" "endometrium" "endotoxemia" "endpoint" "endpoints" "energy-efficient" "enhancer" "enhancer-binding" "enteropathy" "enzyme-substrate" "enzymes" "enzyme–activator" "enzyme–substrate" "eosin" "epidermoid" "epithelia" "epithelial-like" "epithelial-mesenchymal" "epithelial-mesenchymal-like" "epithelial-specific" "epithelial-stroma" "epithelial-to-mesenchymal" "epithelial‐to" "epithelial–mesenchymal" "epithelioid" "epithelioid-like" "epithelium" "epitopes" "erlotinb" "erytheroid-derived-2-like" "erythroid-2–related" "estrogen-and" "estrogen-deprived" "estrogen-receptor-α" "et" "eta" "et " "ever-changing" "ever-expanding" "evidenceofmiR-29b's" "ex" "ex-smoker" "ex-smokers" "ex-vivo" "ex12" "ex2" "ex3" "exercise-induced" "exocrine" "exon-intron" "exon11-mutated" "exons" "exosome" "expressers" "extra-hepatic" "extra-islet" "extra-nuclear" "extra-ribosomal" "extra-thymic" "extra-uterine" "extracellularly-delivered" "extrinsic–death" "ex " "e–08" "facilitated-tumor" "factor-1" "factor-1α" "factor-2" "factor-kB" "factor-kappa-B" "factor-kappaB" "factors" "fair-skinned" "false-discovery" "false-discovery-rate-corrected" "false-positives" "family-trio" "far-fetched" "farnesyl" "fast-migrating" "fat-pads" "fatigue-induced" "feedback-mediated" "female-derived" "female-specific" "female-type" "femtosecond" "fenoprofen" "ferroportin-1" "fiber-type-specific" "fibro-muscular" "fibroblast-like" "fibroblastoid" "fibroblastoid-like" "fibrofatty" "fibrosis-associated" "field-induced" "field-of-view" "filopodia-like" "fine-needle" "fine-tune" "fine-tuned" "fine-tuning" "finger-like" "first-degree" "first-generation" "first-in-class" "first-line" "five-drug" "five-fluorouracil" "five-transmembrane" "five-weeks" "five-year" "fixed-dose" "flag‐PIK3CA" "flash-frozen" "flat-mounts" "flavaglines" "flavonolignan" "flcn-1" "flow-cytometric" "flow-cytometry" "flow-mediated" "flowchart" "flow‐mediated" "flox" "fluorodeoxyglucose" "fluorophore" "fluorophores" "focus-forming" "foenum" "foenum-graecum" "foeto" "foeto–maternal" "fold-coverage" "fold-increase" "follicles" "follow-up" "follow-ups" "followed-up" "followup" "forMARCKS" "forebrain" "forestomach" "formalin-fixation" "forty-eight" "four-serine" "fourth-largest" "frame-shift" "frameshift" "frameshifts" "free-survival" "fresh-frozen" "front-back" "front-line" "front-to-back" "frozen" "fructose-2,6-bisphosophatase" "fs" "fsX16" "full-lenth" "full-term" "full-text" "fumarate" "fusion-activated" "gDNA" "gadolinium" "gain-and-loss-of-function" "gain-of-function" "gain-of-functions" "gain‐of‐function" "gallbladder" "ganglion-10" "gasotransmitters" "gastrectomy" "gastro" "gastro-esophageal" "gastro-intestinal" "gate-keeper" "gate-keepers" "gatekeeper" "geldanamycin-derivative" "gene-disease" "gene-expression-based" "gene-gene" "gene-panel" "gene-regulatory" "gene-therapeutic" "genes" "geneset" "genetic-association" "genetically-defined" "genetically-engineered" "gene–gene" "genome" "genome-wide" "genomes" "genotype" "genotype-phenotype" "genotypes" "genotype–phenotype" "geranylgeranyl" "geranylgeranyl-transferase" "germ-line" "gk378" "glia" "glia-like" "glucagon-like" "glucocorticoid-regulated" "glucose-1-phosphate" "glucose-6" "glutamate-cysteine" "glutamate-glutamine" "glutamate–cysteine" "glutamine-to-leucine" "glutamyl" "glycerol-3-phosphate" "glycine-rich" "gm" "goes" "gondii" "gp87" "gpdh" "gpdh-1" "gpdh-2" "graecum" "gram-scale" "granulo" "granulo-monocyte" "granulo-monocytic" "granulocyte-monocyte" "greater" "greatest" "green-fluorescent" "grip-like" "group11" "growth-arrest-specific" "growth-dependency" "growth-restrictive" "growth-suppressive" "gsy-1" "gt33" "guanine-mimetic" "guanine-to-thymidine" "gymnestrogenin" "hESCs" "hMSC" "hMSCs" "hMps1-MDM2-ubH2B" "hMps1with" "hNPCs" "hNQO1-ARE-Luc" "hRBM4" "hT" "hTER" "hTERT-cells" "hTRmin" "haeme" "haemolysis-associated" "half-ERE" "half-fold" "half-inhibitory" "half-life" "half-lives" "half-maximal" "half-siblings" "half-sisters" "half-site" "half-sites" "half-sized" "halo-like" "haplo-insufficiency" "haplotype" "haplotypes" "hard-to-find" "has-miR-1" "has-miR-142-5p" "has-miR-202" "has-miR-98" "has-miR29" "head-to-tail" "heart-specific" "heat-inducible" "heat-map" "heat-shock" "heatmap" "helices" "helix" "helix-loop-helix" "helixes" "helix–loop–helix" "hemagglutinin-epitope-tagged" "hematoxylin-eosin" "hemeoxygenase-1" "hemispherectomy" "heparin-agarose" "hepatocyte-derived" "hepatocyte-like" "hepatoid" "hepatotoxins" "hept-5-ene-2-carboxylic" "heptapeptide" "hetero" "hetero-dimeric" "hetero-dimers" "hetero-oligomerization" "hetero-tetramer" "heterodimers" "heteronucleotide" "heterozygote" "hg19" "hidden" "high-TIL" "high-ab" "high-affinity" "high-affinity-binding" "high-cellularity" "high-concentration" "high-confidence" "high-content" "high-copy" "high-degree" "high-density" "high-dose" "high-energy" "high-fat" "high-fat-diet" "high-glucose" "high-grade" "high-heterogeneity" "high-input" "high-input-power" "high-iron" "high-irradiance" "high-level" "high-levels" "high-mobility-group" "high-penetrance" "high-penetrant" "high-performance" "high-quality" "high-resistance" "high-resolution" "high-risk" "high-sensitivity" "higher-affinity" "higher-dose" "higher-order" "highest-scoring" "highly-activated" "highly-annotated" "highly-sensitive" "high‐risk" "hinge–hinge" "hippo-mediated" "histochemistry" "histologies" "histology" "histotype" "histotypes" "hnRNPA1-ESS" "hnRNPA1-ISS" "hnRNPs" "home-brew" "homeodomain" "homo-dimers" "homo-oligomers" "homogenates" "homolog" "homolog-5" "homologs" "homology-2" "homology-based" "homonucleotide" "homopurine" "homopyrimidine" "homozygote" "homozygotes" "hormonal-dependent" "hormone-naïve" "hospital-based" "hot-miR-138" "hot-spot" "hotspot" "hotspots" "hsCRP" "hsa-miR-101" "hsa-miR-125b" "hsa-miR-29a" "hsa-miR-29b" "hsa-miR-513a-5p" "hsa-miR-628-3p" "hsa-miR-9-1" "hsa-miR-9-2" "hsa-miR-9-3" "hsp-miR-98" "hyaloid" "hydrogels" "hydrogen-bond" "hydrogen-exchanger" "hydroxycholesterol" "hyper" "hyper-activation" "hyper-dissemination" "hyper-invasive" "hyper-proliferation" "hyper-γ-H2A" "hyperinsulinemia" "hyperoxia-CCN1" "hyperphosphatemia" "hyperpolarization-activated" "hyperresponsiveness" "hypo-acetylation" "hypo-expression" "hypo-phosphorylated" "hypocalcemia" "hypodermis" "hypoglycemia" "hypoxia-LY294002" "hypoxia-niche" "hypoxia-protective" "hypoxia-survival" "i-GSEA4GWAS" "iBMK" "iCOGs" "iEA" "iEA " "iGSEA4GWAS" "iNOS+p53" "iNSCs" "iNSCs-like" "iNSc" "iNSc-like" "iVSD" "iVSDs" "identifiers" "ie" "ii" "iii" "ill-defined" "imidazole-4-carboxamide" "immediate-early" "immune-cell-poor" "immune-cell-rich" "immune-depressed" "immune-driven" "immune-histochemical" "immune-histochemistry" "immune-mediated" "immune-related" "immuno-FISH" "immuno-histochemistry" "immuno-modulatory" "immunoarray" "immunoassay" "immunocytochemistry" "immunoglobulin" "immunoglobulin-like" "immunophenotype" "immunophenotypes" "immunoprecipitant" "immunosurveillance" "immunotherapies" "immunotherapy" "impedance" "in-depth" "in-frame" "in-house" "in-line" "in-nucleus" "in-situ" "in-stent" "in-vitro" "in-vivo" "inK-ras" "inMCF" "inNrf2" "inPhb2" "indel" "indels" "induced-fit" "induced-pluripotent" "infection-induced" "inflammation-associated" "inflammation-induced" "inflammation-promoting" "inflammatory-like" "inhibition-not" "inhibiton" "inhibitor-1" "inhibitor-NF-κB" "inhibitor-treated" "inhibitors" "input-power" "input-power-dependent" "inside-out" "insulin-AKT-mTOR" "insulin-activated" "insulin-dependent" "insulin-induced" "insulin-like" "insulin-mediated" "insulin-sensitive" "insulin-stimulated" "insulinoma-glucagonoma" "int-1" "integrin-cytoskeleton" "integrin-evoked" "intensity-modulated" "inter-cellular" "inter-chromosomal" "inter-domain" "inter-group" "inter-individual" "inter-malignancy" "inter-membrane" "inter-observer" "inter-relationship" "inter-strand" "inter-study" "inter-subset" "interacome" "interactome" "interactomes" "interconvert" "intercrosses" "intermediate-conformation" "intermediate-risk" "intermembrane" "internet" "interquartile" "interstitium" "interstrand" "intestinal-type" "intima" "intra-S" "intra-S-phase" "intra-domain" "intra-epithelial" "intra-islet" "intra-mitochondrial" "intra-ovarian" "intra-peritoneal" "intra-protein" "intra-residual" "intra-tissue" "intra-tumor" "intra-tumoral" "intracellular-domain" "intractableEML4-ALK" "intramitochondrial-calcium-dependent" "intrinsic–mitochondrial" "intron-2" "introns" "invariant" "invasion-associated" "invasion-inducing" "invasion-inhibition" "invasion-metastasis" "invasion-promoting" "in‐house" "ion-pair" "ionization-time" "irradiance" "irradiances" "irradiation-induced" "irradiation-treated" "ischaemia" "islet-derived" "iso-elasticity" "isoindolin-2-ylmethyl" "isothiocyanatostilbenes" "isotype" "isotypes" "isozymes" "iv" "jam-l" "kDa" "kappa-light-chain-enhancer" "karyotype" "karyotypes" "kb24" "kb33" "kbp" "kcal" "ketoprofen" "ketorolac" "kg" "kinase-null" "kinase1" "kinases" "kinase‐associated" "kinetochore-mitotic" "kinome" "kit-8" "km25" "knock-down" "knock-in" "knocked-down" "knockin" "knocking-down" "kruppel-like" "l-glutathione" "lHSP72" "lactose" "lambda" "lamina" "laminin-triggered" "large-cell" "large-scale" "larger-scale" "larger-sized" "laser-capture" "laser-damage" "laser-induced" "laser-irradiated" "late-onset" "late-passage" "late-stage" "lavage" "lavages" "layer-specific" "lead-like" "leave-one-out" "left-side" "lenti-ZFP36L1" "lenti-ZFP36L1-infected" "lenti-ctrl-infected" "lenti-shZFP36L1" "lenti-viral" "less-than-perfect" "let-7a" "let-7b" "let-7f" "let-7f-5p" "let-7i" "leukemia-1" "leukemia-2" "leukocoria" "life-long" "lifespan" "ligand-RTK" "ligand-less" "ligand-receptor" "light-chain" "line-to-line" "lineage-specific" "lineage-survival" "lipoproteins" "lipoxygenase-5" "liriodenine" "littermate" "littermates" "live-cell" "liver-carcinogenic" "lncPro" "lncRNA" "lncRNA+mRNA" "lncRNA-ATB" "lncRNA-GAS5" "lncRNA-anti-differentiation" "lncRNA‐DLEU1" "lncRNA‐related" "lncRNA–mRNA" "loCP" "localizations" "lock-and-key" "locked-nucleic" "loco-regional" "locus-specific" "log-additive" "log-fold" "log-normal" "log-rank" "log2" "long-chain" "long-lasting" "long-lived" "long-period" "long-range" "long-standing" "longer-lasting" "longer-term" "long‐term" "look-up" "loss-of-ATM-function" "loss-of-function" "loss-of-heterozygosity" "loss‐of‐function" "low-ER-staining" "low-HER-2-expressing" "low-MPS" "low-TIL" "low-abundance" "low-affinity" "low-complexity" "low-coverage" "low-density" "low-differentiation" "low-dose" "low-energy" "low-frequency" "low-grade" "low-input-power" "low-irradiance" "low-level" "low-levels" "low-passage" "low-penetrance" "low-penetrant" "low-penetrate" "low-power" "low-proliferative" "low-risk" "low-set" "low-to-null" "lower-bound" "lower-differentiated" "lower-differentiation" "lower-grade" "luciferase-reporter" "luminal-like" "luminal-to-basal" "luminal-type" "lumpectomy" "lupus-like" "lymph-node" "lymph-node-positive" "lymphoblastoid" "lymphoma-2" "lymphoma-extra" "m3p" "m5p" "mADC" "mADCs" "mAG" "mAG1" "mAb" "mAb135" "mAb48" "mAbs" "mCRC" "mCRCs" "mCRPC" "mGFP" "mHER2" "mHSP72" "mHTT" "mIR-200c-driven" "mJ" "mKO2" "mL·h" "mRNA" "mRNA-level" "mRNA-like" "mRNA-stability" "mRNAs" "mRNA‐ESR1" "mRNA–ncRNA" "mROS" "mSigDB" "mSin3A" "mT" "mT-mG" "mTOR-inhibitor" "mTOR-pathway" "mTOR1" "mTORopathies" "macro-metastasis" "macropulse" "macropulses" "macroscopicK" "magainin1" "magnesium-activated" "make-up" "malignances" "malignancy‐specific" "mammography" "mammosphere" "mammospheres" "mantGTP" "mastectomy" "master-c-Myc" "materials" "matrix-detachment" "mature-B-cell" "maximum-tolerated" "mdm2-C" "mdx" "mdx-βgeo" "mediated-ADCC" "medically-intractable" "medications" "medium-to-large" "medulla" "medullary-like" "mega-analysis" "megalencephaly-polymicrogyria-polydactyly-hydrocephalus" "melanogaster" "melittin-Sepharose" "mellitus" "membranaceus" "membrane-cytoskeletal" "membrane-permeable" "membrane‐associated" "membrane‐bound" "mesenchymal-CSCs" "mesenchymal-epithelial" "mesenchymal-like" "mesenchymal-related" "mesenchymal-to-epithelial" "mesenchymal–epithelial" "mesenchyme" "mesenchyme-like" "mesoderm" "mesylate" "metal-stress" "metalloproteinase-1" "metalloproteinase-released" "metastasis-repressive" "metastasis-suppressive" "metastatic-repressive" "methanesulfonate" "methide" "methides" "methionine–choline-deficient" "methoxy" "methyl-DNA" "methyl-Ile" "methyl-Met" "methyl-methanesulfonate" "methyladenine" "mevalonate" "mg3" "miR-1" "miR-1-based" "miR-101" "miR-101-transfected" "miR-103" "miR-107" "miR-107-induced" "miR-107-mediated" "miR-107-overexpressing" "miR-10a" "miR-122" "miR-122-mediated" "miR-124" "miR-124-1" "miR-125" "miR-125-5p" "miR-1254" "miR-125a" "miR-126" "miR-126a-3p" "miR-127" "miR-128" "miR-130a" "miR-132" "miR-133a" "miR-133b" "miR-135" "miR-135a" "miR-138" "miR-138-mediated" "miR-138-suppressed" "miR-139-3p" "miR-139-5p" "miR-139-5p-expressing" "miR-139-5p-expression" "miR-141" "miR-141-3p" "miR-142" "miR-142-3p" "miR-143" "miR-143-3p" "miR-144" "miR-144-SW1463" "miR-144-SW837" "miR-144-overexpressing" "miR-144-trans-fected" "miR-145" "miR-146a" "miR-146b-3p" "miR-148b" "miR-150" "miR-150-RET" "miR-150-RET-infected" "miR-150-expressing" "miR-155" "miR-155-3p" "miR-155-regulated" "miR-155-treated" "miR-15a" "miR-16" "miR-16-mediated" "miR-17" "miR-17-92" "miR-18" "miR-181" "miR-182" "miR-1826" "miR-183" "miR-185-3p" "miR-18a" "miR-18b" "miR-190" "miR-192" "miR-192-mediated" "miR-192-transfected" "miR-192-treated" "miR-193a-3p" "miR-195" "miR-195-5p-agomir-treated" "miR-196a-5p" "miR-197-3p" "miR-199" "miR-199a" "miR-199a2" "miR-199b" "miR-199b-5p" "miR-1NC" "miR-1inhbitor" "miR-1inhibitor" "miR-1mimic" "miR-200" "miR-200s" "miR-202-3p" "miR-203" "miR-204" "miR-205" "miR-208b" "miR-20a" "miR-210" "miR-210-3p" "miR-211" "miR-212" "miR-212-3p" "miR-212-induced" "miR-214" "miR-214-based" "miR-214-induced" "miR-214-inhibited" "miR-214-overexpressing" "miR-214–overexpressing" "miR-215" "miR-216b" "miR-219" "miR-219-1-3p" "miR-22" "miR-22-deficient" "miR-22-dependent" "miR-22-treated" "miR-221-mediated" "miR-223" "miR-224" "miR-22–deficient" "miR-22–sufficient" "miR-24" "miR-24-Bim" "miR-24-mediated" "miR-24-overexpressing" "miR-26a" "miR-26b" "miR-296" "miR-29b-AKT" "miR-29b-AKT-HK2" "miR-29b-mediatedcontrolof" "miR-29bmay" "miR-3" "miR-30" "miR-301b" "miR-302a" "miR-302c" "miR-30a" "miR-30c" "miR-3151" "miR-32" "miR-320" "miR-320b" "miR-320b-transfected" "miR-326" "miR-328" "miR-329" "miR-331-3p" "miR-33a" "miR-33a-induced" "miR-33a-overexpressing" "miR-33b" "miR-34" "miR-340" "miR-342-3p" "miR-346" "miR-346-activated" "miR-346-dependent" "miR-346-facilitated" "miR-346-induced" "miR-346-loop" "miR-346-mediated" "miR-34b" "miR-34c" "miR-361" "miR-361-3p" "miR-367" "miR-369-3p" "miR-369–3p" "miR-370" "miR-371-3p" "miR-372" "miR-373" "miR-376b" "miR-378a-3p" "miR-380-3p" "miR-382" "miR-410" "miR-424" "miR-433" "miR-450a" "miR-451" "miR-451-induced" "miR-454" "miR-455" "miR-455-3p" "miR-484" "miR-485-3p" "miR-486" "miR-487a" "miR-487b" "miR-490-3p" "miR-491-3p" "miR-494" "miR-495" "miR-499a-5p" "miR-502" "miR-503" "miR-505" "miR-506" "miR-508" "miR-510" "miR-511" "miR-512-3p" "miR-513a-5p" "miR-517a" "miR-517c" "miR-518b" "miR-518d" "miR-518f" "miR-519c" "miR-519d" "miR-519e" "miR-520b" "miR-520d-5p" "miR-522" "miR-523" "miR-545" "miR-548a" "miR-548a-5p" "miR-548b-5p" "miR-548c" "miR-548c-5p" "miR-548d" "miR-548d-5p" "miR-556-3p" "miR-561" "miR-570" "miR-576-3p" "miR-584" "miR-589" "miR-590-3p" "miR-597" "miR-598" "miR-599" "miR-618" "miR-622" "miR-622-associated" "miR-622-mediated" "miR-622-overexpressing" "miR-622-transfected" "miR-627" "miR-628-3p" "miR-629-HNF4-miR-124" "miR-652" "miR-654-3p" "miR-655" "miR-672" "miR-7-dependent" "miR-708" "miR-888" "miR-889" "miR-891a" "miR-9" "miR-9-2" "miR-9-3" "miR-9-3p" "miR-9-5p" "miR-9-5q" "miR-9-mediated" "miR-92" "miR-92a-1" "miR-92a-2" "miR-92a-2-3p" "miR-92a-2-5p" "miR-92a-3p" "miR-93" "miR-95" "miR-98" "miR-chips" "miR-control-SW1463" "miR-control-SW837" "miR-control-transfected" "miR103" "miR133a" "miR139-5p" "miR200c" "miR488" "miR92a-2-3p" "miR92a-2-3p-overexpressing" "miRDB" "miRNA" "miRNA-130a" "miRNA-15a" "miRNA-16" "miRNA-16-1" "miRNA-192" "miRNA-200" "miRNA-205" "miRNA-21" "miRNA-212" "miRNA-23a" "miRNA-29" "miRNA-346-mediated" "miRNA-372" "miRNA-451" "miRNA-9" "miRNAs" "miRNA‐mediated" "miRNA–lncRNA" "miRNA–mRNAnetwork" "miRNA–mRNA–lncRNA" "miRNA–mRNA–lncRNAinteraction" "miRNA–mRNA–lncRNAinteractions" "miRanda" "miRwalk" "miR‐106a" "miR‐106a~363" "miR‐130a‐3p" "miR‐141" "miR‐148b‐3p" "miR‐17" "miR‐17‐3p" "miR‐17‐5p" "miR‐17‐92" "miR‐18a‐5p" "miR‐19" "miR‐19a" "miR‐19a‐3p" "miR‐19b" "miR‐19b‐3p" "miR‐200c" "miR‐20a" "miR‐20b" "miR‐25‐3p" "miR‐363" "miR‐490" "miR‐490‐3p" "miR‐490‐5p" "miR‐92" "miR‐92a" "miR‐92‐3p" "miR‐93‐5p" "mice" "micro-CT" "micro-compartments" "micro-computed" "micro-disection" "micro-dissected" "micro-environment" "micro-injected" "micro-injuries" "micro-irradiation" "micro-metastases" "micro-molar" "micro-tumor" "micro-tumors" "microRNA-144" "microRNA-200" "microRNA-22" "microRNA-451" "microRNA-494" "microRNA-7" "microdomains" "microenvironment-induced" "microenvironment-niches" "micrographs" "microparticles" "micropipette" "microsatellite" "microsatellite-unstable" "microvasculature" "microvessel" "micro‐RNAs" "mid-anteroseptal" "mid-inferior" "mid-infero-lateral" "mid-inferolateral" "mid-life" "mid-myocardial" "mid-myocardium" "midbrain" "middle-ear" "migration-and" "mild-inflammatory" "mild-regenerating" "milliseconds" "mim1" "mimics" "mineralization-inducing" "mini-review" "minigenes" "minimal-subunit" "mir-214" "mir-548" "mir30-based" "mirPath" "mis-leading" "mis-sense" "missense" "mitEGFR-GFP" "mitochondria-targeting-EGFR" "mitochondrial-binding" "mitochondrial-dependent" "mitochondrial-mediated" "mitochondrial-related" "mitochondrial-targeting" "mitoses" "mitotic-phase" "mitotic-specific" "mixed-lineage" "mixed-type" "ml " "mobility-shift" "mock-ROCK1" "mock-infected" "mock-infection" "mock-irradiated" "mock-irradiation" "mock-treated" "moderate-inflammatory" "moderate-penetrance" "moderate-risk" "moderate-to-elevated" "moderate-to-high" "moderately-differentiated" "moderately-increased" "modes-of-action" "modest-to-weak" "mono-adducts" "mono-bound" "mono-methylate" "mono-protonated" "mono-site" "mono-therapy" "monoadducts" "monocyte-derived" "monocytic-like" "monocytic-specific" "monolayer" "monophosphate" "monopolar-phenotypic" "monotherapies" "monotherapy" "month-old" "mortality-to-incidence" "moth-eaten" "motif-containing" "motif-dependent" "motif-specific" "motifs" "motile" "motile-to-motile" "mp53BS" "mt-p53" "mucosa" "multi-cancer" "multi-case" "multi-chemotherapy" "multi-component" "multi-drug" "multi-focal" "multi-hit" "multi-institutional" "multi-lineage" "multi-organ" "multi-pathways" "multi-protein" "multi-punch" "multi-stage" "multi-step" "multi-targets" "multi-tissue" "multi-vesicular" "multicenter" "multicentre" "multigene" "multilineage" "multimers" "multiorgan" "multiphoton" "multiple-center" "multiple-hit" "multiple-punch" "multiple-species" "multiple-target" "multiprotein" "multistage" "multivariate" "muscle-resident" "muscle-specific" "muscularis" "mutant-NLS" "mutant-like" "mutant–substrate" "mutations" "myelo-monocytic" "myeloid-cell-rich" "myocardium" "myofiber" "myofibers" "myofibroblast-like" "myofibroblasts" "myristoyl" "myristoylation‐deficient" "n-collar" "n=12" "n=30" "n=5" "n=6" "nCB" "nCounter" "nabumetone" "nano-Gln" "nano-liposomes" "nano-molar" "nano-particle-mediated" "nanoparticulate" "nanosecond" "nascent-RNA" "naso-pharyngeal" "nation-wide" "naïve" "ncRNA–mRNA" "near-complete" "near-fatal" "near-infrared" "near-significance" "near-tetraploid" "nearest" "necropsy" "needle-catheter" "negative-control" "neo-adjuvant" "neo-vascular" "neoadjuvant" "neointima" "neoplasias" "nephrectomy" "nephron" "nephropathies" "nephropathy" "nervous-system" "nestin-positive" "neu" "neural-crest" "neurite" "neuro" "neuro-degenerative" "neuro-developmental" "neuro-hormones" "neuro-protective" "neuroendocrine" "neuron-like" "neuronally-differentiated" "neuropathology" "neurospheres" "neutropenia" "never-smokers" "newer" "next-generation" "next-generation-sequencing" "ngTMA" "nick-end" "nil-by-mouth" "no-cardia" "no-combination" "noncarriers" "nonmalignant" "nonresponders" "nonresponse" "nonsense-mediated" "nonsignificant" "nonsmall" "nonsmokers" "non‐coding" "non‐synonymous" "non‐tumour" "normal-large" "normal-resistance" "normally-reacting" "not-commonly" "nt" "nt+1351" "nts" "nuclear-to-cytoplasmic" "nucleates" "nucleo" "nucleo-cytoplasmatic" "nucleotide-dependent-‘specific’" "nultin3a" "n = 6" "ob" "occurrences" "oestrogen" "ofCDKN2Apromoter" "ofDAB2IP" "ofESR1" "ofK" "ofKEAP1" "ofKEAP1promoter" "ofKeap1" "ofMARCKS‐mediated" "ofPIK3CA" "ofRASSF1" "ofUHRF1fromPDACcells" "ofUHRF1is" "ofUHRF1reduced" "ofbim" "off-target" "offs" "ofnPTB" "ok524" "ok975" "old-style" "oligos" "oligosaccharide-binding" "omega-3" "omega-N" "omic" "omics" "on-going" "on-target" "on-the-fly" "once-daily" "oncodriver" "oncogene-driven" "oncomiR" "oncomirs" "oncoprotein-18" "oncotarget" "one-carbon" "one-ended" "one-letter" "one-month" "one-period" "one-site" "one-step" "one-third" "one-way" "one‐fourth" "oophorectomy" "open-label" "ortholog" "orthologue" "orthologues" "osm-11" "osm-7" "osmo-protective" "osteoblast-like" "osteoblasts" "osteomimicry" "otitis" "out-of-control" "out-of-expectation" "outer-membrane" "ovarian-specific" "ovariectomy" "over-accumulate" "over-activated" "over-activating" "over-diploid" "over-presence" "over-proliferation" "over-replication" "over-representation" "over-simplistic" "over-treated" "over-treatment" "over-winding" "overexpressors" "overnight-cultivated" "overuse" "overview" "over‐expressed" "over‐expression" "oxidative-reductive" "oxidative-stress-responsive" "oxido-reductase" "oxoG" "oxoglutarate" "oxoguanine" "oxygenase-1" "p18IN4" "p21CIP" "p21waf" "p38K" "p38MAPK" "p38MAPK-mediated" "p38β" "p53-LOH" "p53-antagonist" "p53-competent" "p53-defective" "p53-gene-specific" "p53-heterozygotic" "p53-independent" "p53-independently" "p53-null" "p53-pathway" "p53-proficient" "p53BR" "p53BRmt" "p53BS" "p53RE" "p53REs" "p53wt" "p70S6K-dependent" "p85α" "p=0.01" "p=0.02" "p=0.03" "p=0.09" "p=0.93" "pAKT" "pAKT2" "pAKT473" "pALK" "pALK-Y1604" "pATM" "pBOB" "pCM184" "pCMV-Klotho" "pCMV-Klotho-transfected" "pCMV6" "pCMV6-Klotho" "pCR" "pCdc2" "pChk1" "pChk1s" "pChk2" "pDCIS" "pDNA-PK" "pDNA-PKcs" "pDNA3.1" "pEGFP-AR" "pEGFP-V" "pEGFR" "pERK" "pERK5" "pEZX-PG04" "pFOXO1" "pFOXO1A" "pGADT7" "pGATA" "pGBKT7" "pGL3-1172" "pGL3-1733" "pGL3-202" "pGL3-320" "pGL3-320-mut" "pGL3-502" "pGL3-581" "pGL3-702" "pGL3-B-miR-101-L" "pGL3-B-miR-101-M" "pGL3-B-miR-101-MBS" "pGL3-B-miR-101-S" "pGL3-B-miR-101-W" "pGL3-B-miR-101-WBS" "pGL3-Basic-transfected" "pGL3-E-cadherinP" "pGL3-E2F1" "pGL3-E2F1-mut" "pGL3-E2F2" "pGL3-HCCR" "pGL3-HCCRP" "pGL3-PAI-1-3" "pGL3-basic" "pGSK" "pGSK-3" "pGSK3β1130" "pGeneClip-shTCERG1-C1" "pH" "pHBV1.2" "pHER2" "pHH3" "pJAK2" "pLEX" "pLEX-PTPN6" "pLKO" "pLL3.7" "pLYN" "pLasts1" "pLats1" "pLuc-979" "pMET" "pMIR-COX-2" "pMst1" "pN" "pN808S" "pRL-null" "pRRL-CMV-IRES-GFP" "pRuF" "pRuF-empty" "pS127-YAP" "pS127-YAP1" "pS184" "pS204-pS208" "pS210-CPEB1" "pS38-STMN1" "pS423" "pSMAD2" "pSPL3" "pSTAT3" "pSUPERp53" "pSer-Pro" "pSer307-specific" "pSerPro" "pSiCHECK2" "pSilencer" "pSilencer2.1" "pSilencer2.1-HCCR" "pSmad2" "pSmad2C" "pSmad3C" "pSmad3L" "pStage" "pT" "pT1-4" "pT306" "pT4" "pY" "pY1221" "pY1234" "pY31" "pY357-YAP1" "pY416-SRC" "pY527-SRC" "pY925" "pYAP" "pYAP-S127" "pYB1" "pachygyria" "pack-years" "paired-cell" "pairwise" "palmitoylcarnitine" "pan-AKT" "pan-DUB" "pan-HER" "pan-HER-TKI" "pan-MMP" "pan-PI3K" "pan-PIM" "pan-cadherin" "pan-caspase" "pan-inhibitor" "pan-nuclear" "pan-regulated" "pan-specific" "pan-upregulation" "pan-βAR" "pancreatitis" "pancreatitis-like" "para-medial" "para-medially" "paracrine" "paralog" "paralogues" "parenchyma" "parent-child" "parents" "parthanatos" "parvum" "pathobiology" "pathogen-associated" "pathogen-dependent" "pathophysiology" "pathway-proficient" "patients" "pattern-based" "pattern-recognition" "pcDNA-survivin" "pcDNA3-myc" "peak-like" "pectus" "peg-IFN" "penetrance" "penetrant" "peptide-1" "peptide-6" "peptide-like" "peptide-substrate-binding" "peptides" "per-allele" "perforin" "perhaps" "peri-operative" "peri-tumoral" "peritoneum" "person-time" "phAR1.6Luc" "phAR1.6Luc-UTR" "phAR1.6Luc-UTRm1" "phAR1.6Luc-UTRm2" "phAR1.6Luc-UTRm3" "phAR1.6Luc-UTRm4" "phAR1.6Luc-UTRm5" "phAR1.6Luc-UTRm6" "phAR1.6Luc-UTRΔm1" "phAR1.6Luc-Δm1" "pharmaco-mimetic" "phase-II" "phase-III" "phenotype-like" "phenylarsine" "phenylcarbamothioyl" "phosphatidylinositol-3-OH" "phospho-STMN1" "phosphodegron" "phosphoinositide-3" "phosphoinositide-3-OH" "phospholipid-binding" "phosphopeptide" "phosphopeptide-PBD" "phosphopeptides" "phosphor-AKT" "phosphoribosyl" "phosphorylation-consensus" "phosphorylation-dephosphorylation" "phosphorylation‐deficient" "phospho‐MARCKS" "photo-ablation" "photo-thermal" "photodamage" "photoproducts" "phs000424" "phyllodes" "physician-records" "physio-pathological" "physiology-relevant" "picosecond" "pifithrin-α" "pig-3" "pilaris" "pixel" "planus" "plasmon" "plasticity-inducing" "plate-like" "platelet-tumour" "platform-is" "platins-pemetrexed" "platinum-doublet" "platinum-resistant" "plexiform" "pll3.7" "plug-in" "pluripotency-associated" "plus-end" "pmel-1" "pmiR-RB-REPORT" "pmk-1" "point-mutants" "polarization-based" "polo-like" "poly-A" "poly-ADP" "poly-SUMOylation" "poly-T" "polyI" "polyQ" "polySUMO" "polySUMO2" "polyglutamine-repeat" "polymerase1" "polymicrogyria-like" "polymorphism" "polymorphisms" "polyploid" "polypyrimidine" "poor-differentiation" "poor-prognosis" "poor-risk" "poor-switching" "poorer" "poorly-differentiated" "population-representative" "positron" "positron-emission" "post-IR" "post-PCR" "post-TGFβ" "post-TPF" "post-UVB" "post-analytic" "post-carboplatin" "post-dose" "post-elution" "post-exposure" "post-implantation" "post-incubation" "post-infection" "post-initiation" "post-injury" "post-irradiation" "post-menopausal" "post-mitotic" "post-natal" "post-operative" "post-ovulatory" "post-radiation" "post-reimplantation" "post-release" "post-replication" "post-replicative" "post-stimulation" "post-tamoxifen" "post-therapy" "post-transcription" "post-transcriptional" "post-transcriptionally" "post-transduction" "post-transfection" "post-translation" "post-translational" "post-translationally" "post-transplantation" "post-treatment" "post-wash" "postradiotherapy" "postsurgery" "post‐transcriptional" "precancer" "precancers" "preimmune" "pretreatmentDAB2IPreduction" "pri-miR-101" "pri-miR-138" "pri-miR-346" "pri-miR-622" "pri-miR-9" "pri-miR-9-1" "pri-miR-9-2" "pri-miR-9-3" "primary-response" "primer-pair" "prior-responders" "priori" "pro-IL-1β" "pro-MMP9" "pro-MT1-MMP" "pro-NHEJ" "pro-angiogenesis" "pro-angiogenic" "pro-apoptosis" "pro-autophagic" "pro-cancer" "pro-caspase-3" "pro-caspase-8" "pro-differentiation" "pro-drug" "pro-drugs" "pro-fibrogenesis" "pro-fibrogenic" "pro-fibrotic" "pro-fibrotic-related" "pro-growth" "pro-inflammatory" "pro-luc" "pro-lymphangiogenic" "pro-metastasis" "pro-metastatic" "pro-oncogene" "pro-oncogenes" "pro-proliferative" "pro-survival" "pro-tumor" "pro-tumoral" "pro-tumorigenic" "proband" "probands" "probe-sets" "procaspase-3" "profiler" "progeny" "progesterone-receptor" "progression-free-survival" "progression‐free" "proliferator-activated" "proline-glutamate-serine-threonine" "promoter-associated" "promoter-binding" "promoter-mediated" "proof-of-concept" "proof-of-principle" "prospectively-collected" "prostaglandins" "prostasphere" "prostaspheres" "prostatectomy" "prostate‐specific" "protease-14" "protein-1" "protein-2" "protein-72" "protein-DNA" "protein-RNA" "protein-level" "protein-like" "protein-sulfenic" "proteins" "protein‐2" "protein‐coding" "protein–27" "proteome" "proteomes" "proteomics-based" "proteosome" "proven" "pseudo-EMT" "pseudo-hypoxia" "pseudo-phosphorylated" "pseudo-phosphorylation" "pseudo-substrate" "pseudosubstrate" "psiCheck" "psiCheck‐2" "psoriacin" "psoriasis-like" "publically-available" "pull-down" "pull-downs" "pulldown" "pulled-down" "pulse-chase" "pur" "pur-α" "pur-α-rich" "pygl-1" "pyrrolo-pyrazole" "p " "p = 0.02" "p = 0.09" "q3dx4" "qPCR" "qPCR-HRM" "qRT‐PCR" "quality-of-life" "quencher" "quinazolin-3-one" "quinonoid" "radiation-induced" "radiation-sensitive" "radiation‐based" "radio-chemoresistance" "radio-resistance" "radio-sensitivity" "radio-therapy" "radioresistance" "radioresistant" "random-effects" "rank-ordered" "rapalogs" "rarer" "ras2" "re-analysis" "re-analyzed" "re-appearance" "re-assessed" "re-assessment" "re-challenge" "re-classified" "re-classifies" "re-confirm" "re-confirmed" "re-differentiated" "re-distribute" "re-distribution" "re-enable" "re-encountering" "re-endothelialization" "re-endothelialize" "re-entered" "re-entry" "re-epithelialization" "re-establish" "re-established" "re-establishment" "re-evaluate" "re-evaluated" "re-evaluation" "re-examination" "re-examine" "re-exposure" "re-expressed" "re-expressing" "re-expression" "re-growth" "re-induce" "re-induced" "re-infected" "re-infection" "re-initiate" "re-introduction" "re-localization" "re-operation" "re-overexpression" "re-plated" "re-polymerization" "re-probed" "re-programming" "re-seeded" "re-seeding" "re-sensitize" "re-sensitized" "re-sensitizes" "re-stained" "re-start" "re-suspension" "re-synthesis" "re-testing" "re-transferring" "re-transplantation" "re-treatment" "re-uptake" "reactions–a" "reactive-immunoassay" "read-out" "readout" "readouts" "real‐time" "receiver-operating" "receptor-alpha" "receptor-gamma" "receptor-ligand" "receptor-α" "recombination-deficient" "recut" "red-colored" "red-fluorescent" "reducedDAB2IPdemonstrated" "reducedDAB2IPhas" "reduction-oxidation" "ref" "refractoriness" "regrowth" "regulator-1" "regulatorUHRF1suppresses" "regulators" "regulatory-associated" "regulatory-binding" "relatedness" "releasate" "relocalise" "repair-defective" "repeat-containing" "repeats-containing" "replication-associated" "replication-blocking" "replication-competent" "replication-dependent" "replication-induced" "repopulate" "repressors" "reprogramming-like" "research-outcomes" "resp" "respective-length" "responder" "responders" "retainingDAB2IP" "retro" "retro-orbitally" "retro-viral" "retrovirally-transduced" "retrovirus" "revealedDAB2IP" "reverse-phase" "reverse-transcription" "rginine" "rhAPO2L" "rhApo2L" "rhSLURP1" "rhabdoid" "ribose" "ribose-5-phosphate" "ribulose-5-phosphate" "rich-cell" "right-handed" "right-sided" "ring-finger" "ring-like" "risk-reducing" "risk-reductive" "round-shaped" "round-to-elongated" "rpt6" "rs1042522" "rs1043618" "rs1061581" "rs1078806" "rs1078806-rs2420946-rs2981579-rs2981582" "rs1078806C-rs2420946T-rs2981579T-rs2981582T" "rs1078806T-rs2420946C-rs2981579C-rs2981582C" "rs11237477" "rs11571833" "rs11705932" "rs1219648" "rs12597021" "rs12699477" "rs13361707" "rs1421896" "rs144848" "rs149330805" "rs1748" "rs1799794" "rs1801132" "rs1801274" "rs1966265" "rs2018199" "rs2075158" "rs2075800" "rs2227956" "rs2234693" "rs2234909" "rs2273773" "rs2293347" "rs2293347G" "rs2293347GA" "rs2293347GG" "rs2293347 " "rs2293607" "rs2420946" "rs2420946T" "rs2450140" "rs2510044" "rs2511156" "rs2530223" "rs2547547" "rs25487" "rs2736098" "rs2736108" "rs2853669" "rs2867461" "rs2867461G" "rs2867461 " "rs2972388" "rs2981579" "rs2981579T" "rs2981582" "rs2981582T" "rs3135848" "rs32954" "rs351855" "rs3758391" "rs3859027" "rs396991" "rs412658" "rs41290601" "rs4561483" "rs55637647" "rs55870064" "rs61764370" "rs6457452" "rs689466" "rs7107174" "rs712" "rs7705526" "rs78378222" "rs861539" "rs9340799" "run-away" "run-on" "run-to-run" "s10689-015-9841-9" "s12881-015-0240-8" "s12885-015-1661-7" "s12885-015-1701-3" "s12885-015-1721-z" "s12885-015-1731-x" "s12885-015-1740-9" "s12885-015-1763-2" "s12885-015-1772-1" "s12885-015-1778-8" "s12885-015-1779-7" "s12885-015-1817-5" "s12885-015-1872-y" "s12885-015-1880-y" "s12885-015-1890-9" "s12890-015-0127-7" "s12929-015-0196-1" "s12931-015-0286-3" "s12967-015-0680-0" "s12967-015-0685-8" "s12967-015-0721-8" "s13045-015-0206-5" "s13046-015-0239-1" "s13058-015-0643-7" "s13059-015-0791-1" "s13075-015-0828-6" "s13742-015-0088-z" "sCD40L" "sHSP" "sHSPs" "sIL-6R" "sMaf" "sT-antigen" "sT-antigens" "sTantigen" "saliva-derived" "salpingo" "salpingo-oophorectomy" "sarcomatoid" "scaffolding-like" "scenarii" "scramble-shRNA-treated" "scratch-wound" "sd" "se" "second-degree" "second-generation" "second-largest" "second-line" "secretome" "selenol–thiol" "selenosulfide" "self-activating" "self-aggregate" "self-antigens" "self-association" "self-defense" "self-defensive" "self-degradative" "self-digestion" "self-eliminate" "self-interact" "self-interaction" "self-oligomerization" "self-phosphorylation" "self-protective" "self-renew" "self-renewal" "self-report" "self-sustaining" "self-tolerance" "semi" "semi-conductor" "semi-conservative" "semi-quantify" "semi-quantitative" "semi-solid" "senescence-like" "senescent-specific" "sensitizer" "sensitizers" "sequence-specific" "sequence-specifically" "sequestering-tubulin" "serine-2" "serine-to-alanine" "sessile" "set-up" "seventy-five" "severe-inflammatory" "sgRNA" "sh-POH1-Tet-on" "sh-miR-33a" "sh386" "sh848" "shACC1" "shACSL4" "shAPRT" "shATM" "shBcl" "shBcl-2" "shBcl-xL" "shBub1" "shBub1-#1" "shBub1-#2" "shCBL" "shCBL-Vector" "shCOPR5" "shCon" "shDNA-PK" "shDR5" "shERK" "shERK1" "shERβ" "shETV4" "shFOXO3-treated" "shFOXO3a" "shGFP" "shHIF-1α" "shHO-1" "shLuc" "shNSC" "shNT" "shPTEN" "shR-CBL" "shR-hTERT" "shRNA" "shRNA-vector" "shSUPT" "shSUPT5H" "shSUPT5H-1" "shSUPT5H-2" "shSUPT5H-3" "shScramble" "shUBASH" "shUBASH-1" "shUBASH-2" "shYAP#1" "sham-irradiated" "shockwaves" "short-chain" "short-hairpin" "short-interfering" "short-term" "short-time" "shorter-term" "shp53" "sh‐PIK3CA" "si-1" "si-2" "si-E2F1-1" "si-E2F1-2" "si-GAS5" "si-HULC-1" "si-HULC-2" "si-IκB-α" "si-SPHK1-1" "si-SPHK1-2" "si-Survivin" "siALK" "siCDH2" "siCtrl" "siGFP" "siIGF1R" "siISCU" "siISCU1" "siISCU2" "siMITF" "siNQO1" "siPRMT6" "siR-R" "siRASSF1" "siRASSF1A" "siRNA" "siRNA-1886" "siRNA-transfection" "siRNA1" "siRNA2" "siRNA‐mediated" "siSART3" "siUSP4-2" "sickle-Antilles-haemoglobin" "side-by-side" "side-chain" "side-chains" "side-effect" "side-effects" "side-population" "sigmoid" "signal-to-noise" "signalling-competent" "silencers" "silico" "simplest" "single-base" "single-cell" "single-center" "single-dose" "single-driver" "single-drug" "single-hit" "single-institution" "single-letter" "single-molecule" "single-nucleotide" "single-particle" "single-plex" "single-repeat" "single-site" "single-step" "single-strand" "sip53-treated" "sirtuin" "site-II" "situ" "six-gene" "six-oncogenic" "six-residue" "sixty-eight" "slow-growing" "slowed-down" "slower-migrating" "smMIPs" "small-GTP" "small-angle" "small-bowel" "small-cell" "small-molecule" "small-molecules" "small-nucleolar-RNA" "small-study" "smaller-sized" "smear-like" "smokers" "sodium-bicarbonate" "sodium-chloride" "sodium-dicarboxylate" "sodium-hydrogen" "sodium-induced" "sodium-proton" "soft-agar" "sotrastaurin" "spatial-temporal" "sphere-derived" "sphere-forming" "spheroid-induced" "sphingosine" "spike-in" "spiked-in" "spin-down" "spindle-assembly" "spindle-cell" "spindle-checkpoint" "spindle-like" "spindle-type" "spirometry" "splice-related" "spot-count" "spp" "ss" "ssDNA" "stably-infected" "standard-fat-diet" "standard-of-care" "state-of-the-art" "stathmin-like" "status-dependent" "steady-state" "stellate" "stem-cell" "stem-junction" "stem-like" "stem-line" "stem-loop" "stemloid" "stemness" "step-up" "step-wise" "stepwise" "sterol-response-element-binding" "stilbene" "stiposome" "stn-1" "strand-breaks" "strand-invasion" "stress-activated" "stress-adaptation" "stress-adaption" "stress-associated" "stress-dependent" "stress-induced" "stress-inducible" "stress-mediated" "stress-responding" "stress-responses" "stress-stimulated" "stressful" "stromal-derived" "stromal-epithelial" "structure-activity" "structure-based" "structure–activity" "structure–function" "study-entry" "sub-G1" "sub-G1-phase" "sub-Saharan" "sub-acute" "sub-analysis" "sub-capsular" "sub-categories" "sub-category" "sub-cellular" "sub-class" "sub-classification" "sub-classifications" "sub-clones" "sub-cohort" "sub-diploid" "sub-domains" "sub-effective" "sub-families" "sub-fractionation" "sub-group" "sub-groups" "sub-lethal" "sub-lineage" "sub-maximal" "sub-nanosecond" "sub-nuclear" "sub-optimal" "sub-pathway" "sub-pathways" "sub-population" "sub-populations" "sub-region" "sub-retinal" "sub-sets" "sub-telomeric" "sub-type" "sub-unit" "sub-units" "subG1" "subclasses" "subdomain" "subfamilies" "sublineage" "sublineages" "sublines" "submicron" "submucosa" "subpopulations" "subsequent-line" "subset" "subsets" "substituents" "substoichiometric-associated" "substrate-binding" "substrate-binding-site" "substrate-recognition" "substrate-site" "subtype" "succinate-dehydrogenase" "sulfhydryl" "sulfur-based" "super-expressor" "super-expressors" "super-high" "super-imposed" "superactivate" "supernatant" "supernatants" "suppressorDAB2IPis" "supra-maximal" "supra-physiological" "survivors" "swing-arm" "switching-loop" "sylvestris" "synapse" "syndrome-like" "synergism" "synonimous-synonimous" "synthases-PG" "synthesis-independent" "system-wide" "t-SNARE" "t-circles" "t-rpS6" "t-tpS6" "t0" "tATP" "tBHQ-treatment" "tag-SNPs" "take-rate" "tamoxifen-inducibleGli1" "tamoxifen-inducibleNestin" "tan-shinone" "tankyrase1" "target-DNA" "target-capture-based" "target-gene" "telencephalon" "telomerase-mediated" "telomere-proximal" "telomere-telomerase" "telomeric-repeat" "telomeropathies" "template-complementary" "ten-eleven" "tet-off" "teto-DTA" "tetranor-PGEM" "tetraplegia" "tetraploid" "thatUHRF1‐mediated" "the16-week-old" "theAKT3" "theCDKN2Atumour" "theDAB2IP" "theK" "theKEAP1gene" "theKEAP1promoter" "theLINE‐1promoter" "theMCF‐7" "thenPTB" "therapy-induced" "therapy-refractory" "therapy-specific" "thermo" "thermo-elastic" "thiazoline" "thick-walled" "thiol-containing" "thiol-disulfide" "third-largest" "third-line" "thirty-five" "three-dimensional" "three-finger" "three-letter" "three-or-more" "three-order" "three-stage" "three-step" "three-stranded" "three-tube" "threonine-specific" "thrombocythemia" "thrombus" "thymidine-adenine" "thymidine-to-guanine" "time-average" "time-course" "time-dependency" "time-dependently" "time-invariant" "time-lapse" "time-point" "time-points" "time-series" "timepoint" "times-points" "tissue-resident" "tissue-susceptibility" "tissues" "titers" "tm1044" "tm1944" "tm1Wjl" "to-mesenchymal" "to150" "toPhb2" "toll-like" "topology" "total-STAT3" "total-YAP1" "toxicants" "trade-off" "trans-cellular" "trans-membrane" "trans-regulatory" "trans-tail" "trans-well" "transcript-1" "transcript-specific" "transcription-1" "transcription-quantitative" "transcriptome" "transcriptomes" "transcriptome‐wide" "transducedPhb2" "transducer" "transducing-β-like" "transferase-1" "transformation-like" "transmembrane-4" "transporter-1" "transporter-mediated" "transwell-invasion" "transwells" "trastuzumab-chemotherapy" "trastuzumab-chemotherapy-resistant" "treated-cells" "treatment-naïve" "treatment-period" "tri-lineage" "tri-potency" "tri-potentiality" "trichrome" "tricuspid" "trifluorothiazoline" "trimester" "triphosphate" "triple-hit" "triple-negative" "triple-point-mutation" "triple-staining" "triple‐negative" "triptans" "trisomy" "trisphosphate" "troponin-1" "troponin-I" "trunk-branch" "tube-like" "tubule" "tubules" "tubulin-RhoA" "tubulinopathies" "tumor-adjacent" "tumor-agnostic" "tumor-cytokine-miRNA" "tumor-driver" "tumor-like" "tumor-permissive" "tumor-specificity" "tumor-sphere" "tumor-spheres" "tumor-supportive" "tumor-suppressive" "tumor-surveillance" "tumorDAB2IPstatus" "tumorosphere" "tumorospheres" "tumors" "tumour-based" "tumour-causing" "tumour-mediated" "tumour-promoting" "tumour-suppressive" "tumour-suppressor" "twenty-first" "twenty-five" "twenty-four" "twenty-seven" "twenty-six" "two-base" "two-binding" "two-carbon" "two-chamber" "two-class" "two-color" "two-gene" "two-hairpin" "two-hit" "two-hybrid" "two-photon" "two-pronged" "two-sided" "two-site" "two-step" "two-tailed" "two-thirds" "two-times" "two-way" "two-week" "tympanostomy" "type-1" "type-2" "type-I" "typhimurium" "tyrosine-15-phosphorylated" "tyrosine-phosphorylation-regulated" "ubiquitin-7-amido-4-methylcoumarin" "ubiquitin-proteasome-mediated" "ubiquitin-proteosome" "ubiquitin-thioester" "ubiquitously-expressed" "ubiqutin" "uc001ver" "ultra-deep" "ultra-low" "ultra-short" "ultrafine" "ultrastructure" "un" "und" "under-appreciated" "under-expressed" "under-participation" "under-replicated" "under-representation" "under-treatment" "undergoes" "undergone" "underpinnings" "undertaken" "uni" "univariate" "unmet" "up-regulator" "up-stream" "up-to-date" "up‐regulated" "up‐regulation" "urea" "urothelium" "usedPhb2" "users" "utero" "uveal" "v-SNARE–like" "v1" "v10" "v2" "v2.0" "v3.0" "v4.0" "v6" "vascular-disrupting" "vaso" "vaso-occlusive" "vehicle-treated" "vera" "vesico-ureteral" "vessel-like" "vessel-specific" "vestigial-like" "vi" "villi" "viremia" "virotherapy" "vis-a-vis" "vitro" "vivo" "voltage-gradients" "vs.1" "vs.10.0" "vs.12.0" "vs.14.0" "vs.TT" "v‐Ras" "water-soluble" "web-based" "website" "websites" "weeks" "well-accepted" "well-annotated" "well-balanced" "well-being" "well-conserved" "well-defined" "well-designed" "well-developed" "well-differentiated" "well-differentiation" "well-documented" "well-measured" "well-moderately" "well-preserved" "well-recognized" "well-structured" "well-studied" "well-suited" "well-tolerated" "well‐regulated" "whileOma1" "white-skinned" "whole-cell" "whole-exome" "whole-genome" "whole-tumour" "wide-scale" "wide-spread" "widely-expressed" "wild‐type" "with-no-lysine" "withNCCN" "wks" "work-up" "workers" "workflow" "world-wide" "wound‐healing" "written" "wt-p53" "wt-p53-Huh7.5.1" "wtEGFR" "wtp53" "x-ray" "x10" "xL" "xeno" "xeno-estrogens" "xeno-transplantation" "xenograft-transplantation" "yellow-brown" "yellow-colored" "yet-to-be-identified" "z-score" "z-scores" "zero-transformation" "zinc-induced" "zipper-EF-hand-containing" "×10" "×S" "× 10" "× 10" "÷14" "ɛ-amino" "ʹend" "Αn" "Δ148–314" "Δ169" "Δ245–373" "Δ31–147" "Δ385–543" "Δ5" "ΔC" "ΔC11" "ΔC3-7" "ΔC7" "ΔCD" "ΔCt" "ΔE5" "ΔE8" "ΔE9" "ΔIgG" "ΔKD-1" "ΔKD-2" "ΔLRR" "ΔM" "ΔN" "ΔUBL2" "Δm1" "Δm2" "ΔΨm" "Δψm" "ΦxΦΦΦ" "α-8-oxoguanine" "α-IL23" "α-KG" "α-Me-COOH" "α-MyHC" "α-aminophosphonate" "α-carbon" "α-defensin2" "α-enolase" "α-granule" "α-helical" "α-helices" "α-helix" "α-methyl" "α-methylated" "α-motif" "α-myc" "α-myosin" "α-toxin" "α-β" "α10" "α11" "α1a-tubulin" "α2β1" "α3" "α3β1" "α4" "α4β1" "α6" "α7-nAChR" "α7-nAChR-deficient" "α7-nAChR-mediated" "α7-nAChRs" "α7-nicotinic" "αv" "β-adrenergic" "β-adrenoceptor" "β-carbon" "β-cat" "β-catenin-YAP" "β-cateninaxis" "β-chain" "β-defensin2" "β-helixes" "β-lactose" "β-oxidation" "β-sheet" "β-sheets" "β-site" "β-strand" "β-sympathomimetics" "β-tubulins" "β1-strand" "β1AR" "β1–β2" "β2-Adrenergic" "β2-MG" "β2-adrenergic" "β3" "β3-strand" "β4" "β6" "β8" "βGal" "βeta-catenin" "β‐actin" "γ-H2A" "γ-aminobutyric" "γ-glutamyltransferase" "γ2" "γ3" "γH2aX" "δ-dependent" "ε-amino" "κB" "κt" "μM–30" "μW" "μg" "μg " "μl" "μmol" "χ²" "ϕH2AX" "кB" " 000" "↓and" "∆N151" "∆PAL" "∆Ψ" "−0.1" "△CT"))
75924737e1fcf173c82e8e49f4704ad44e5d19bae6b2544011452343b78377d8
dpapathanasiou/tweet-secret
core_test.clj
(ns tweet-secret.core-test (:require [clojure.test :refer :all] [tweet-secret.core :as core :refer :all] [tweet-secret.config :as config] [tweet-secret.utils :as utils] [tweet-secret.languages :as languages])) Test parameters for English (def english-dict '"/~ola/ap/linuxwords") (def english-corpus '"") (def english-messages '["Hit me baby"]) (def english-tweets '["If the lady loves her husband·, she does not love your Majesty." "I have made a small study of tattoo marks and have even· contributed to the literature of the subject." "It is in a German-speaking country--in Bohemia, not far from Ca·rlsbad."]) (deftest english-encode "This tests the encoding of an English-language message, using a static corpus from gutenberg.org, and a static, universally available dictionary text found online (rather than the linux words file as defined in config.properties, which can vary from distro to distro and computer to computer)." (testing "Encoding a message in English" (binding [core/*dictionary-text* (utils/slurp-url-or-file english-dict)] (let [eligible-tweets (core/get-eligible-tweets (core/parse-corpus core/*corpus-parse-fn* (core/load-corpus english-corpus)))] (is (not (nil? core/*dictionary-text*))) (is (= english-tweets (core/encode-plaintext (languages/en-tokenize-words english-messages) eligible-tweets))))))) (deftest english-decode "This tests the decoding of a series of English-language tweets, using a static corpus from gutenberg.org, and a static, universally available dictionary text found online (rather than the linux words file as defined in config.properties, which can vary from distro to distro and computer to computer). Since the encoding/decoding process does not preserve case in English, the output of the decode function is forced into lower case, to make sure the test passes if the only difference with the input is case." (testing "Decoding tweets back to the original English message" (binding [core/*dictionary-text* (utils/slurp-url-or-file english-dict)] (let [eligible-tweets (core/get-eligible-tweets (core/parse-corpus core/*corpus-parse-fn* (core/load-corpus english-corpus)))] (is (not (nil? core/*dictionary-text*))) (is (= (map #(clojure.string/lower-case %) (core/decode-tweets eligible-tweets english-tweets)) (map #(clojure.string/lower-case %) (languages/en-tokenize-words english-messages))))))))
null
https://raw.githubusercontent.com/dpapathanasiou/tweet-secret/764242341c03439aecf655fe8ca8e0384a25643f/test/tweet_secret/core_test.clj
clojure
(ns tweet-secret.core-test (:require [clojure.test :refer :all] [tweet-secret.core :as core :refer :all] [tweet-secret.config :as config] [tweet-secret.utils :as utils] [tweet-secret.languages :as languages])) Test parameters for English (def english-dict '"/~ola/ap/linuxwords") (def english-corpus '"") (def english-messages '["Hit me baby"]) (def english-tweets '["If the lady loves her husband·, she does not love your Majesty." "I have made a small study of tattoo marks and have even· contributed to the literature of the subject." "It is in a German-speaking country--in Bohemia, not far from Ca·rlsbad."]) (deftest english-encode "This tests the encoding of an English-language message, using a static corpus from gutenberg.org, and a static, universally available dictionary text found online (rather than the linux words file as defined in config.properties, which can vary from distro to distro and computer to computer)." (testing "Encoding a message in English" (binding [core/*dictionary-text* (utils/slurp-url-or-file english-dict)] (let [eligible-tweets (core/get-eligible-tweets (core/parse-corpus core/*corpus-parse-fn* (core/load-corpus english-corpus)))] (is (not (nil? core/*dictionary-text*))) (is (= english-tweets (core/encode-plaintext (languages/en-tokenize-words english-messages) eligible-tweets))))))) (deftest english-decode "This tests the decoding of a series of English-language tweets, using a static corpus from gutenberg.org, and a static, universally available dictionary text found online (rather than the linux words file as defined in config.properties, which can vary from distro to distro and computer to computer). Since the encoding/decoding process does not preserve case in English, the output of the decode function is forced into lower case, to make sure the test passes if the only difference with the input is case." (testing "Decoding tweets back to the original English message" (binding [core/*dictionary-text* (utils/slurp-url-or-file english-dict)] (let [eligible-tweets (core/get-eligible-tweets (core/parse-corpus core/*corpus-parse-fn* (core/load-corpus english-corpus)))] (is (not (nil? core/*dictionary-text*))) (is (= (map #(clojure.string/lower-case %) (core/decode-tweets eligible-tweets english-tweets)) (map #(clojure.string/lower-case %) (languages/en-tokenize-words english-messages))))))))
eb2e97819d649da346abfb0ec14c842de67cbde5d100d3ae2f957d9f493c2010
mmottl/gsl-ocaml
qrng_ex.ml
open Gsl let _ = let qrng = Qrng.make Qrng.SOBOL 2 in let tmp = Array.make 2 0. in for _i = 0 to 1023 do Qrng.get qrng tmp ; Printf.printf "%.5f %.5f\n" tmp.(0) tmp.(1) done
null
https://raw.githubusercontent.com/mmottl/gsl-ocaml/76f8d93cccc1f23084f4a33d3e0a8f1289450580/examples/qrng_ex.ml
ocaml
open Gsl let _ = let qrng = Qrng.make Qrng.SOBOL 2 in let tmp = Array.make 2 0. in for _i = 0 to 1023 do Qrng.get qrng tmp ; Printf.printf "%.5f %.5f\n" tmp.(0) tmp.(1) done
912bd088654dd685f4cece41a18829343c01b4bd13e14ebd58d34d98a4b6dad2
RefactoringTools/HaRe
FunIn2.expected.hs
module FunIn2 where --Any unused parameter to a definition can be removed. --In this example: remove the parameter 'x' to 'foo' inc :: Int -> Int foo :: Int foo = h + t where (h,t) = head $ zip [1..7] [3..15] inc x=x+1 main :: Int main = foo
null
https://raw.githubusercontent.com/RefactoringTools/HaRe/ef5dee64c38fb104e6e5676095946279fbce381c/test/testdata/RmOneParameter/FunIn2.expected.hs
haskell
Any unused parameter to a definition can be removed. In this example: remove the parameter 'x' to 'foo'
module FunIn2 where inc :: Int -> Int foo :: Int foo = h + t where (h,t) = head $ zip [1..7] [3..15] inc x=x+1 main :: Int main = foo
5a94cfdd753654cd0293c24fcc3b827a5f83f314a57e30a326e830c6ec3001ce
cyga/real-world-haskell
LocalReader.hs
file : ch18 / LocalReader.hs import Control.Monad.Reader myName step = do name <- ask return (step ++ ", I am " ++ name) localExample :: Reader String (String, String, String) localExample = do a <- myName "First" b <- local (++"dy") (myName "Second") c <- myName "Third" return (a, b, c)
null
https://raw.githubusercontent.com/cyga/real-world-haskell/4ed581af5b96c6ef03f20d763b8de26be69d43d9/ch18/LocalReader.hs
haskell
file : ch18 / LocalReader.hs import Control.Monad.Reader myName step = do name <- ask return (step ++ ", I am " ++ name) localExample :: Reader String (String, String, String) localExample = do a <- myName "First" b <- local (++"dy") (myName "Second") c <- myName "Third" return (a, b, c)
76143c595fca0896f31875c139c77c66220215eb11c7dc74ff8547d5ecfe183d
ferd/dlhttpc
webserver.erl
%%% ---------------------------------------------------------------------------- Copyright ( c ) 2009 , Erlang Training and Consulting Ltd. %%% All rights reserved. %%% %%% Redistribution and use in source and binary forms, with or without %%% modification, are permitted provided that the following conditions are met: %%% * Redistributions of source code must retain the above copyright %%% notice, this list of conditions and the following disclaimer. %%% * Redistributions in binary form must reproduce the above copyright %%% notice, this list of conditions and the following disclaimer in the %%% documentation and/or other materials provided with the distribution. * Neither the name of Erlang Training and Consulting Ltd. 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 Erlang Training and Consulting Ltd. ''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 Erlang Training and Consulting Ltd. BE %%% LIABLE 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. %%% ---------------------------------------------------------------------------- @author < > @author < > %%% @doc Simple web server for testing purposes %%% @end -module(webserver). -export([start/2, read_chunked/3]). -export([accept_connection/4]). start(Module, Responders) -> LS = listen(Module), spawn_link(?MODULE, accept_connection, [self(), Module, LS, Responders]), port(Module, LS). accept_connection(Parent, Module, ListenSocket, Responders) -> Socket = accept(Module, ListenSocket), server_loop(Module, Socket, nil, [], Responders), unlink(Parent). read_chunked(Module, Socket, Headers) -> Body = read_chunks(Module, Socket, []), ok = setopts(Module, Socket, [{packet, httph}]), Trailers = read_trailers(Module, Socket, Headers), % For next request ok = setopts(Module, Socket, [{packet, http}]), {Body, Trailers}. read_chunks(Module, Socket, Acc) -> ok = setopts(Module, Socket, [{packet, line}]), case Module:recv(Socket, 0) of {ok, HexSizeExtension} -> case chunk_size(HexSizeExtension, []) of 0 -> list_to_binary(lists:reverse(Acc)); Size -> setopts(Module, Socket, [{packet, raw}]), {ok, <<Chunk:Size/binary, "\r\n">>} = Module:recv(Socket, Size + 2), read_chunks(Module, Socket, [Chunk | Acc]) end; {error, Reason} -> erlang:error(Reason) end. read_trailers(Module, Socket, Hdrs) -> case Module:recv(Socket, 0) of {ok, {http_header, _, Name, _, Value}} when is_atom(Name) -> Trailer = {atom_to_list(Name), Value}, read_trailers(Module, Socket, [Trailer | Hdrs]); {ok, {http_header, _, Name, _, Value}} when is_list(Name) -> Trailer = {Name, Value}, read_trailers(Module, Socket, [Trailer | Hdrs]); {ok, http_eoh} -> Hdrs end. server_loop(Module, Socket, _, _, []) -> Module:close(Socket); server_loop(Module, Socket, Request, Headers, Responders) -> case Module:recv(Socket, 0) of {ok, {http_request, _, _, _} = NewRequest} -> server_loop(Module, Socket, NewRequest, Headers, Responders); {ok, {http_header, _, Field, _, Value}} when is_atom(Field) -> NewHeaders = [{atom_to_list(Field), Value} | Headers], server_loop(Module, Socket, Request, NewHeaders, Responders); {ok, {http_header, _, Field, _, Value}} when is_list(Field) -> NewHeaders = [{Field, Value} | Headers], server_loop(Module, Socket, Request, NewHeaders, Responders); {ok, http_eoh} -> RequestBody = case proplists:get_value("Content-Length", Headers) of undefined -> <<>>; "0" -> <<>>; SLength -> Length = list_to_integer(SLength), setopts(Module, Socket, [{packet, raw}]), {ok, Body} = Module:recv(Socket, Length), setopts(Module, Socket, [{packet, http}]), Body end, Responder = hd(Responders), Responder(Module, Socket, Request, Headers, RequestBody), server_loop(Module, Socket, none, [], tl(Responders)); {error, closed} -> Module:close(Socket) end. listen(ssl) -> Opts = [ {packet, http}, binary, {active, false}, {ip, {127,0,0,1}}, {verify,0}, {keyfile, "../test/key.pem"}, {certfile, "../test/crt.pem"} ], {ok, LS} = ssl:listen(0, Opts), LS; listen(Module) -> {ok, LS} = Module:listen(0, [ {packet, http}, binary, {active, false}, {ip, {127,0,0,1}} ]), LS. accept(ssl, ListenSocket) -> {ok, Socket} = ssl:transport_accept(ListenSocket, 10000), ok = ssl:ssl_accept(Socket), Socket; accept(Module, ListenSocket) -> {ok, Socket} = Module:accept(ListenSocket, 1000), Socket. setopts(ssl, Socket, Options) -> ssl:setopts(Socket, Options); setopts(_, Socket, Options) -> inet:setopts(Socket, Options). port(ssl, Socket) -> {ok, {_, Port}} = ssl:sockname(Socket), Port; port(_, Socket) -> {ok, Port} = inet:port(Socket), Port. chunk_size(<<$;, _/binary>>, Acc) -> erlang:list_to_integer(lists:reverse(Acc), 16); chunk_size(<<"\r\n">>, Acc) -> erlang:list_to_integer(lists:reverse(Acc), 16); chunk_size(<<Char, Rest/binary>>, Acc) -> chunk_size(Rest, [Char | Acc]).
null
https://raw.githubusercontent.com/ferd/dlhttpc/10726522af5a5df2ada91bb7c08fcfcc62fb7a4d/test/webserver.erl
erlang
---------------------------------------------------------------------------- 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. 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 Erlang Training and Consulting Ltd. ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE LIABLE 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. ---------------------------------------------------------------------------- @doc Simple web server for testing purposes @end For next request
Copyright ( c ) 2009 , Erlang Training and Consulting Ltd. * Neither the name of Erlang Training and Consulting Ltd. nor the IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL Erlang Training and Consulting Ltd. BE @author < > @author < > -module(webserver). -export([start/2, read_chunked/3]). -export([accept_connection/4]). start(Module, Responders) -> LS = listen(Module), spawn_link(?MODULE, accept_connection, [self(), Module, LS, Responders]), port(Module, LS). accept_connection(Parent, Module, ListenSocket, Responders) -> Socket = accept(Module, ListenSocket), server_loop(Module, Socket, nil, [], Responders), unlink(Parent). read_chunked(Module, Socket, Headers) -> Body = read_chunks(Module, Socket, []), ok = setopts(Module, Socket, [{packet, httph}]), Trailers = read_trailers(Module, Socket, Headers), ok = setopts(Module, Socket, [{packet, http}]), {Body, Trailers}. read_chunks(Module, Socket, Acc) -> ok = setopts(Module, Socket, [{packet, line}]), case Module:recv(Socket, 0) of {ok, HexSizeExtension} -> case chunk_size(HexSizeExtension, []) of 0 -> list_to_binary(lists:reverse(Acc)); Size -> setopts(Module, Socket, [{packet, raw}]), {ok, <<Chunk:Size/binary, "\r\n">>} = Module:recv(Socket, Size + 2), read_chunks(Module, Socket, [Chunk | Acc]) end; {error, Reason} -> erlang:error(Reason) end. read_trailers(Module, Socket, Hdrs) -> case Module:recv(Socket, 0) of {ok, {http_header, _, Name, _, Value}} when is_atom(Name) -> Trailer = {atom_to_list(Name), Value}, read_trailers(Module, Socket, [Trailer | Hdrs]); {ok, {http_header, _, Name, _, Value}} when is_list(Name) -> Trailer = {Name, Value}, read_trailers(Module, Socket, [Trailer | Hdrs]); {ok, http_eoh} -> Hdrs end. server_loop(Module, Socket, _, _, []) -> Module:close(Socket); server_loop(Module, Socket, Request, Headers, Responders) -> case Module:recv(Socket, 0) of {ok, {http_request, _, _, _} = NewRequest} -> server_loop(Module, Socket, NewRequest, Headers, Responders); {ok, {http_header, _, Field, _, Value}} when is_atom(Field) -> NewHeaders = [{atom_to_list(Field), Value} | Headers], server_loop(Module, Socket, Request, NewHeaders, Responders); {ok, {http_header, _, Field, _, Value}} when is_list(Field) -> NewHeaders = [{Field, Value} | Headers], server_loop(Module, Socket, Request, NewHeaders, Responders); {ok, http_eoh} -> RequestBody = case proplists:get_value("Content-Length", Headers) of undefined -> <<>>; "0" -> <<>>; SLength -> Length = list_to_integer(SLength), setopts(Module, Socket, [{packet, raw}]), {ok, Body} = Module:recv(Socket, Length), setopts(Module, Socket, [{packet, http}]), Body end, Responder = hd(Responders), Responder(Module, Socket, Request, Headers, RequestBody), server_loop(Module, Socket, none, [], tl(Responders)); {error, closed} -> Module:close(Socket) end. listen(ssl) -> Opts = [ {packet, http}, binary, {active, false}, {ip, {127,0,0,1}}, {verify,0}, {keyfile, "../test/key.pem"}, {certfile, "../test/crt.pem"} ], {ok, LS} = ssl:listen(0, Opts), LS; listen(Module) -> {ok, LS} = Module:listen(0, [ {packet, http}, binary, {active, false}, {ip, {127,0,0,1}} ]), LS. accept(ssl, ListenSocket) -> {ok, Socket} = ssl:transport_accept(ListenSocket, 10000), ok = ssl:ssl_accept(Socket), Socket; accept(Module, ListenSocket) -> {ok, Socket} = Module:accept(ListenSocket, 1000), Socket. setopts(ssl, Socket, Options) -> ssl:setopts(Socket, Options); setopts(_, Socket, Options) -> inet:setopts(Socket, Options). port(ssl, Socket) -> {ok, {_, Port}} = ssl:sockname(Socket), Port; port(_, Socket) -> {ok, Port} = inet:port(Socket), Port. chunk_size(<<$;, _/binary>>, Acc) -> erlang:list_to_integer(lists:reverse(Acc), 16); chunk_size(<<"\r\n">>, Acc) -> erlang:list_to_integer(lists:reverse(Acc), 16); chunk_size(<<Char, Rest/binary>>, Acc) -> chunk_size(Rest, [Char | Acc]).
386345d42cafc6a75f3f44b17f557da9d9f01c3ac3238b7b537908d59b7bf88d
uber/NEAL
swift_provider.ml
Copyright ( c ) 2017 Uber Technologies , Inc. (* *) (* Permission is hereby granted, free of charge, to any person obtaining a copy *) (* of this software and associated documentation files (the "Software"), to deal *) in the Software without restriction , including without limitation the rights (* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell *) copies of the Software , and to permit persons to whom the Software is (* furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included in *) all copies or substantial portions of the Software . (* *) THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *) (* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *) LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , (* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN *) (* THE SOFTWARE. *) open Neal exception Found let inherits_from ctx args = let aux () = match args with | [`String name] -> begin match List.assoc "TypeInheritanceClause" ctx.Ctx.props with | Absyn.List(typeInheritanceClause) -> begin List.iter (fun node -> match node with | Absyn.Node("TypeIdentifier",_,props) -> begin match List.assoc "TypeName" props with | Absyn.Node("Identifier",_,props) -> begin match List.assoc "Value" props with | Absyn.String str when str = name -> raise Found | _ -> () end | _ -> () end | _ -> () ) typeInheritanceClause end | _ -> () end | _ -> () in try aux (); `Bool false with Found -> `Bool true let () = Provider.register(module struct let name = "Swift" let extensions = [".swift"] let parse = Parser.parse let exported_macros = [ ("inheritsFrom", inherits_from) ] let exported_actions = [] end)
null
https://raw.githubusercontent.com/uber/NEAL/6a382a3f957c3bb4abe3f9aba9761ffef13fa5fe/src/providers/swift/swift_provider.ml
ocaml
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal to use, copy, modify, merge, publish, distribute, sublicense, and/or sell furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Copyright ( c ) 2017 Uber Technologies , Inc. in the Software without restriction , including without limitation the rights copies of the Software , and to permit persons to whom the Software is all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , open Neal exception Found let inherits_from ctx args = let aux () = match args with | [`String name] -> begin match List.assoc "TypeInheritanceClause" ctx.Ctx.props with | Absyn.List(typeInheritanceClause) -> begin List.iter (fun node -> match node with | Absyn.Node("TypeIdentifier",_,props) -> begin match List.assoc "TypeName" props with | Absyn.Node("Identifier",_,props) -> begin match List.assoc "Value" props with | Absyn.String str when str = name -> raise Found | _ -> () end | _ -> () end | _ -> () ) typeInheritanceClause end | _ -> () end | _ -> () in try aux (); `Bool false with Found -> `Bool true let () = Provider.register(module struct let name = "Swift" let extensions = [".swift"] let parse = Parser.parse let exported_macros = [ ("inheritsFrom", inherits_from) ] let exported_actions = [] end)
b0fb3e8d9a94466439c4a9f8b5963e92a61f2cb060ee51a9ecc89a446c5a6343
inhabitedtype/ocaml-aws
deleteUserGroup.ml
open Types open Aws type input = DeleteUserGroupMessage.t type output = UserGroup.t type error = Errors_internal.t let service = "elasticache" let signature_version = Request.V4 let to_http service region req = let uri = Uri.add_query_params (Uri.of_string (Aws.Util.of_option_exn (Endpoints.url_of service region))) (List.append [ "Version", [ "2015-02-02" ]; "Action", [ "DeleteUserGroup" ] ] (Util.drop_empty (Uri.query_of_encoded (Query.render (DeleteUserGroupMessage.to_query req))))) in `POST, uri, [] let of_http body = try let xml = Ezxmlm.from_string body in let resp = Util.option_bind (Xml.member "DeleteUserGroupResponse" (snd xml)) (Xml.member "DeleteUserGroupResult") in try Util.or_error (Util.option_bind resp UserGroup.parse) (let open Error in BadResponse { body; message = "Could not find well formed UserGroup." }) with Xml.RequiredFieldMissing msg -> let open Error in `Error (BadResponse { body ; message = "Error parsing UserGroup - missing field in body or children: " ^ msg }) with Failure msg -> `Error (let open Error in BadResponse { body; message = "Error parsing xml: " ^ msg }) let parse_error code err = let errors = [] @ Errors_internal.common in match Errors_internal.of_string err with | Some var -> if List.mem var errors && match Errors_internal.to_http_code var with | Some var -> var = code | None -> true then Some var else None | None -> None
null
https://raw.githubusercontent.com/inhabitedtype/ocaml-aws/b6d5554c5d201202b5de8d0b0253871f7b66dab6/libraries/elasticache/lib/deleteUserGroup.ml
ocaml
open Types open Aws type input = DeleteUserGroupMessage.t type output = UserGroup.t type error = Errors_internal.t let service = "elasticache" let signature_version = Request.V4 let to_http service region req = let uri = Uri.add_query_params (Uri.of_string (Aws.Util.of_option_exn (Endpoints.url_of service region))) (List.append [ "Version", [ "2015-02-02" ]; "Action", [ "DeleteUserGroup" ] ] (Util.drop_empty (Uri.query_of_encoded (Query.render (DeleteUserGroupMessage.to_query req))))) in `POST, uri, [] let of_http body = try let xml = Ezxmlm.from_string body in let resp = Util.option_bind (Xml.member "DeleteUserGroupResponse" (snd xml)) (Xml.member "DeleteUserGroupResult") in try Util.or_error (Util.option_bind resp UserGroup.parse) (let open Error in BadResponse { body; message = "Could not find well formed UserGroup." }) with Xml.RequiredFieldMissing msg -> let open Error in `Error (BadResponse { body ; message = "Error parsing UserGroup - missing field in body or children: " ^ msg }) with Failure msg -> `Error (let open Error in BadResponse { body; message = "Error parsing xml: " ^ msg }) let parse_error code err = let errors = [] @ Errors_internal.common in match Errors_internal.of_string err with | Some var -> if List.mem var errors && match Errors_internal.to_http_code var with | Some var -> var = code | None -> true then Some var else None | None -> None
ac061717b623461a4b14d6d27723aef0613d15bd0154df37cf343ec0245af318
sky-big/RabbitMQ
rabbit_authn_backend.erl
The contents of this file are subject to the Mozilla Public License %% Version 1.1 (the "License"); you may not use this file except in %% compliance with the License. You may obtain a copy of the License %% at / %% Software distributed under the License is distributed on an " AS IS " %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See %% the License for the specific language governing rights and %% limitations under the License. %% The Original Code is RabbitMQ . %% The Initial Developer of the Original Code is GoPivotal , Inc. Copyright ( c ) 2007 - 2014 GoPivotal , Inc. All rights reserved . %% -module(rabbit_authn_backend). -include("rabbit.hrl"). -ifdef(use_specs). %% Check a user can log in, given a username and a proplist of %% authentication information (e.g. [{password, Password}]). If your %% backend is not to be used for authentication, this should always %% refuse access. %% %% Possible responses: %% {ok, User} %% Authentication succeeded, and here's the user record. %% {error, Error} %% Something went wrong. Log and die. { refused , Msg , } %% Client failed authentication. Log and die. -callback user_login_authentication(rabbit_types:username(), [term()]) -> {'ok', rabbit_types:auth_user()} | {'refused', string(), [any()]} | {'error', any()}. -else. -export([behaviour_info/1]). behaviour_info(callbacks) -> [{user_login_authentication, 2}]; behaviour_info(_Other) -> undefined. -endif.
null
https://raw.githubusercontent.com/sky-big/RabbitMQ/d7a773e11f93fcde4497c764c9fa185aad049ce2/src/rabbit_authn_backend.erl
erlang
Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at / basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. Check a user can log in, given a username and a proplist of authentication information (e.g. [{password, Password}]). If your backend is not to be used for authentication, this should always refuse access. Possible responses: {ok, User} Authentication succeeded, and here's the user record. {error, Error} Something went wrong. Log and die. Client failed authentication. Log and die.
The contents of this file are subject to the Mozilla Public License Software distributed under the License is distributed on an " AS IS " The Original Code is RabbitMQ . The Initial Developer of the Original Code is GoPivotal , Inc. Copyright ( c ) 2007 - 2014 GoPivotal , Inc. All rights reserved . -module(rabbit_authn_backend). -include("rabbit.hrl"). -ifdef(use_specs). { refused , Msg , } -callback user_login_authentication(rabbit_types:username(), [term()]) -> {'ok', rabbit_types:auth_user()} | {'refused', string(), [any()]} | {'error', any()}. -else. -export([behaviour_info/1]). behaviour_info(callbacks) -> [{user_login_authentication, 2}]; behaviour_info(_Other) -> undefined. -endif.
79e003e9086a9fc84d492ce0a4b288d8046e731bff99a46ff2d5e4935049e6e2
hanshuebner/pixelisp
gallery.lisp
;; -*- Lisp -*- (defpackage :gallery (:use :cl :alexandria) (:export #:play #:playlist #:make-gif-pathname #:import-gif #:chill-factor #:settings)) (in-package :gallery) (defparameter *gifs-directory* #P"gifs/") (storage:defconfig 'playlist nil) (storage:defconfig 'animation-show-time 15) (storage:defconfig 'chill-factor 2) (defun playlist () (storage:config 'playlist)) (defun (setf playlist) (new) (setf (storage:config 'playlist) new) new) (defun load-animation (file) (cl-log:log-message :info "Loading ~A" file) (handler-case (display:load-gif file :chill-factor (storage:config 'chill-factor)) (error (e) (cl-log:log-message :error "Error loading animation ~A~%~A~%" file e) (sleep .5)))) (defun make-gif-pathname (name) (make-pathname :name name :defaults (make-pathname :type (and name "gif") :defaults *gifs-directory*))) (defclass playlist () ((animation-files :initform nil :reader animation-files))) (defgeneric changedp (playlist)) (defmethod initialize-instance :after ((playlist playlist) &key) (cl-log:log-message :info "playing ~A with ~D animations" (type-of playlist) (length (animation-files playlist)))) (defclass all-animations-playlist (playlist) ((last-update :reader last-update :initform (file-write-date (make-gif-pathname nil))))) (defmethod initialize-instance :before ((playlist all-animations-playlist) &key) (let ((*random-state* (make-random-state t))) (setf (slot-value playlist 'animation-files) (alexandria:shuffle (directory #P"gifs/*.gif"))))) (defmethod changedp ((playlist all-animations-playlist)) (/= (last-update playlist) (file-write-date (make-gif-pathname nil)))) (defclass user-playlist (playlist) ((animation-names :reader animation-names))) (defmethod initialize-instance :before ((playlist user-playlist) &key) (with-slots (animation-names animation-files) playlist (setf animation-names (playlist) animation-files (remove-if-not #'probe-file (mapcar #'make-gif-pathname animation-names))))) (defmethod changedp ((playlist user-playlist)) (not (equal (animation-names playlist) (playlist)))) (defun playlist-class () (if (playlist) 'user-playlist 'all-animations-playlist)) (defun check-playlist-changed (playlist) (when (or (not (typep playlist (playlist-class))) (changedp playlist)) (cl-log:log-message :debug "restarting because of playlist change") (invoke-restart 'app:start))) (defun shift-randomly (list) (let ((size (length list))) (if (= size 1) list (let ((split-at (random size))) (concatenate 'list (subseq list split-at) (subseq list 0 split-at)))))) (defun play () (loop (with-simple-restart (app:start "Fresh start") (loop with playlist = (make-instance (playlist-class)) with current-animation with animation-files = (shift-randomly (animation-files playlist)) with single-file-paylist-p = (= (length animation-files) 1) do (loop for file in animation-files for animation-show-time = (storage:config 'animation-show-time) for animation-end-time = (+ (get-universal-time) animation-show-time) do (check-playlist-changed playlist) (when (or (not current-animation) (not single-file-paylist-p)) (setf current-animation (load-animation file)) (messaging:send :display :set-animation current-animation)) (loop for first-start-p = t then nil for remaining-time = (- animation-end-time (get-universal-time)) while (plusp remaining-time) do (with-simple-restart (app:resume "Resume playing") (cl-log:log-message :debug "remaining animation time: ~:D seconds" remaining-time) (when (or (not first-start-p) single-file-paylist-p) (messaging:send :display :set-animation current-animation)) (sleep remaining-time)) finally (when (and single-file-paylist-p (not (plusp remaining-time))) (messaging:send :display :set-animation current-animation)))))))) (defun import-gif (input-file output-file) (handler-case (utils:run-program "gifsicle" "--resize" "_x16" "-i" (namestring input-file) "-o" (namestring output-file)) (error (e) (cl-log:log-message :error "Error importing ~A to ~A: ~A" input-file output-file e)))) (hunchentoot:define-easy-handler (load-gif :uri "/load-gif") (name) (messaging:send :display :set-animation (display:load-gif (make-gif-pathname name))) "loaded") (hunchentoot:define-easy-handler (delete-gif :uri "/delete-gif") (name) (cond ((eq (hunchentoot:request-method*) :post) (delete-file (make-gif-pathname name)) (format t "image ~A deleted" name)) (t (error "invalid request method, need POST")))) (hunchentoot:define-easy-handler (gallery-playlist :uri "/gallery/playlist") () (when (eq (hunchentoot:request-method*) :post) (let ((body (hunchentoot:raw-post-data :force-text t))) (cl-log:log-message :debug "POST body: ~S" body) (setf (playlist) (yason:parse body)))) (setf (hunchentoot:content-type*) "application/json") (with-output-to-string (s) (yason:encode (playlist) s))) (defun parse-float (string) (float (parse-number:parse-positive-real-number string))) (hunchentoot:define-easy-handler (chill :uri "/gallery/chill") ((factor :parameter-type 'parse-float)) (when (eq (hunchentoot:request-method*) :post) (check-type factor (float 0.0 5.0)) (setf (storage:config 'chill-factor) factor) (when-let (animation (display:current-animation)) (setf (display:chill-factor animation) factor))) (format nil "chill factor ~A" (storage:config 'chill-factor)))
null
https://raw.githubusercontent.com/hanshuebner/pixelisp/b4ccde622e85c0131515101989b4cdddae15c0c9/src/gallery.lisp
lisp
-*- Lisp -*-
(defpackage :gallery (:use :cl :alexandria) (:export #:play #:playlist #:make-gif-pathname #:import-gif #:chill-factor #:settings)) (in-package :gallery) (defparameter *gifs-directory* #P"gifs/") (storage:defconfig 'playlist nil) (storage:defconfig 'animation-show-time 15) (storage:defconfig 'chill-factor 2) (defun playlist () (storage:config 'playlist)) (defun (setf playlist) (new) (setf (storage:config 'playlist) new) new) (defun load-animation (file) (cl-log:log-message :info "Loading ~A" file) (handler-case (display:load-gif file :chill-factor (storage:config 'chill-factor)) (error (e) (cl-log:log-message :error "Error loading animation ~A~%~A~%" file e) (sleep .5)))) (defun make-gif-pathname (name) (make-pathname :name name :defaults (make-pathname :type (and name "gif") :defaults *gifs-directory*))) (defclass playlist () ((animation-files :initform nil :reader animation-files))) (defgeneric changedp (playlist)) (defmethod initialize-instance :after ((playlist playlist) &key) (cl-log:log-message :info "playing ~A with ~D animations" (type-of playlist) (length (animation-files playlist)))) (defclass all-animations-playlist (playlist) ((last-update :reader last-update :initform (file-write-date (make-gif-pathname nil))))) (defmethod initialize-instance :before ((playlist all-animations-playlist) &key) (let ((*random-state* (make-random-state t))) (setf (slot-value playlist 'animation-files) (alexandria:shuffle (directory #P"gifs/*.gif"))))) (defmethod changedp ((playlist all-animations-playlist)) (/= (last-update playlist) (file-write-date (make-gif-pathname nil)))) (defclass user-playlist (playlist) ((animation-names :reader animation-names))) (defmethod initialize-instance :before ((playlist user-playlist) &key) (with-slots (animation-names animation-files) playlist (setf animation-names (playlist) animation-files (remove-if-not #'probe-file (mapcar #'make-gif-pathname animation-names))))) (defmethod changedp ((playlist user-playlist)) (not (equal (animation-names playlist) (playlist)))) (defun playlist-class () (if (playlist) 'user-playlist 'all-animations-playlist)) (defun check-playlist-changed (playlist) (when (or (not (typep playlist (playlist-class))) (changedp playlist)) (cl-log:log-message :debug "restarting because of playlist change") (invoke-restart 'app:start))) (defun shift-randomly (list) (let ((size (length list))) (if (= size 1) list (let ((split-at (random size))) (concatenate 'list (subseq list split-at) (subseq list 0 split-at)))))) (defun play () (loop (with-simple-restart (app:start "Fresh start") (loop with playlist = (make-instance (playlist-class)) with current-animation with animation-files = (shift-randomly (animation-files playlist)) with single-file-paylist-p = (= (length animation-files) 1) do (loop for file in animation-files for animation-show-time = (storage:config 'animation-show-time) for animation-end-time = (+ (get-universal-time) animation-show-time) do (check-playlist-changed playlist) (when (or (not current-animation) (not single-file-paylist-p)) (setf current-animation (load-animation file)) (messaging:send :display :set-animation current-animation)) (loop for first-start-p = t then nil for remaining-time = (- animation-end-time (get-universal-time)) while (plusp remaining-time) do (with-simple-restart (app:resume "Resume playing") (cl-log:log-message :debug "remaining animation time: ~:D seconds" remaining-time) (when (or (not first-start-p) single-file-paylist-p) (messaging:send :display :set-animation current-animation)) (sleep remaining-time)) finally (when (and single-file-paylist-p (not (plusp remaining-time))) (messaging:send :display :set-animation current-animation)))))))) (defun import-gif (input-file output-file) (handler-case (utils:run-program "gifsicle" "--resize" "_x16" "-i" (namestring input-file) "-o" (namestring output-file)) (error (e) (cl-log:log-message :error "Error importing ~A to ~A: ~A" input-file output-file e)))) (hunchentoot:define-easy-handler (load-gif :uri "/load-gif") (name) (messaging:send :display :set-animation (display:load-gif (make-gif-pathname name))) "loaded") (hunchentoot:define-easy-handler (delete-gif :uri "/delete-gif") (name) (cond ((eq (hunchentoot:request-method*) :post) (delete-file (make-gif-pathname name)) (format t "image ~A deleted" name)) (t (error "invalid request method, need POST")))) (hunchentoot:define-easy-handler (gallery-playlist :uri "/gallery/playlist") () (when (eq (hunchentoot:request-method*) :post) (let ((body (hunchentoot:raw-post-data :force-text t))) (cl-log:log-message :debug "POST body: ~S" body) (setf (playlist) (yason:parse body)))) (setf (hunchentoot:content-type*) "application/json") (with-output-to-string (s) (yason:encode (playlist) s))) (defun parse-float (string) (float (parse-number:parse-positive-real-number string))) (hunchentoot:define-easy-handler (chill :uri "/gallery/chill") ((factor :parameter-type 'parse-float)) (when (eq (hunchentoot:request-method*) :post) (check-type factor (float 0.0 5.0)) (setf (storage:config 'chill-factor) factor) (when-let (animation (display:current-animation)) (setf (display:chill-factor animation) factor))) (format nil "chill factor ~A" (storage:config 'chill-factor)))
1d40ca63be0f706310873aa51354d15b972920495ad0e04222cf567bf8329fe9
bluemont/kria
schema_get.clj
(defn conn-cb [asc e a] (println (if e e "connected"))) (def conn (client/connect "127.0.0.1" 8087 conn-cb)) (schema/get conn "S-600" result-cb) (keys @result) ; (:schema) (keys (:schema @result)) ; (:name :content) (-> @result :schema :name) ; "S-600" (print (-> @result :schema :content))
null
https://raw.githubusercontent.com/bluemont/kria/8ed7fb1ebda8bfa1a2a6d7a3acf05e2255fcf0f0/doc/examples/schema_get.clj
clojure
(:schema) (:name :content) "S-600"
(defn conn-cb [asc e a] (println (if e e "connected"))) (def conn (client/connect "127.0.0.1" 8087 conn-cb)) (schema/get conn "S-600" result-cb) (print (-> @result :schema :content))
fe3ad95318dc05e8b53b522685ae99186b0fc50c6103c1fb7c3db1d2ff01f95b
nklein/userial
serialize.lisp
Copyright ( c ) 2011 nklein software MIT License . See included LICENSE.txt file for licensing details . (in-package :userial) ;;; serialize generic function (contextl:define-layered-function serialize (type value &key &allow-other-keys) (:documentation "Method used to serialize a VALUE of given TYPE into BUFFER") (:method (type value &key &allow-other-keys) "There is no default way to serialize something, so chuck an error." (declare (ignore value)) (error "SERIALIZE not supported for type ~A" type))) ;;; unserialize generic function (contextl:define-layered-function unserialize (type &key &allow-other-keys) (:documentation "Method used to unserialize a value of given TYPE from BUFFER") (:method (type &key &allow-other-keys) "There is no default way to unserialize something, so chuck an error." (error "UNSERIALIZE not supported for type ~A" type))) (defmacro serialize* (&rest type-value-pairs) "SERIALIZE a list of TYPE + VALUE into BUFFER returning the final BUFFER. For example: (SERIALIZE* :UINT8 5 :INT16 -10)" (multiple-value-bind (vars types values) (get-syms-types-places type-value-pairs) (declare (ignore vars)) `(progn ,@(mapcar #'(lambda (tt vv) `(serialize ,tt ,vv)) types values)))) (defmacro serialize-slots* (object &rest type-slot-plist) (let ((obj-sym (gensym "OBJ-"))) (labels ((do-slot (tt ss) `(,tt (when (slot-boundp ,obj-sym ',ss) (slot-value ,obj-sym ',ss))))) (multiple-value-bind (vars types slots) (get-syms-types-places type-slot-plist) (declare (ignore vars)) `(let ((,obj-sym ,object)) (serialize* ,@(loop :for tt :in types :for ss :in slots :appending (do-slot tt ss)))))))) (defmacro serialize-accessors* (object &rest type-accessor-plist) (multiple-value-bind (vars types accessors) (get-syms-types-places type-accessor-plist) `(with-accessors ,(mapcar #'quote-2 vars accessors) ,object (serialize* ,@(apply #'append (mapcar #'quote-2 types vars)))))) (defmacro unserialize* (&rest type-place-plist) "UNSERIALIZE a list of TYPE + PLACE from the given BUFFER and execute the body. For example: (LET (AA BB) (UNSERIALIZE* :UINT8 AA :INT16 BB) (LIST AA BB))" (multiple-value-bind (vars types places) (get-syms-types-places type-place-plist) (declare (ignore vars)) `(setf ,@(apply #'append (mapcar #'(lambda (tt pp) `(,pp (unserialize ,tt))) types places))))) (defmacro unserialize-slots* (object &rest type-slot-plist) (multiple-value-bind (vars types slots) (get-syms-types-places type-slot-plist) (let ((obj (gensym "OBJ-"))) `(let ((,obj ,object)) (with-slots ,(mapcar #'quote-2 vars slots) ,obj (unserialize* ,@(apply #'append (mapcar #'quote-2 types vars)))) ,obj)))) (defmacro unserialize-accessors* (object &rest type-accessor-plist) (multiple-value-bind (vars types accessors) (get-syms-types-places type-accessor-plist) (let ((obj (gensym "OBJ-"))) `(let ((,obj ,object)) (with-accessors ,(mapcar #'quote-2 vars accessors) ,obj (unserialize* ,@(apply #'append (mapcar #'quote-2 types vars))) ,obj))))) (defmacro unserialize-let* ((&rest type-var-plist) &body body) "UNSERIALIZE a list of TYPE + VARIABLE-NAME from the given BUFFER and execute the body. For example: (UNSERIALIZE-LET* (:UINT8 AA :INT16 BB) (LIST AA BB))" (multiple-value-bind (vars types places) (get-syms-types-places type-var-plist) (declare (ignore vars)) `(let* (,@(mapcar #'(lambda (pp tt) `(,pp (unserialize ,tt))) places types)) (values (progn ,@body) *buffer*)))) (defun unserialize-list* (types) "UNSERIALIZE a list of types from the given BUFFER into a list. For example: (MAPCAR #'PRINC (UNSERIALIZE-LIST* '(:UINT8 :INT16) :BUFFER BUFFER))" (values (mapcar #'(lambda (tt) (unserialize tt)) types) *buffer*)) ;; help define a serializer (defmacro define-serializer ((key value &key layer extra) &body body) (let ((keysym (gensym "KEY-"))) `(contextl:define-layered-method serialize ,@(when layer `(:in-layer ,layer)) ((,keysym (eql ,key)) ,value &key ,@extra &allow-other-keys) (declare (ignore ,keysym)) ,@body *buffer*))) ;; help define an unserializer (defmacro define-unserializer ((key &key layer extra) &body body) (multiple-value-bind (decls body) (userial::separate-docstring-and-decls body) (let ((keysym (gensym "KEY-"))) `(contextl:define-layered-method unserialize ,@(when layer `(:in-layer ,layer)) ((,keysym (eql ,key)) &key ,@extra &allow-other-keys) ,@decls (declare (ignore ,keysym)) (values (progn ,@body) *buffer*))))) ;;; help build integer serialize/unserialize methods (defmacro make-uint-serializer (key bytes &key layer) "Make SERIALIZE/UNSERIALIZE methods for an unsigned-int of BYTES bytes in length dispatched by KEY." `(progn (define-serializer (,key value :layer ,layer) (declare (type (unsigned-byte ,(* bytes 8)) value) (optimize (speed 3))) (unroll-add-bytes value ,bytes)) (define-unserializer (,key :layer ,layer) (declare (optimize (speed 3))) (unroll-get-bytes ,bytes)))) ;;; define standard unsigned-int serialize/deserialize methods (make-uint-serializer :uint8 1) (make-uint-serializer :uint16 2) (make-uint-serializer :uint24 3) (make-uint-serializer :uint32 4) (make-uint-serializer :uint48 6) (make-uint-serializer :uint64 8) ;;; progressively stored unsigned integers (define-serializer (:uint value) (declare (type (integer 0 *) value) (optimize (speed 3))) (labels ((store-bytes (vv) (declare (type (integer 0 *) vv)) (multiple-value-bind (high low) (floor vv 128) (declare (type (integer 0 *) high) (type (integer 0 127) low)) (cond ((zerop high) (serialize :uint8 low)) (t (serialize :uint8 (+ low 128)) (store-bytes high)))))) (store-bytes value))) (define-unserializer (:uint) (declare (optimize (speed 3))) (labels ((fetch-bytes (&optional (vv 0) (offset 1)) (declare (type (integer 0 *) vv) (type (integer 1 *) offset)) (unserialize-let* (:uint8 byte) (flet ((add (bb) (+ vv (* bb offset)))) (cond ((< byte 128) (add byte)) (t (fetch-bytes (add (- byte 128)) (* offset 128)))))))) (fetch-bytes))) (defmacro twos-complement (val bytes) `(1+ (logxor ,val ,(1- (expt 2 (* bytes 8)))))) (defmacro make-int-serializer (key bytes &key layer) "Make SERIALIZE/UNSERIALIZE methods for a signed-int of BYTES bytes in length dispatched by KEY." (let ((vv (gensym "VV-"))) `(progn (define-serializer (,key value :layer ,layer) (declare (type (signed-byte ,(* bytes 8)) value) (optimize (speed 3))) (let ((,vv (if (minusp value) (twos-complement (- value) ,bytes) value))) (unroll-add-bytes ,vv ,bytes))) (define-unserializer (,key :layer ,layer) (declare (optimize (speed 3))) (let ((,vv (unroll-get-bytes ,bytes))) (declare (type (unsigned-byte ,(* bytes 8)) ,vv)) (if (logbitp ,(1- (* bytes 8)) ,vv) (- (twos-complement ,vv ,bytes)) ,vv)))))) ;;; define standard signed-int serialize/deserialize methods (make-int-serializer :int8 1) (make-int-serializer :int16 2) (make-int-serializer :int32 4) (make-int-serializer :int64 8) (define-serializer (:int value) (declare (type integer value) (optimize (speed 3))) (flet ((store-and-go (vv sign) (multiple-value-bind (high low) (floor vv 64) (cond ((zerop high) (serialize :uint8 (+ low sign))) (t (serialize :uint8 (+ low sign 64)) (serialize :uint high)))))) (cond ((minusp value) (store-and-go (- value) 128)) (t (store-and-go value 0))))) (define-unserializer (:int) (declare (optimize (speed 3))) (flet ((get-number (vv) (cond ((<= 64 vv) (+ (* (unserialize :uint) 64) (- vv 64))) (t vv)))) (declare (ftype (function (uint) uint) get-number)) (let ((byte (unserialize :uint8))) (declare (type uchar byte)) (cond ((<= 128 byte) (- (get-number (- byte 128)))) (t (get-number byte)))))) ;;; floating-point type helper (defmacro make-float-serializer (key type bytes encoder decoder &key layer) "Make serialize/unserialize routines for floating-point type TYPE dispatched by KEY with the given number of BYTES and an ENCODER/DECODER pair." (let ((vv (gensym "VV-"))) `(progn (define-serializer (,key value :layer ,layer) (declare (type ,type value) (optimize (speed 3))) (unroll-add-bytes (,encoder value) ,bytes)) (define-unserializer (,key :layer ,layer) (declare (optimize (speed 3))) (let ((,vv (unroll-get-bytes ,bytes))) (declare (type (unsigned-byte ,(* bytes 8)) ,vv)) (,decoder ,vv)))))) ;;; floating-point type serializers/deserializers (make-float-serializer :float32 single-float 4 ieee-floats:encode-float32 ieee-floats:decode-float32) (make-float-serializer :float64 double-float 8 ieee-floats:encode-float64 ieee-floats:decode-float64) ;;; byte arrays without size encoded with them (define-serializer (:raw-bytes value :extra ((start 0) (end (length value)))) (declare (type (vector (unsigned-byte 8)) value)) (assert (<= 0 start end (length value))) (let ((length (- end start)) (buf-start (buffer-length))) (buffer-advance length) (setf (subseq *buffer* buf-start (buffer-length)) (subseq value start end)))) (define-unserializer (:raw-bytes :extra (output (start 0) (end (length output)))) (assert (<= 0 start end)) (let* ((length (- end start)) (buf-start (buffer-length)) (output (or output (make-array (list length) :initial-element 0 :element-type '(unsigned-byte 8))))) (declare (type (vector (unsigned-byte 8)) output)) (assert (<= end (length output))) (buffer-advance length) (setf (subseq output start end) (subseq *buffer* buf-start (buffer-length))) output)) ;;; byte arrays with size (define-serializer (:bytes value) (declare (type (vector (unsigned-byte 8)) value)) (serialize :uint (length value)) (serialize :raw-bytes value)) (define-unserializer (:bytes) (unserialize-let* (:uint length) (let ((value (make-array (list length) :initial-element 0 :element-type '(unsigned-byte 8)))) (unserialize :raw-bytes :output value)))) ;;; string handling (define-serializer (:string value) (declare (type string value)) (serialize :bytes (trivial-utf-8:string-to-utf-8-bytes value))) (define-unserializer (:string) (let ((value (unserialize :bytes))) (declare (type (vector (unsigned-byte 8)) value)) (trivial-utf-8:utf-8-bytes-to-string value))) ;;; enum helper (defmacro make-enum-serializer (type (&rest choices) &key layer (minimum-bytes 0)) "Create serialize/unserialize methods keyed by TYPE where the possible values are given by CHOICES" (let ((bytes (max (nth-value 0 (ceiling (log (length choices) 256))) minimum-bytes))) `(progn (define-serializer (,type value :layer ,layer) (declare (type symbol value)) (let ((value (ecase value ,@(loop :for ii :from 0 :for vv :in choices :collecting (list (if vv vv '(nil)) ii))))) (declare (type (unsigned-byte ,(* bytes 8)) value)) (unroll-add-bytes value ,bytes))) (define-unserializer (,type :layer ,layer) (let ((value (unroll-get-bytes ,bytes))) (declare (type (unsigned-byte ,(* bytes 8)) value)) (let ((value (ecase value ,@(loop :for ii :from 0 :for vv :in choices :collecting (list ii `',vv))))) (declare (type symbol value)) value)))))) ;;; define standard enum methods (make-enum-serializer :boolean (nil t)) (defmacro make-bitfield-serializer (type (&rest choices) &key layer) "Create serialize/unserialize methods keyed by TYPE where the CHOICES can either be specified singly or as a list." (let ((bytes (nth-value 0 (ceiling (length choices) 8)))) `(progn (define-serializer (,type (value cons) :layer ,layer) (declare (type cons value)) (let ((val (reduce #'(lambda (acc &optional sym) (logior acc (ecase sym ,@(loop :for ii :from 0 :for vv :in choices :collecting (list vv (expt 2 ii)))))) value :initial-value 0))) (declare (type (unsigned-byte ,(* bytes 8)) val)) (unroll-add-bytes val ,bytes))) (define-serializer (,type (value symbol) :layer ,layer) (declare (type symbol value)) (let ((val (ecase value ((nil) 0) ,@(loop :for ii :from 0 :for vv :in choices :collecting (list vv (expt 2 ii)))))) (declare (type (unsigned-byte ,(* bytes 8)) val)) (unroll-add-bytes val ,bytes))) (define-unserializer (,type :layer ,layer) (let ((value (unroll-get-bytes ,bytes))) (declare (type (unsigned-byte ,(* bytes 8)) value)) (assert (< value ,(expt 2 (length choices)))) (loop :for ii :from 0 :below ,(length choices) :when (plusp (logand value (expt 2 ii))) :collect (svref (vector ,@(mapcar #'(lambda (cc) `',cc) choices)) ii))))))) (defmacro make-simple-serializer ((type value factory &key layer extra) &rest pairs) `(progn (define-serializer (,type ,value :layer ,layer :extra extra) (serialize* ,@pairs)) (define-unserializer (,type :layer ,layer :extra ((,value ,factory) ,@extra)) (unserialize* ,@pairs)))) (defmacro make-slot-serializer ((type value factory &key layer) &rest fields) "Make a serialize/unserialize pair with given TYPE using the FACTORY form when a new instance is needed where FIELDS is a list of key/slot values. For example: (defstruct person name (age 0)) (make-slot-serializer (:person person buffer (make-person)) :string name :uint8 age)" `(progn (define-serializer (,type ,value :layer ,layer) (serialize-slots* ,value ,@fields)) (define-unserializer (,type :layer ,layer :extra ((,value ,factory))) (unserialize-slots* ,value ,@fields) ,value))) (defmacro make-accessor-serializer ((type value factory &key layer) &rest fields) "Make a serialize/unserialize pair with given TYPE using the FACTORY form when a new instance is needed where FIELDS is a list of key/accessor values. For example: (defstruct person name (age 0)) (make-accessor-serializer (:person person buffer (make-person)) :string person-name :uint8 person-age)" `(progn (define-serializer (,type ,value :layer ,layer) (serialize-accessors* ,value ,@fields)) (define-unserializer (,type :layer ,layer :extra ((,value ,factory))) (unserialize-accessors* ,value ,@fields) ,value))) ;;; maker to create serializers for lists (defmacro make-list-serializer (type element-type &key layer) "Make a serialize/unserialize pair for the key TYPE where each element is serialized with the key ELEMENT-TYPE." `(progn (define-serializer (,type value :layer ,layer) (declare (type list value)) (serialize :uint32 (length value)) (dolist (ee value) (serialize ,element-type ee))) (define-unserializer (,type :layer ,layer) (unserialize-let* (:uint32 len) (loop :for ii :from 1 :to len :collecting (unserialize ,element-type)))))) ;;; maker to create serializers for fixed length vectors (defmacro make-vector-serializer (type element-type length &key layer) (let ((elt (gensym "ELT-")) (value (gensym "VALUE-"))) `(progn (define-serializer (,type ,value :layer ,layer) (declare (type (vector * ,length) ,value)) (loop :for ,elt :across ,value :do (serialize ,element-type ,elt))) (define-unserializer (,type :layer ,layer) (vector ,@(loop :for elt :from 0 :below length :collecting `(unserialize ,element-type))))))) ;;; serializer for keywords (define-serializer (:keyword value) (declare (type symbol value)) (serialize :string (symbol-name value))) (define-unserializer (:keyword) (unserialize-let* (:string name) (intern name :keyword))) ;;; serializer for symbols (define-serializer (:symbol value) (declare (type symbol value)) (serialize* :string (symbol-name value) :string (package-name (symbol-package value)))) (define-unserializer (:symbol) (unserialize-let* (:string name :string package) (intern name package))) ;;; maker for aliasing serializers (defmacro make-alias-serializer (is-key was-key &key layer) (let ((keysym (gensym "KEY-")) (value (gensym "VAL-")) (rest (gensym "REST-"))) `(progn (contextl:define-layered-method serialize ,@(when layer `(:in-layer ,layer)) ((,keysym (eql ,is-key)) ,value &rest ,rest &key &allow-other-keys) (declare (ignore ,keysym)) (apply #'serialize ,was-key ,value ,rest)) (contextl:define-layered-method unserialize ,@(when layer `(:in-layer ,layer)) ((,keysym (eql ,is-key)) &rest ,rest &key &allow-other-keys) (declare (ignore ,keysym)) (apply #'unserialize ,was-key ,rest))))) ;;; serializer for objects fetched by a key (defmacro make-key-*-serializer (serialize-it unserialize-it (key var type-getter-var-list finder-form &key layer extra) &rest type-*-pairs) `(progn (define-serializer (,key ,var :layer ,layer :extra ,extra) (serialize* ,@(loop :for aa :on type-getter-var-list :by #'cdddr :appending (list (first aa) (let ((ff (second aa))) (if (symbolp ff) `(when (slot-boundp ,var ',ff) (slot-value ,var ',ff)) ff))))) (,serialize-it ,var ,@type-*-pairs)) (define-unserializer (,key :layer ,layer :extra (,var ,@extra)) (declare (ignorable ,var)) (unserialize-let* ,(loop :for aa :on type-getter-var-list :by #'cdddr :appending (list (first aa) (third aa))) ,(when type-*-pairs `(,unserialize-it ,finder-form ,@type-*-pairs)))))) (defmacro make-key-slot-serializer ((key var type-getter-var-list finder-form &key layer extra) &rest type-slot-pairs) `(make-key-*-serializer serialize-slots* unserialize-slots* (,key ,var ,type-getter-var-list ,finder-form :layer ,layer :extra ,extra) ,@type-slot-pairs)) (defmacro make-key-accessor-serializer ((key var type-getter-var-list finder-form &key layer extra) &rest type-accessor-pairs) `(make-key-*-serializer serialize-accessors* unserialize-accessors* (,key ,var ,type-getter-var-list ,finder-form :layer ,layer :extra ,extra) ,@type-accessor-pairs)) (defmacro make-global-variable-serializer ((key value-key &key layer) &rest global-vars) (let ((enum-key (gensym "ENUM-")) (var-sym (gensym "VAR-"))) `(progn (make-enum-serializer ',enum-key (,@global-vars) :layer ,layer) (define-serializer (,key ,var-sym :layer ,layer) (serialize ',enum-key ,var-sym) (serialize ,value-key (symbol-value ,var-sym))) (define-unserializer (,key :layer ,layer) (let ((,var-sym (unserialize ',enum-key))) (setf (symbol-value ,var-sym) (unserialize ,value-key)) ,var-sym))))) (defmacro make-maybe-serializer (key value-key &key layer) (let ((var-sym (gensym "VAR-"))) `(progn (define-serializer (,key ,var-sym :layer ,layer) (serialize :boolean (if ,var-sym t nil)) (when ,var-sym (serialize ,value-key ,var-sym))) (define-unserializer (,key :layer ,layer) (when (unserialize :boolean) (unserialize ,value-key))))))
null
https://raw.githubusercontent.com/nklein/userial/dc34fc73385678a61c39e98f77a4443433eedb1d/userial/serialize.lisp
lisp
serialize generic function unserialize generic function help define a serializer help define an unserializer help build integer serialize/unserialize methods define standard unsigned-int serialize/deserialize methods progressively stored unsigned integers define standard signed-int serialize/deserialize methods floating-point type helper floating-point type serializers/deserializers byte arrays without size encoded with them byte arrays with size string handling enum helper define standard enum methods maker to create serializers for lists maker to create serializers for fixed length vectors serializer for keywords serializer for symbols maker for aliasing serializers serializer for objects fetched by a key
Copyright ( c ) 2011 nklein software MIT License . See included LICENSE.txt file for licensing details . (in-package :userial) (contextl:define-layered-function serialize (type value &key &allow-other-keys) (:documentation "Method used to serialize a VALUE of given TYPE into BUFFER") (:method (type value &key &allow-other-keys) "There is no default way to serialize something, so chuck an error." (declare (ignore value)) (error "SERIALIZE not supported for type ~A" type))) (contextl:define-layered-function unserialize (type &key &allow-other-keys) (:documentation "Method used to unserialize a value of given TYPE from BUFFER") (:method (type &key &allow-other-keys) "There is no default way to unserialize something, so chuck an error." (error "UNSERIALIZE not supported for type ~A" type))) (defmacro serialize* (&rest type-value-pairs) "SERIALIZE a list of TYPE + VALUE into BUFFER returning the final BUFFER. For example: (SERIALIZE* :UINT8 5 :INT16 -10)" (multiple-value-bind (vars types values) (get-syms-types-places type-value-pairs) (declare (ignore vars)) `(progn ,@(mapcar #'(lambda (tt vv) `(serialize ,tt ,vv)) types values)))) (defmacro serialize-slots* (object &rest type-slot-plist) (let ((obj-sym (gensym "OBJ-"))) (labels ((do-slot (tt ss) `(,tt (when (slot-boundp ,obj-sym ',ss) (slot-value ,obj-sym ',ss))))) (multiple-value-bind (vars types slots) (get-syms-types-places type-slot-plist) (declare (ignore vars)) `(let ((,obj-sym ,object)) (serialize* ,@(loop :for tt :in types :for ss :in slots :appending (do-slot tt ss)))))))) (defmacro serialize-accessors* (object &rest type-accessor-plist) (multiple-value-bind (vars types accessors) (get-syms-types-places type-accessor-plist) `(with-accessors ,(mapcar #'quote-2 vars accessors) ,object (serialize* ,@(apply #'append (mapcar #'quote-2 types vars)))))) (defmacro unserialize* (&rest type-place-plist) "UNSERIALIZE a list of TYPE + PLACE from the given BUFFER and execute the body. For example: (LET (AA BB) (UNSERIALIZE* :UINT8 AA :INT16 BB) (LIST AA BB))" (multiple-value-bind (vars types places) (get-syms-types-places type-place-plist) (declare (ignore vars)) `(setf ,@(apply #'append (mapcar #'(lambda (tt pp) `(,pp (unserialize ,tt))) types places))))) (defmacro unserialize-slots* (object &rest type-slot-plist) (multiple-value-bind (vars types slots) (get-syms-types-places type-slot-plist) (let ((obj (gensym "OBJ-"))) `(let ((,obj ,object)) (with-slots ,(mapcar #'quote-2 vars slots) ,obj (unserialize* ,@(apply #'append (mapcar #'quote-2 types vars)))) ,obj)))) (defmacro unserialize-accessors* (object &rest type-accessor-plist) (multiple-value-bind (vars types accessors) (get-syms-types-places type-accessor-plist) (let ((obj (gensym "OBJ-"))) `(let ((,obj ,object)) (with-accessors ,(mapcar #'quote-2 vars accessors) ,obj (unserialize* ,@(apply #'append (mapcar #'quote-2 types vars))) ,obj))))) (defmacro unserialize-let* ((&rest type-var-plist) &body body) "UNSERIALIZE a list of TYPE + VARIABLE-NAME from the given BUFFER and execute the body. For example: (UNSERIALIZE-LET* (:UINT8 AA :INT16 BB) (LIST AA BB))" (multiple-value-bind (vars types places) (get-syms-types-places type-var-plist) (declare (ignore vars)) `(let* (,@(mapcar #'(lambda (pp tt) `(,pp (unserialize ,tt))) places types)) (values (progn ,@body) *buffer*)))) (defun unserialize-list* (types) "UNSERIALIZE a list of types from the given BUFFER into a list. For example: (MAPCAR #'PRINC (UNSERIALIZE-LIST* '(:UINT8 :INT16) :BUFFER BUFFER))" (values (mapcar #'(lambda (tt) (unserialize tt)) types) *buffer*)) (defmacro define-serializer ((key value &key layer extra) &body body) (let ((keysym (gensym "KEY-"))) `(contextl:define-layered-method serialize ,@(when layer `(:in-layer ,layer)) ((,keysym (eql ,key)) ,value &key ,@extra &allow-other-keys) (declare (ignore ,keysym)) ,@body *buffer*))) (defmacro define-unserializer ((key &key layer extra) &body body) (multiple-value-bind (decls body) (userial::separate-docstring-and-decls body) (let ((keysym (gensym "KEY-"))) `(contextl:define-layered-method unserialize ,@(when layer `(:in-layer ,layer)) ((,keysym (eql ,key)) &key ,@extra &allow-other-keys) ,@decls (declare (ignore ,keysym)) (values (progn ,@body) *buffer*))))) (defmacro make-uint-serializer (key bytes &key layer) "Make SERIALIZE/UNSERIALIZE methods for an unsigned-int of BYTES bytes in length dispatched by KEY." `(progn (define-serializer (,key value :layer ,layer) (declare (type (unsigned-byte ,(* bytes 8)) value) (optimize (speed 3))) (unroll-add-bytes value ,bytes)) (define-unserializer (,key :layer ,layer) (declare (optimize (speed 3))) (unroll-get-bytes ,bytes)))) (make-uint-serializer :uint8 1) (make-uint-serializer :uint16 2) (make-uint-serializer :uint24 3) (make-uint-serializer :uint32 4) (make-uint-serializer :uint48 6) (make-uint-serializer :uint64 8) (define-serializer (:uint value) (declare (type (integer 0 *) value) (optimize (speed 3))) (labels ((store-bytes (vv) (declare (type (integer 0 *) vv)) (multiple-value-bind (high low) (floor vv 128) (declare (type (integer 0 *) high) (type (integer 0 127) low)) (cond ((zerop high) (serialize :uint8 low)) (t (serialize :uint8 (+ low 128)) (store-bytes high)))))) (store-bytes value))) (define-unserializer (:uint) (declare (optimize (speed 3))) (labels ((fetch-bytes (&optional (vv 0) (offset 1)) (declare (type (integer 0 *) vv) (type (integer 1 *) offset)) (unserialize-let* (:uint8 byte) (flet ((add (bb) (+ vv (* bb offset)))) (cond ((< byte 128) (add byte)) (t (fetch-bytes (add (- byte 128)) (* offset 128)))))))) (fetch-bytes))) (defmacro twos-complement (val bytes) `(1+ (logxor ,val ,(1- (expt 2 (* bytes 8)))))) (defmacro make-int-serializer (key bytes &key layer) "Make SERIALIZE/UNSERIALIZE methods for a signed-int of BYTES bytes in length dispatched by KEY." (let ((vv (gensym "VV-"))) `(progn (define-serializer (,key value :layer ,layer) (declare (type (signed-byte ,(* bytes 8)) value) (optimize (speed 3))) (let ((,vv (if (minusp value) (twos-complement (- value) ,bytes) value))) (unroll-add-bytes ,vv ,bytes))) (define-unserializer (,key :layer ,layer) (declare (optimize (speed 3))) (let ((,vv (unroll-get-bytes ,bytes))) (declare (type (unsigned-byte ,(* bytes 8)) ,vv)) (if (logbitp ,(1- (* bytes 8)) ,vv) (- (twos-complement ,vv ,bytes)) ,vv)))))) (make-int-serializer :int8 1) (make-int-serializer :int16 2) (make-int-serializer :int32 4) (make-int-serializer :int64 8) (define-serializer (:int value) (declare (type integer value) (optimize (speed 3))) (flet ((store-and-go (vv sign) (multiple-value-bind (high low) (floor vv 64) (cond ((zerop high) (serialize :uint8 (+ low sign))) (t (serialize :uint8 (+ low sign 64)) (serialize :uint high)))))) (cond ((minusp value) (store-and-go (- value) 128)) (t (store-and-go value 0))))) (define-unserializer (:int) (declare (optimize (speed 3))) (flet ((get-number (vv) (cond ((<= 64 vv) (+ (* (unserialize :uint) 64) (- vv 64))) (t vv)))) (declare (ftype (function (uint) uint) get-number)) (let ((byte (unserialize :uint8))) (declare (type uchar byte)) (cond ((<= 128 byte) (- (get-number (- byte 128)))) (t (get-number byte)))))) (defmacro make-float-serializer (key type bytes encoder decoder &key layer) "Make serialize/unserialize routines for floating-point type TYPE dispatched by KEY with the given number of BYTES and an ENCODER/DECODER pair." (let ((vv (gensym "VV-"))) `(progn (define-serializer (,key value :layer ,layer) (declare (type ,type value) (optimize (speed 3))) (unroll-add-bytes (,encoder value) ,bytes)) (define-unserializer (,key :layer ,layer) (declare (optimize (speed 3))) (let ((,vv (unroll-get-bytes ,bytes))) (declare (type (unsigned-byte ,(* bytes 8)) ,vv)) (,decoder ,vv)))))) (make-float-serializer :float32 single-float 4 ieee-floats:encode-float32 ieee-floats:decode-float32) (make-float-serializer :float64 double-float 8 ieee-floats:encode-float64 ieee-floats:decode-float64) (define-serializer (:raw-bytes value :extra ((start 0) (end (length value)))) (declare (type (vector (unsigned-byte 8)) value)) (assert (<= 0 start end (length value))) (let ((length (- end start)) (buf-start (buffer-length))) (buffer-advance length) (setf (subseq *buffer* buf-start (buffer-length)) (subseq value start end)))) (define-unserializer (:raw-bytes :extra (output (start 0) (end (length output)))) (assert (<= 0 start end)) (let* ((length (- end start)) (buf-start (buffer-length)) (output (or output (make-array (list length) :initial-element 0 :element-type '(unsigned-byte 8))))) (declare (type (vector (unsigned-byte 8)) output)) (assert (<= end (length output))) (buffer-advance length) (setf (subseq output start end) (subseq *buffer* buf-start (buffer-length))) output)) (define-serializer (:bytes value) (declare (type (vector (unsigned-byte 8)) value)) (serialize :uint (length value)) (serialize :raw-bytes value)) (define-unserializer (:bytes) (unserialize-let* (:uint length) (let ((value (make-array (list length) :initial-element 0 :element-type '(unsigned-byte 8)))) (unserialize :raw-bytes :output value)))) (define-serializer (:string value) (declare (type string value)) (serialize :bytes (trivial-utf-8:string-to-utf-8-bytes value))) (define-unserializer (:string) (let ((value (unserialize :bytes))) (declare (type (vector (unsigned-byte 8)) value)) (trivial-utf-8:utf-8-bytes-to-string value))) (defmacro make-enum-serializer (type (&rest choices) &key layer (minimum-bytes 0)) "Create serialize/unserialize methods keyed by TYPE where the possible values are given by CHOICES" (let ((bytes (max (nth-value 0 (ceiling (log (length choices) 256))) minimum-bytes))) `(progn (define-serializer (,type value :layer ,layer) (declare (type symbol value)) (let ((value (ecase value ,@(loop :for ii :from 0 :for vv :in choices :collecting (list (if vv vv '(nil)) ii))))) (declare (type (unsigned-byte ,(* bytes 8)) value)) (unroll-add-bytes value ,bytes))) (define-unserializer (,type :layer ,layer) (let ((value (unroll-get-bytes ,bytes))) (declare (type (unsigned-byte ,(* bytes 8)) value)) (let ((value (ecase value ,@(loop :for ii :from 0 :for vv :in choices :collecting (list ii `',vv))))) (declare (type symbol value)) value)))))) (make-enum-serializer :boolean (nil t)) (defmacro make-bitfield-serializer (type (&rest choices) &key layer) "Create serialize/unserialize methods keyed by TYPE where the CHOICES can either be specified singly or as a list." (let ((bytes (nth-value 0 (ceiling (length choices) 8)))) `(progn (define-serializer (,type (value cons) :layer ,layer) (declare (type cons value)) (let ((val (reduce #'(lambda (acc &optional sym) (logior acc (ecase sym ,@(loop :for ii :from 0 :for vv :in choices :collecting (list vv (expt 2 ii)))))) value :initial-value 0))) (declare (type (unsigned-byte ,(* bytes 8)) val)) (unroll-add-bytes val ,bytes))) (define-serializer (,type (value symbol) :layer ,layer) (declare (type symbol value)) (let ((val (ecase value ((nil) 0) ,@(loop :for ii :from 0 :for vv :in choices :collecting (list vv (expt 2 ii)))))) (declare (type (unsigned-byte ,(* bytes 8)) val)) (unroll-add-bytes val ,bytes))) (define-unserializer (,type :layer ,layer) (let ((value (unroll-get-bytes ,bytes))) (declare (type (unsigned-byte ,(* bytes 8)) value)) (assert (< value ,(expt 2 (length choices)))) (loop :for ii :from 0 :below ,(length choices) :when (plusp (logand value (expt 2 ii))) :collect (svref (vector ,@(mapcar #'(lambda (cc) `',cc) choices)) ii))))))) (defmacro make-simple-serializer ((type value factory &key layer extra) &rest pairs) `(progn (define-serializer (,type ,value :layer ,layer :extra extra) (serialize* ,@pairs)) (define-unserializer (,type :layer ,layer :extra ((,value ,factory) ,@extra)) (unserialize* ,@pairs)))) (defmacro make-slot-serializer ((type value factory &key layer) &rest fields) "Make a serialize/unserialize pair with given TYPE using the FACTORY form when a new instance is needed where FIELDS is a list of key/slot values. For example: (defstruct person name (age 0)) (make-slot-serializer (:person person buffer (make-person)) :string name :uint8 age)" `(progn (define-serializer (,type ,value :layer ,layer) (serialize-slots* ,value ,@fields)) (define-unserializer (,type :layer ,layer :extra ((,value ,factory))) (unserialize-slots* ,value ,@fields) ,value))) (defmacro make-accessor-serializer ((type value factory &key layer) &rest fields) "Make a serialize/unserialize pair with given TYPE using the FACTORY form when a new instance is needed where FIELDS is a list of key/accessor values. For example: (defstruct person name (age 0)) (make-accessor-serializer (:person person buffer (make-person)) :string person-name :uint8 person-age)" `(progn (define-serializer (,type ,value :layer ,layer) (serialize-accessors* ,value ,@fields)) (define-unserializer (,type :layer ,layer :extra ((,value ,factory))) (unserialize-accessors* ,value ,@fields) ,value))) (defmacro make-list-serializer (type element-type &key layer) "Make a serialize/unserialize pair for the key TYPE where each element is serialized with the key ELEMENT-TYPE." `(progn (define-serializer (,type value :layer ,layer) (declare (type list value)) (serialize :uint32 (length value)) (dolist (ee value) (serialize ,element-type ee))) (define-unserializer (,type :layer ,layer) (unserialize-let* (:uint32 len) (loop :for ii :from 1 :to len :collecting (unserialize ,element-type)))))) (defmacro make-vector-serializer (type element-type length &key layer) (let ((elt (gensym "ELT-")) (value (gensym "VALUE-"))) `(progn (define-serializer (,type ,value :layer ,layer) (declare (type (vector * ,length) ,value)) (loop :for ,elt :across ,value :do (serialize ,element-type ,elt))) (define-unserializer (,type :layer ,layer) (vector ,@(loop :for elt :from 0 :below length :collecting `(unserialize ,element-type))))))) (define-serializer (:keyword value) (declare (type symbol value)) (serialize :string (symbol-name value))) (define-unserializer (:keyword) (unserialize-let* (:string name) (intern name :keyword))) (define-serializer (:symbol value) (declare (type symbol value)) (serialize* :string (symbol-name value) :string (package-name (symbol-package value)))) (define-unserializer (:symbol) (unserialize-let* (:string name :string package) (intern name package))) (defmacro make-alias-serializer (is-key was-key &key layer) (let ((keysym (gensym "KEY-")) (value (gensym "VAL-")) (rest (gensym "REST-"))) `(progn (contextl:define-layered-method serialize ,@(when layer `(:in-layer ,layer)) ((,keysym (eql ,is-key)) ,value &rest ,rest &key &allow-other-keys) (declare (ignore ,keysym)) (apply #'serialize ,was-key ,value ,rest)) (contextl:define-layered-method unserialize ,@(when layer `(:in-layer ,layer)) ((,keysym (eql ,is-key)) &rest ,rest &key &allow-other-keys) (declare (ignore ,keysym)) (apply #'unserialize ,was-key ,rest))))) (defmacro make-key-*-serializer (serialize-it unserialize-it (key var type-getter-var-list finder-form &key layer extra) &rest type-*-pairs) `(progn (define-serializer (,key ,var :layer ,layer :extra ,extra) (serialize* ,@(loop :for aa :on type-getter-var-list :by #'cdddr :appending (list (first aa) (let ((ff (second aa))) (if (symbolp ff) `(when (slot-boundp ,var ',ff) (slot-value ,var ',ff)) ff))))) (,serialize-it ,var ,@type-*-pairs)) (define-unserializer (,key :layer ,layer :extra (,var ,@extra)) (declare (ignorable ,var)) (unserialize-let* ,(loop :for aa :on type-getter-var-list :by #'cdddr :appending (list (first aa) (third aa))) ,(when type-*-pairs `(,unserialize-it ,finder-form ,@type-*-pairs)))))) (defmacro make-key-slot-serializer ((key var type-getter-var-list finder-form &key layer extra) &rest type-slot-pairs) `(make-key-*-serializer serialize-slots* unserialize-slots* (,key ,var ,type-getter-var-list ,finder-form :layer ,layer :extra ,extra) ,@type-slot-pairs)) (defmacro make-key-accessor-serializer ((key var type-getter-var-list finder-form &key layer extra) &rest type-accessor-pairs) `(make-key-*-serializer serialize-accessors* unserialize-accessors* (,key ,var ,type-getter-var-list ,finder-form :layer ,layer :extra ,extra) ,@type-accessor-pairs)) (defmacro make-global-variable-serializer ((key value-key &key layer) &rest global-vars) (let ((enum-key (gensym "ENUM-")) (var-sym (gensym "VAR-"))) `(progn (make-enum-serializer ',enum-key (,@global-vars) :layer ,layer) (define-serializer (,key ,var-sym :layer ,layer) (serialize ',enum-key ,var-sym) (serialize ,value-key (symbol-value ,var-sym))) (define-unserializer (,key :layer ,layer) (let ((,var-sym (unserialize ',enum-key))) (setf (symbol-value ,var-sym) (unserialize ,value-key)) ,var-sym))))) (defmacro make-maybe-serializer (key value-key &key layer) (let ((var-sym (gensym "VAR-"))) `(progn (define-serializer (,key ,var-sym :layer ,layer) (serialize :boolean (if ,var-sym t nil)) (when ,var-sym (serialize ,value-key ,var-sym))) (define-unserializer (,key :layer ,layer) (when (unserialize :boolean) (unserialize ,value-key))))))
366bd4878074c39d13608f57e22193c14d09314abd229275bd3125a7702c347e
bluelisp/hemlock
termcap.lisp
;;;; -*- Mode: Lisp; indent-tabs-mode: nil -*- ;;; ;;; ********************************************************************** This code was written as part of the CMU Common Lisp project at Carnegie Mellon University , and has been placed in the public domain . ;;; ;;; ;;; ********************************************************************** ;;; Written by ;;; ;;; Terminal Capability (in-package :hemlock-internals) This stuff used to parse a Termcap file . Now it 's just a compatibility layer over the Terminfo code . At some point this ;;; should be deleted entirely. (defvar *termcaps* ()) (defun termcap (name) (funcall (cdr (assoc name *termcaps* :test #'eq)))) (defmacro deftermcap (name type cl-name terminfo-name) (declare (ignore name type)) `(progn (push (cons ',cl-name (lambda () ,(intern (symbol-name terminfo-name) :hemlock.terminfo))) *termcaps*))) (deftermcap "is" :string :init-string init-2string) (deftermcap "if" :string :init-file init-file) (deftermcap "ti" :string :init-cursor-motion enter-ca-mode) (deftermcap "te" :string :end-cursor-motion exit-ca-mode) (deftermcap "al" :string :open-line insert-line) (deftermcap "am" :boolean :auto-margins-p auto-right-margin) (deftermcap "ce" :string :clear-to-eol clr-eol) (deftermcap "cl" :string :clear-display clear-screen) #+nil (deftermcap "cm" :string :cursor-motion cursor-address) (deftermcap "co" :number :columns columns) (deftermcap "dc" :string :delete-char delete-character) (deftermcap "dm" :string :init-delete-mode enter-delete-mode) (deftermcap "ed" :string :end-delete-mode clr-eos) (deftermcap "dl" :string :delete-line delete-line) (deftermcap "im" :string :init-insert-mode enter-insert-mode) (deftermcap "ic" :string :init-insert-char insert-character) (deftermcap "ip" :string :end-insert-char insert-padding) (deftermcap "ei" :string :end-insert-mode exit-insert-mode) (deftermcap "li" :number :lines lines) (deftermcap "so" :string :init-standout-mode enter-standout-mode) (deftermcap "se" :string :end-standout-mode exit-standout-mode) #+nil(deftermcap "tc" :string :similar-terminal) (deftermcap "os" :boolean :overstrikes over-strike) (deftermcap "ul" :boolean :underlines transparent-underline) font related stuff , added by (deftermcap "ae" :string :end-alternate-char-set exit-alt-charset-mode) (deftermcap "as" :string :start-alternate-char-set enter-alt-charset-mode) (deftermcap "mb" :string :start-blinking-attribute enter-blink-mode) (deftermcap "md" :string :start-bold-attribute enter-bold-mode) (deftermcap "me" :string :end-all-attributes exit-attribute-mode) (deftermcap "mh" :string :start-half-bright-attribute enter-dim-mode) (deftermcap "mk" :string :start-blank-attribute enter-secure-mode) (deftermcap "mp" :string :start-protected-attribute enter-protected-mode) (deftermcap "mr" :string :start-reverse-video-attribute enter-reverse-mode) (deftermcap "ue" :string :end-underscore-mode exit-underline-mode) (deftermcap "us" :string :start-underscore-mode enter-underline-mode)
null
https://raw.githubusercontent.com/bluelisp/hemlock/47e16ba731a0cf4ffd7fb2110e17c764ae757170/src/termcap.lisp
lisp
-*- Mode: Lisp; indent-tabs-mode: nil -*- ********************************************************************** ********************************************************************** Terminal Capability should be deleted entirely.
This code was written as part of the CMU Common Lisp project at Carnegie Mellon University , and has been placed in the public domain . Written by (in-package :hemlock-internals) This stuff used to parse a Termcap file . Now it 's just a compatibility layer over the Terminfo code . At some point this (defvar *termcaps* ()) (defun termcap (name) (funcall (cdr (assoc name *termcaps* :test #'eq)))) (defmacro deftermcap (name type cl-name terminfo-name) (declare (ignore name type)) `(progn (push (cons ',cl-name (lambda () ,(intern (symbol-name terminfo-name) :hemlock.terminfo))) *termcaps*))) (deftermcap "is" :string :init-string init-2string) (deftermcap "if" :string :init-file init-file) (deftermcap "ti" :string :init-cursor-motion enter-ca-mode) (deftermcap "te" :string :end-cursor-motion exit-ca-mode) (deftermcap "al" :string :open-line insert-line) (deftermcap "am" :boolean :auto-margins-p auto-right-margin) (deftermcap "ce" :string :clear-to-eol clr-eol) (deftermcap "cl" :string :clear-display clear-screen) #+nil (deftermcap "cm" :string :cursor-motion cursor-address) (deftermcap "co" :number :columns columns) (deftermcap "dc" :string :delete-char delete-character) (deftermcap "dm" :string :init-delete-mode enter-delete-mode) (deftermcap "ed" :string :end-delete-mode clr-eos) (deftermcap "dl" :string :delete-line delete-line) (deftermcap "im" :string :init-insert-mode enter-insert-mode) (deftermcap "ic" :string :init-insert-char insert-character) (deftermcap "ip" :string :end-insert-char insert-padding) (deftermcap "ei" :string :end-insert-mode exit-insert-mode) (deftermcap "li" :number :lines lines) (deftermcap "so" :string :init-standout-mode enter-standout-mode) (deftermcap "se" :string :end-standout-mode exit-standout-mode) #+nil(deftermcap "tc" :string :similar-terminal) (deftermcap "os" :boolean :overstrikes over-strike) (deftermcap "ul" :boolean :underlines transparent-underline) font related stuff , added by (deftermcap "ae" :string :end-alternate-char-set exit-alt-charset-mode) (deftermcap "as" :string :start-alternate-char-set enter-alt-charset-mode) (deftermcap "mb" :string :start-blinking-attribute enter-blink-mode) (deftermcap "md" :string :start-bold-attribute enter-bold-mode) (deftermcap "me" :string :end-all-attributes exit-attribute-mode) (deftermcap "mh" :string :start-half-bright-attribute enter-dim-mode) (deftermcap "mk" :string :start-blank-attribute enter-secure-mode) (deftermcap "mp" :string :start-protected-attribute enter-protected-mode) (deftermcap "mr" :string :start-reverse-video-attribute enter-reverse-mode) (deftermcap "ue" :string :end-underscore-mode exit-underline-mode) (deftermcap "us" :string :start-underscore-mode enter-underline-mode)
c3617ffc48ed15a0bfca7a8534f66ce5e69fe9f3ed33b57dbf86cdc74dd017f4
Frama-C/Frama-C-snapshot
wfile.ml
(**************************************************************************) (* *) This file is part of Frama - C. (* *) Copyright ( C ) 2007 - 2019 CEA ( Commissariat à l'énergie atomique et aux énergies (* alternatives) *) (* *) (* you can redistribute it and/or modify it under the terms of the GNU *) Lesser General Public License as published by the Free Software Foundation , version 2.1 . (* *) (* It is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* GNU Lesser General Public License for more details. *) (* *) See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . (* *) (**************************************************************************) (* -------------------------------------------------------------------------- *) (* --- File Chooser --- *) (* -------------------------------------------------------------------------- *) type filekind = [ `FILE | `DIR ] class dialog ?(kind=`FILE) ?(title="Select File") ?(select="Select") ?parent () = let dialog = GWindow.dialog ~title ?parent ~modal:true () in let packing = dialog#vbox#pack ~expand:true in let action = match kind with `FILE -> `SAVE | `DIR -> `CREATE_FOLDER in let chooser = GFile.chooser_widget ~action ~packing () in object inherit [string] Wutil.signal as signal initializer begin ignore (dialog#event#connect#delete (fun _ -> true)) ; dialog#add_button "Cancel" `DELETE_EVENT ; dialog#add_button select `SELECT ; ignore (GMisc.label ~packing:(dialog#action_area#pack ~expand:true) ()) ; end method add_filter ~descr ~patterns = if kind = `FILE then chooser#add_filter (GFile.filter ~name:descr ~patterns ()) method select ?dir ?file () = begin match dir , file with | None , None -> ignore (chooser#set_filename "") | None , Some path -> ignore (chooser#set_filename path) | Some dir , None -> ignore (chooser#set_current_folder dir) ; ignore (chooser#set_current_name "") | Some dir , Some file -> ignore (chooser#set_current_folder dir) ; ignore (chooser#set_current_name file) end ; let result = dialog#run () in dialog#misc#hide () ; match result with | `DELETE_EVENT -> () | `SELECT -> match chooser#get_filenames with | f::_ -> signal#fire f | _ -> () end class button ?kind ?title ?select ?tooltip ?parent () = let box = GPack.hbox ~homogeneous:false ~spacing:0 ~border_width:0 () in let fld = GMisc.label ~text:"(none)" ~xalign:0.0 ~packing:(box#pack ~expand:true) () in let _ = GMisc.separator `VERTICAL ~packing:(box#pack ~expand:false ~padding:2) ~show:true () in let _ = GMisc.image ~packing:(box#pack ~expand:false) ~stock:`OPEN () in let button = GButton.button () in let dialog = new dialog ?kind ?title ?select ?parent () in object(self) inherit Wutil.gobj_widget button inherit! [string] Wutil.selector "" as current val mutable disptip = fun f -> match tooltip , f with | None , "" -> "(none)" | None , _ -> f | Some d , "" -> d | Some d , f -> Printf.sprintf "%s: %s" d f val mutable display = function | "" -> "(none)" | path -> Filename.basename path initializer begin button#add box#coerce ; button#set_focus_on_click false ; ignore (button#connect#clicked self#select) ; dialog#connect current#set ; Wutil.set_tooltip button tooltip ; current#connect (fun f -> button#misc#set_tooltip_text (disptip f) ; fld#set_text (display f)) ; end method set_tooltip p = disptip <- p ; fld#misc#set_tooltip_text (p current#get) method set_display p = display <- p ; fld#set_text (p current#get) method add_filter = dialog#add_filter method select ?dir ?file () = let file = match file with None -> current#get | Some f -> f in dialog#select ?dir ~file () end
null
https://raw.githubusercontent.com/Frama-C/Frama-C-snapshot/639a3647736bf8ac127d00ebe4c4c259f75f9b87/src/plugins/gui/wfile.ml
ocaml
************************************************************************ alternatives) you can redistribute it and/or modify it under the terms of the GNU It is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ************************************************************************ -------------------------------------------------------------------------- --- File Chooser --- --------------------------------------------------------------------------
This file is part of Frama - C. Copyright ( C ) 2007 - 2019 CEA ( Commissariat à l'énergie atomique et aux énergies Lesser General Public License as published by the Free Software Foundation , version 2.1 . See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . type filekind = [ `FILE | `DIR ] class dialog ?(kind=`FILE) ?(title="Select File") ?(select="Select") ?parent () = let dialog = GWindow.dialog ~title ?parent ~modal:true () in let packing = dialog#vbox#pack ~expand:true in let action = match kind with `FILE -> `SAVE | `DIR -> `CREATE_FOLDER in let chooser = GFile.chooser_widget ~action ~packing () in object inherit [string] Wutil.signal as signal initializer begin ignore (dialog#event#connect#delete (fun _ -> true)) ; dialog#add_button "Cancel" `DELETE_EVENT ; dialog#add_button select `SELECT ; ignore (GMisc.label ~packing:(dialog#action_area#pack ~expand:true) ()) ; end method add_filter ~descr ~patterns = if kind = `FILE then chooser#add_filter (GFile.filter ~name:descr ~patterns ()) method select ?dir ?file () = begin match dir , file with | None , None -> ignore (chooser#set_filename "") | None , Some path -> ignore (chooser#set_filename path) | Some dir , None -> ignore (chooser#set_current_folder dir) ; ignore (chooser#set_current_name "") | Some dir , Some file -> ignore (chooser#set_current_folder dir) ; ignore (chooser#set_current_name file) end ; let result = dialog#run () in dialog#misc#hide () ; match result with | `DELETE_EVENT -> () | `SELECT -> match chooser#get_filenames with | f::_ -> signal#fire f | _ -> () end class button ?kind ?title ?select ?tooltip ?parent () = let box = GPack.hbox ~homogeneous:false ~spacing:0 ~border_width:0 () in let fld = GMisc.label ~text:"(none)" ~xalign:0.0 ~packing:(box#pack ~expand:true) () in let _ = GMisc.separator `VERTICAL ~packing:(box#pack ~expand:false ~padding:2) ~show:true () in let _ = GMisc.image ~packing:(box#pack ~expand:false) ~stock:`OPEN () in let button = GButton.button () in let dialog = new dialog ?kind ?title ?select ?parent () in object(self) inherit Wutil.gobj_widget button inherit! [string] Wutil.selector "" as current val mutable disptip = fun f -> match tooltip , f with | None , "" -> "(none)" | None , _ -> f | Some d , "" -> d | Some d , f -> Printf.sprintf "%s: %s" d f val mutable display = function | "" -> "(none)" | path -> Filename.basename path initializer begin button#add box#coerce ; button#set_focus_on_click false ; ignore (button#connect#clicked self#select) ; dialog#connect current#set ; Wutil.set_tooltip button tooltip ; current#connect (fun f -> button#misc#set_tooltip_text (disptip f) ; fld#set_text (display f)) ; end method set_tooltip p = disptip <- p ; fld#misc#set_tooltip_text (p current#get) method set_display p = display <- p ; fld#set_text (p current#get) method add_filter = dialog#add_filter method select ?dir ?file () = let file = match file with None -> current#get | Some f -> f in dialog#select ?dir ~file () end
cfbf169bd0676b50b087749b8f016acbba69c9b7c1182ff1260be5ee4dd0844d
sjl/euler
problems.lisp
(in-package :euler) (defun problem-10 () The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17 . Find the sum of all the primes below two million . (summation (sieve 2000000))) (defun problem-11 () In the 20×20 grid below , four numbers along a diagonal line have been marked ;; in red. ;; The product of these numbers is 26 × 63 × 78 × 14 = 1788696 . ;; What is the greatest product of four adjacent numbers in the same direction ( up , down , left , right , or diagonally ) in the 20×20 grid ? (let ((grid #2A((08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08) (49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00) (81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65) (52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91) (22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80) (24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50) (32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70) (67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21) (24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72) (21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95) (78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92) (16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57) (86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58) (19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40) (04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66) (88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69) (04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36) (20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16) (20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54) (01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48)))) (max ;; horizontal (iterate (for-nested ((row :from 0 :below 20) (col :from 0 :below 16))) (maximize (* (aref grid row (+ 0 col)) (aref grid row (+ 1 col)) (aref grid row (+ 2 col)) (aref grid row (+ 3 col))))) ;; vertical (iterate (for-nested ((row :from 0 :below 16) (col :from 0 :below 20))) (maximize (* (aref grid (+ 0 row) col) (aref grid (+ 1 row) col) (aref grid (+ 2 row) col) (aref grid (+ 3 row) col)))) ;; backslash \ (iterate (for-nested ((row :from 0 :below 16) (col :from 0 :below 16))) (maximize (* (aref grid (+ 0 row) (+ 0 col)) (aref grid (+ 1 row) (+ 1 col)) (aref grid (+ 2 row) (+ 2 col)) (aref grid (+ 3 row) (+ 3 col))))) ;; slash / (iterate (for-nested ((row :from 3 :below 20) (col :from 0 :below 16))) (maximize (* (aref grid (- row 0) (+ 0 col)) (aref grid (- row 1) (+ 1 col)) (aref grid (- row 2) (+ 2 col)) (aref grid (- row 3) (+ 3 col)))))))) (defun problem-12 () ;; The sequence of triangle numbers is generated by adding the natural numbers . So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28 . The first ten terms would be : ;; 1 , 3 , 6 , 10 , 15 , 21 , 28 , 36 , 45 , 55 , ... ;; Let us list the factors of the first seven triangle numbers : ;; 1 : 1 3 : 1,3 6 : 1,2,3,6 10 : 1,2,5,10 15 : 1,3,5,15 21 : 1,3,7,21 28 : 1,2,4,7,14,28 ;; We can see that 28 is the first triangle number to have over five divisors . ;; What is the value of the first triangle number to have over five hundred ;; divisors? (iterate (for tri :key #'triangle :from 1) (finding tri :such-that (> (count-divisors tri) 500)))) (defun problem-13 () Work out the first ten digits of the sum of the following one - hundred 50 - digit numbers . (-<> (read-all-from-file "data/013-numbers.txt") summation aesthetic-string (subseq <> 0 10) parse-integer (nth-value 0 <>))) (defun problem-14 () ;; The following iterative sequence is defined for the set of positive ;; integers: ;; ;; n → n/2 (n is even) ;; n → 3n + 1 (n is odd) ;; Using the rule above and starting with 13 , we generate the following ;; sequence: ;; 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 ;; It can be seen that this sequence ( starting at 13 and finishing at 1 ) contains 10 terms . Although it has not been proved yet ( Collatz Problem ) , it is thought that all starting numbers finish at 1 . ;; Which starting number , under one million , produces the longest chain ? ;; NOTE : Once the chain starts the terms are allowed to go above one million . (iterate (for i :from 1 :below 1000000) (finding i :maximizing #'collatz-length))) (defun problem-15 () Starting in the top left corner of a 2×2 grid , and only being able to move to the right and down , there are exactly 6 routes to the bottom right ;; corner. ;; How many such routes are there through a 20×20 grid ? (binomial-coefficient 40 20)) (defun problem-16 () 2 ^ 15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26 . ;; What is the sum of the digits of the number 2 ^ 1000 ? (digital-sum (expt 2 1000))) (defun problem-17 () If the numbers 1 to 5 are written out in words : one , two , three , four , five , then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total . ;; If all the numbers from 1 to 1000 ( one thousand ) inclusive were written out ;; in words, how many letters would be used? ;; NOTE : Do not count spaces or hyphens . For example , 342 ( three hundred and forty - two ) contains 23 letters and 115 ( one hundred and fifteen ) contains 20 letters . The use of " and " when writing out numbers is in compliance with British usage , which is awful . (labels ((letters (n) (-<> n (format nil "~R" <>) (count-if #'alpha-char-p <>))) (has-british-and (n) (or (< n 100) (zerop (mod n 100)))) (silly-british-letters (n) (+ (letters n) (if (has-british-and n) 0 3)))) (summation (irange 1 1000) :key #'silly-british-letters))) (defun problem-18 () ;; By starting at the top of the triangle below and moving to adjacent numbers on the row below , the maximum total from top to bottom is 23 . ;; ;; 3 7 4 2 4 6 ;; 8 5 9 3 ;; That is , 3 + 7 + 4 + 9 = 23 . ;; ;; Find the maximum total from top to bottom of the triangle below. ;; NOTE : As there are only 16384 routes , it is possible to solve this problem by trying every route . However , Problem 67 , is the same challenge with a triangle containing one - hundred rows ; it can not be solved by brute force , ;; and requires a clever method! ;o) (let ((triangle (iterate (for line :in-csv-file "data/018-triangle.txt" :delimiter #\space :key #'parse-integer) (collect line)))) (car (reduce (lambda (prev last) (mapcar #'+ prev (mapcar #'max last (rest last)))) triangle :from-end t)))) (defun problem-19 () ;; You are given the following information, but you may prefer to do some ;; research for yourself. ;; 1 Jan 1900 was a Monday . Thirty days has September , April , June and November . All the rest have thirty - one , Saving February alone , Which has twenty - eight , rain or shine . And on leap years , twenty - nine . A leap year occurs on any year evenly divisible by 4 , but not on a century unless it is divisible by 400 . ;; How many Sundays fell on the first of the month during the twentieth century ( 1 Jan 1901 to 31 Dec 2000 ) ? (iterate (for-nested ((year :from 1901 :to 2000) (month :from 1 :to 12))) (counting (-<> (local-time:encode-timestamp 0 0 0 0 1 month year) local-time:timestamp-day-of-week zerop)))) (defun problem-20 () n ! means n × ( n − 1 ) × ... × 3 × 2 × 1 ;; For example , 10 ! = 10 × 9 × ... × 3 × 2 × 1 = 3628800 , and the sum of the digits in the number 10 ! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27 . ;; Find the sum of the digits in the number 100 ! (digital-sum (factorial 100))) (defun problem-21 () ;; Let d(n) be defined as the sum of proper divisors of n (numbers less than ;; n which divide evenly into n). ;; ;; If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair ;; and each of a and b are called amicable numbers. ;; For example , the proper divisors of 220 are 1 , 2 , 4 , 5 , 10 , 11 , 20 , 22 , 44 , 55 and 110 ; therefore d(220 ) = 284 . The proper divisors of 284 are 1 , 2 , 4 , 71 and 142 ; so d(284 ) = 220 . ;; Evaluate the sum of all the amicable numbers under 10000 . (summation (remove-if-not #'amicablep (range 1 10000)))) (defun problem-22 () Using names.txt , a 46 K text file containing over five - thousand first names , ;; begin by sorting it into alphabetical order. Then working out the ;; alphabetical value for each name, multiply this value by its alphabetical ;; position in the list to obtain a name score. ;; For example , when the list is sorted into alphabetical order , , which is worth 3 + 15 + 12 + 9 + 14 = 53 , is the 938th name in the list . So , would obtain a score of 938 × 53 = 49714 . ;; ;; What is the total of all the name scores in the file? (labels ((read-names () (-<> "data/022-names.txt" parse-strings-file (sort <> #'string<))) (name-score (name) (summation name :key #'letter-number))) (iterate (for position :from 1) (for name :in (read-names)) (summing (* position (name-score name)))))) (defun problem-23 () ;; A perfect number is a number for which the sum of its proper divisors is ;; exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28 , which means that 28 is a perfect ;; number. ;; ;; A number n is called deficient if the sum of its proper divisors is less ;; than n and it is called abundant if this sum exceeds n. ;; As 12 is the smallest abundant number , 1 + 2 + 3 + 4 + 6 = 16 , the smallest number that can be written as the sum of two abundant numbers is 24 . By mathematical analysis , it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers . However , this upper ;; limit cannot be reduced any further by analysis even though it is known that the greatest number that can not be expressed as the sum of two ;; abundant numbers is less than this limit. ;; ;; Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers . (let* ((limit 28123) (abundant-numbers (make-hash-set :initial-contents (remove-if-not #'abundantp (irange 1 limit))))) (flet ((abundant-sum-p (n) (iterate (for a :in-hashset abundant-numbers) (when (hset-contains-p abundant-numbers (- n a)) (return t))))) (summation (remove-if #'abundant-sum-p (irange 1 limit)))))) (defun problem-24 () A permutation is an ordered arrangement of objects . For example , 3124 is one possible permutation of the digits 1 , 2 , 3 and 4 . If all of the ;; permutations are listed numerically or alphabetically, we call it lexicographic order . The lexicographic permutations of 0 , 1 and 2 are : ;; 012 021 102 120 201 210 ;; What is the millionth lexicographic permutation of the digits 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 and 9 ? (-<> "0123456789" (gathering-vector (:size (factorial (length <>))) (map-permutations (compose #'gather #'parse-integer) <> :copy nil)) (sort <> #'<) (elt <> (1- 1000000)))) (defun problem-25 () ;; The Fibonacci sequence is defined by the recurrence relation: ;; Fn = Fn−1 + Fn−2 , where F1 = 1 and F2 = 1 . ;; Hence the first 12 terms will be : ;; F1 = 1 F2 = 1 F3 = 2 F4 = 3 F5 = 5 F6 = 8 F7 = 13 F8 = 21 F9 = 34 F10 = 55 F11 = 89 F12 = 144 ;; The 12th term , F12 , is the first term to contain three digits . ;; What is the index of the first term in the sequence to contain 1000 digits ? (iterate (for f :in-fibonacci t) (for i :from 1) (finding i :such-that (= 1000 (digits-length f))))) (defun problem-26 () A unit fraction contains 1 in the numerator . The decimal representation of the unit fractions with denominators 2 to 10 are given : ;; 1/2 = 0.5 1/3 = 0.(3 ) 1/4 = 0.25 1/5 = 0.2 1/6 = 0.1(6 ) 1/7 = 0.(142857 ) 1/8 = 0.125 1/9 = 0.(1 ) 1/10 = 0.1 ;; Where 0.1(6 ) means 0.166666 ... , and has a 1 - digit recurring cycle . It can be seen that 1/7 has a 6 - digit recurring cycle . ;; Find the value of d < 1000 for which 1 / d contains the longest recurring ;; cycle in its decimal fraction part. (iterate 2 and 5 are the only primes that are n't coprime to 10 (for i :in (set-difference (primes-below 1000) '(2 5))) (finding i :maximizing (multiplicative-order 10 i)))) (defun problem-27 () ;; Euler discovered the remarkable quadratic formula: ;; ;; n² + n + 41 ;; It turns out that the formula will produce 40 primes for the consecutive integer values 0 ≤ n ≤ 39 . However , when n=40 , 40² + 40 + 41 = 40(40 + 1 ) + 41 is divisible by 41 , and certainly when n=41 , 41² + 41 + 41 is clearly divisible by 41 . ;; The incredible formula n² − 79n + 1601 was discovered , which produces 80 primes for the consecutive values 0 ≤ n ≤ 79 . The product of the coefficients , −79 and 1601 , is −126479 . ;; ;; Considering quadratics of the form: ;; n² + an + b , where |a| < 1000 and |b| ≤ 1000 ;; ;; where |n| is the modulus/absolute value of n e.g. |11| = 11 and |−4| = 4 ;; ;; Find the product of the coefficients, a and b, for the quadratic expression ;; that produces the maximum number of primes for consecutive values of n, starting with n=0 . (flet ((primes-produced (a b) (iterate (for n :from 0) (while (primep (math n ^ 2 + a n + b))) (counting t)))) (iterate (for-nested ((a :from -999 :to 999) (b :from -1000 :to 1000))) (finding (* a b) :maximizing (primes-produced a b))))) (defun problem-28 () Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows : ;; 21 22 23 24 25 20 7 8 9 10 19 6 1 2 11 18 5 4 3 12 17 16 15 14 13 ;; It can be verified that the sum of the numbers on the diagonals is 101 . ;; What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral ;; formed in the same way? (iterate (for size :from 1 :to 1001 :by 2) (summing (apply #'+ (number-spiral-corners size))))) (defun problem-29 () Consider all integer combinations of a^b for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5 : ;; 2²=4 , 2³=8 , 2⁴=16 , 2⁵=32 3²=9 , 3³=27 , 3⁴=81 , 3⁵=243 4²=16 , 4³=64 , 4⁴=256 , 4⁵=1024 5²=25 , 5³=125 , 5⁴=625 , 5⁵=3125 ;; ;; If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms : ;; 4 , 8 , 9 , 16 , 25 , 27 , 32 , 64 , 81 , 125 , 243 , 256 , 625 , 1024 , 3125 ;; ;; How many distinct terms are in the sequence generated by a^b for 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100 ? (length (iterate (for-nested ((a :from 2 :to 100) (b :from 2 :to 100))) (adjoining (expt a b))))) (defun problem-30 () Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits : ;; 1634 = 1⁴ + 6⁴ + 3⁴ + 4⁴ 8208 = 8⁴ + 2⁴ + 0⁴ + 8⁴ 9474 = 9⁴ + 4⁴ + 7⁴ + 4⁴ ;; As 1 = 1⁴ is not a sum it is not included . ;; The sum of these numbers is 1634 + 8208 + 9474 = 19316 . ;; Find the sum of all the numbers that can be written as the sum of fifth ;; powers of their digits. (flet ((maximum-sum-for-digits (n) (* (expt 9 5) n)) (digit-power-sum (n) (summation (digits n) :key (rcurry #'expt 5)))) (iterate ;; We want to find a limit N that's bigger than the maximum possible sum ;; for its number of digits. (with limit = (iterate (for digits :from 1) (for n = (expt 10 digits)) (while (< n (maximum-sum-for-digits digits))) (finally (return n)))) ;; Then just brute-force the thing. (for i :from 2 :to limit) (when (= i (digit-power-sum i)) (summing i))))) (defun problem-31 () In England the currency is made up of pound , £ , and pence , p , and there are eight coins in general circulation : ;; 1p , 2p , 5p , 10p , 20p , 50p , £ 1 ( 100p ) and £ 2 ( 200p ) . ;; It is possible to make £ 2 in the following way : ;; 1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p ;; How many different ways can £ 2 be made using any number of coins ? (recursively ((amount 200) (coins '(200 100 50 20 10 5 2 1))) (cond ((zerop amount) 1) ((minusp amount) 0) ((null coins) 0) (t (+ (recur (- amount (first coins)) coins) (recur amount (rest coins))))))) (defun problem-32 () We shall say that an n - digit number is pandigital if it makes use of all the digits 1 to n exactly once ; for example , the 5 - digit number , 15234 , is 1 through 5 pandigital . ;; The product 7254 is unusual , as the identity , 39 × 186 = 7254 , containing multiplicand , multiplier , and product is 1 through 9 pandigital . ;; ;; Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital . ;; HINT : Some products can be obtained in more than one way so be sure to only ;; include it once in your sum. (labels ((split (digits a b) (values (digits-to-number (subseq digits 0 a)) (digits-to-number (subseq digits a (+ a b))) (digits-to-number (subseq digits (+ a b))))) (check (digits a b) (multiple-value-bind (a b c) (split digits a b) (when (= (* a b) c) c)))) (-<> (gathering (map-permutations (lambda (digits) (let ((c1 (check digits 3 2)) (c2 (check digits 4 1))) (when c1 (gather c1)) (when c2 (gather c2)))) #(1 2 3 4 5 6 7 8 9) :copy nil)) remove-duplicates summation))) (defun problem-33 () The fraction 49/98 is a curious fraction , as an inexperienced mathematician in attempting to simplify it may incorrectly believe that 49/98 = 4/8 , which is correct , is obtained by cancelling the 9s . ;; We shall consider fractions like , 30/50 = 3/5 , to be trivial examples . ;; There are exactly four non - trivial examples of this type of fraction , less than one in value , and containing two digits in the numerator and ;; denominator. ;; If the product of these four fractions is given in its lowest common terms , ;; find the value of the denominator. (labels ((safe/ (a b) (unless (zerop b) (/ a b))) (cancel (digit other digits) (destructuring-bind (x y) digits (remove nil (list (when (= digit x) (safe/ other y)) (when (= digit y) (safe/ other x)))))) (cancellations (numerator denominator) (let ((nd (digits numerator)) (dd (digits denominator))) (append (cancel (first nd) (second nd) dd) (cancel (second nd) (first nd) dd)))) (curiousp (numerator denominator) (member (/ numerator denominator) (cancellations numerator denominator))) (trivialp (numerator denominator) (and (dividesp numerator 10) (dividesp denominator 10)))) (iterate (with result = 1) (for numerator :from 10 :to 99) (iterate (for denominator :from (1+ numerator) :to 99) (when (and (curiousp numerator denominator) (not (trivialp numerator denominator))) (mulf result (/ numerator denominator)))) (finally (return (denominator result)))))) (defun problem-34 () 145 is a curious number , as 1 ! + 4 ! + 5 ! = 1 + 24 + 120 = 145 . ;; ;; Find the sum of all numbers which are equal to the sum of the factorial of ;; their digits. ;; Note : as 1 ! = 1 and 2 ! = 2 are not sums they are not included . (iterate (for n :from 3 :to 1000000) (when (= n (summation (digits n) :key #'factorial)) (summing n)))) (defun problem-35 () The number , 197 , is called a circular prime because all rotations of the digits : 197 , 971 , and 719 , are themselves prime . ;; There are thirteen such primes below 100 : 2 , 3 , 5 , 7 , 11 , 13 , 17 , 31 , 37 , 71 , 73 , 79 , and 97 . ;; How many circular primes are there below one million ? (labels ((rotate (n distance) (multiple-value-bind (hi lo) (truncate n (expt 10 distance)) (math lo * 10 ^ #(digits-length hi) + hi))) (rotations (n) (mapcar (curry #'rotate n) (range 1 (digits-length n)))) (circular-prime-p (n) (every #'primep (rotations n)))) (iterate (for i :in-vector (sieve 1000000)) (counting (circular-prime-p i))))) (defun problem-36 () The decimal number , 585 = 1001001001 ( binary ) , is palindromic in both ;; bases. ;; Find the sum of all numbers , less than one million , which are palindromic in base 10 and base 2 . ;; ;; (Please note that the palindromic number, in either base, may not include leading zeros . ) (iterate (for i :from 1 :below 1000000) (when (and (palindromep i 10) (palindromep i 2)) (summing i)))) (defun problem-37 () The number 3797 has an interesting property . Being prime itself , it is ;; possible to continuously remove digits from left to right, and remain prime at each stage : 3797 , 797 , 97 , and 7 . Similarly we can work from right to left : 3797 , 379 , 37 , and 3 . ;; Find the sum of the only eleven primes that are both truncatable from left ;; to right and right to left. ;; NOTE : 2 , 3 , 5 , and 7 are not considered to be truncatable primes . (labels ((truncations (n) (iterate (for i :from 0 :below (digits-length n)) (collect (truncate-number-left n i)) (collect (truncate-number-right n i)))) (truncatablep (n) (every #'primep (truncations n)))) (iterate (with count = 0) (for i :from 11 :by 2) (when (truncatablep i) (summing i) (incf count)) (while (< count 11))))) (defun problem-38 () Take the number 192 and multiply it by each of 1 , 2 , and 3 : ;; 192 × 1 = 192 192 × 2 = 384 192 × 3 = 576 ;; By concatenating each product we get the 1 to 9 pandigital , 192384576 . We will call 192384576 the concatenated product of 192 and ( 1,2,3 ) ;; The same can be achieved by starting with 9 and multiplying by 1 , 2 , 3 , 4 , and 5 , giving the pandigital , 918273645 , which is the concatenated product of 9 and ( 1,2,3,4,5 ) . ;; What is the largest 1 to 9 pandigital 9 - digit number that can be formed as the concatenated product of an integer with ( 1,2 , ... , n ) where n > 1 ? (labels ((concatenated-product (number i) (apply #'concatenate-integers (iterate (for n :from 1 :to i) (collect (* number n)))))) (iterate main (for base :from 1) base ca n't be more than 5 digits long because we have to concatenate at ;; least two products of it (while (<= (digits-length base) 5)) (iterate (for n :from 2) (for result = (concatenated-product base n)) ;; result is only ever going to grow larger, so once we pass the nine digit mark we can stop (while (<= (digits-length result) 9)) (when (pandigitalp result) (in main (maximizing result))))))) (defun problem-39 () If p is the perimeter of a right angle triangle with integral length sides , { a , b , c } , there are exactly three solutions for p = 120 . ;; { 20,48,52 } , { 24,45,51 } , { 30,40,50 } ;; For which value of p ≤ 1000 , is the number of solutions maximised ? (iterate (for p :from 1 :to 1000) (finding p :maximizing (length (pythagorean-triplets-of-perimeter p))))) (defun problem-40 () ;; An irrational decimal fraction is created by concatenating the positive ;; integers: ;; 0.123456789101112131415161718192021 ... ;; It can be seen that the 12th digit of the fractional part is 1 . ;; ;; If dn represents the nth digit of the fractional part, find the value of ;; the following expression. ;; d1 × d10 × d100 × d1000 × d10000 × d100000 × d1000000 (iterate top (with index = 0) (for digits :key #'digits :from 1) (iterate (for d :in digits) (incf index) (when (member index '(1 10 100 1000 10000 100000 1000000)) (in top (multiplying d)) (when (= index 1000000) (in top (terminate))))))) (defun problem-41 () We shall say that an n - digit number is pandigital if it makes use of all the digits 1 to n exactly once . For example , 2143 is a 4 - digit pandigital ;; and is also prime. ;; What is the largest n - digit pandigital prime that exists ? (iterate There 's a clever observation which reduces the upper bound from 9 to 7 from " gamma " in the forum : ;; > Note : Nine numbers can not be done ( 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9=45 = > always dividable by 3 ) > Note : Eight numbers can not be done ( 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8=36 = > always dividable by 3 ) (for n :downfrom 7) (thereis (apply (nullary #'max) (remove-if-not #'primep (pandigitals 1 n)))))) (defun problem-42 () ;; The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so the first ten triangle numbers are : ;; 1 , 3 , 6 , 10 , 15 , 21 , 28 , 36 , 45 , 55 , ... ;; ;; By converting each letter in a word to a number corresponding to its ;; alphabetical position and adding these values we form a word value. For example , the word value for SKY is 19 + 11 + 25 = 55 = t10 . If the word ;; value is a triangle number then we shall call the word a triangle word. ;; Using words.txt ( right click and ' Save Link / Target As ... ' ) , a 16 K text file containing nearly two - thousand common English words , how many are triangle ;; words? (labels ((word-value (word) (summation word :key #'letter-number)) (triangle-word-p (word) (trianglep (word-value word)))) (count-if #'triangle-word-p (parse-strings-file "data/042-words.txt")))) (defun problem-43 () The number , 1406357289 , is a 0 to 9 pandigital number because it is made up of each of the digits 0 to 9 in some order , but it also has a rather ;; interesting sub-string divisibility property. ;; Let d1 be the 1st digit , d2 be the 2nd digit , and so on . In this way , we ;; note the following: ;; d2d3d4=406 is divisible by 2 d3d4d5=063 is divisible by 3 d4d5d6=635 is divisible by 5 d5d6d7=357 is divisible by 7 d6d7d8=572 is divisible by 11 d7d8d9=728 is divisible by 13 d8d9d10=289 is divisible by 17 ;; Find the sum of all 0 to 9 pandigital numbers with this property . (labels ((extract3 (digits start) (digits-to-number (subseq digits start (+ 3 start)))) (interestingp (n) (let ((digits (digits n))) eat shit mathematicians , indexes start from zero (and (dividesp (extract3 digits 1) 2) (dividesp (extract3 digits 2) 3) (dividesp (extract3 digits 3) 5) (dividesp (extract3 digits 4) 7) (dividesp (extract3 digits 5) 11) (dividesp (extract3 digits 6) 13) (dividesp (extract3 digits 7) 17))))) (summation (remove-if-not #'interestingp (pandigitals 0 9))))) (defun problem-44 () Pentagonal numbers are generated by the formula , Pn = n(3n−1)/2 . The first ten pentagonal numbers are : ;; 1 , 5 , 12 , 22 , 35 , 51 , 70 , 92 , 117 , 145 , ... ;; It can be seen that P4 + P7 = 22 + 70 = 92 = P8 . However , their difference , 70 − 22 = 48 , is not pentagonal . ;; Find the pair of pentagonal numbers , and Pk , for which their sum and ;; difference are pentagonal and D = |Pk − Pj| is minimised; what is the value ;; of D? (flet ((interestingp (px py) (and (pentagonp (+ py px)) (pentagonp (- py px))))) (iterate my kingdom for ` CL : INFINITY ` (for y :from 2) (for z :from 3) (for py = (pentagon y)) (for pz = (pentagon z)) (when (>= (- pz py) result) (return result)) (iterate (for x :from (1- y) :downto 1) (for px = (pentagon x)) (when (interestingp px py) (let ((distance (- py px))) (when (< distance result) TODO : This is n't quite right , because this is just the FIRST ;; number we find -- we haven't guaranteed that it's the SMALLEST ;; one we'll ever see. But it happens to accidentally be the ;; correct one, and until I get around to rewriting this with ;; priority queues it'll have to do. (return-from problem-44 distance))) (return)))))) (defun problem-45 () Triangle , pentagonal , and hexagonal numbers are generated by the following ;; formulae: ;; Triangle Tn = n(n+1)/2 1 , 3 , 6 , 10 , 15 , ... Pentagonal Pn = n(3n−1)/2 1 , 5 , 12 , 22 , 35 , ... Hexagonal Hn = n(2n−1 ) 1 , 6 , 15 , 28 , 45 , ... ;; It can be verified that T285 = P165 = H143 = 40755 . ;; ;; Find the next triangle number that is also pentagonal and hexagonal. (iterate (for n :key #'triangle :from 286) (finding n :such-that (and (pentagonp n) (hexagonp n))))) (defun problem-46 () It was proposed by that every odd composite number can ;; be written as the sum of a prime and twice a square. ;; 9 = 7 + 2×1² 15 = 7 + 2×2² 21 = 3 + 2×3² 25 = 7 + 2×3² 27 = 19 + 2×2² 33 = 31 + 2×1² ;; ;; It turns out that the conjecture was false. ;; ;; What is the smallest odd composite that cannot be written as the sum of ;; a prime and twice a square? (flet ((counterexamplep (n) (iterate (for prime :in-vector (sieve n)) (never (squarep (/ (- n prime) 2)))))) (iterate (for i :from 1 :by 2) (finding i :such-that (and (compositep i) (counterexamplep i)))))) (defun problem-47 () The first two consecutive numbers to have two distinct prime factors are : ;; 14 = 2 × 7 15 = 3 × 5 ;; The first three consecutive numbers to have three distinct prime factors are : ;; 644 = 2² × 7 × 23 645 = 3 × 5 × 43 646 = 2 × 17 × 19 ;; Find the first four consecutive integers to have four distinct prime factors each . What is the first of these numbers ? (flet ((factor-count (n) (length (remove-duplicates (prime-factorization n))))) (iterate (with run = 0) (for i :from 1) (if (= 4 (factor-count i)) (incf run) (setf run 0)) (finding (- i 3) :such-that (= run 4))))) (defun problem-48 () The series , 1 ^ 1 + 2 ^ 2 + 3 ^ 3 + ... + 10 ^ 10 = 10405071317 . ;; Find the last ten digits of the series , 1 ^ 1 + 2 ^ 2 + 3 ^ 3 + ... + 1000 ^ 1000 . (-<> (irange 1 1000) (mapcar #'expt <> <>) summation (mod <> (expt 10 10)))) (defun problem-49 () The arithmetic sequence , 1487 , 4817 , , in which each of the terms increases by 3330 , is unusual in two ways : ( i ) each of the three terms are prime , and , ( ii ) each of the 4 - digit numbers are permutations of one ;; another. ;; There are no arithmetic sequences made up of three 1- , 2- , or 3 - digit primes , exhibiting this property , but there is one other 4 - digit increasing ;; sequence. ;; What 12 - digit number do you form by concatenating the three terms in this ;; sequence? (labels ((permutation= (a b) (orderless-equal (digits a) (digits b))) (length>=3 (list) (>= (length list) 3)) (arithmetic-sequence-p (seq) (apply #'= (mapcar (curry #'apply #'-) (n-grams 2 seq)))) (has-arithmetic-sequence-p (seq) (map-combinations (lambda (s) (when (arithmetic-sequence-p s) (return-from has-arithmetic-sequence-p s))) (sort seq #'<) :length 3) nil)) (-<> (primes-in 1000 9999) (equivalence-classes #'permutation= <>) ; find all permutation groups make sure they have at leat 3 elements (mapcar #'has-arithmetic-sequence-p <>) (remove nil <>) (remove-if (lambda (s) (= (first s) 1487)) <>) ; remove the example first (mapcan #'digits <>) digits-to-number))) (defun problem-50 () The prime 41 , can be written as the sum of six consecutive primes : ;; 41 = 2 + 3 + 5 + 7 + 11 + 13 ;; ;; This is the longest sum of consecutive primes that adds to a prime below one - hundred . ;; The longest sum of consecutive primes below one - thousand that adds to a prime , contains 21 terms , and is equal to 953 . ;; Which prime , below one - million , can be written as the sum of the most ;; consecutive primes? (let ((primes (sieve 1000000))) (flet ((score (start) (iterate (with score = 0) (with winner = 0) (for run :from 1) (for prime :in-vector primes :from start) (summing prime :into sum) (while (< sum 1000000)) (when (primep sum) (setf score run winner sum)) (finally (return (values score winner)))))) (iterate (for (values score winner) :key #'score :from 0 :below (length primes)) (finding winner :maximizing score))))) (defun problem-51 () By replacing the 1st digit of the 2 - digit number * 3 , it turns out that six of the nine possible values : 13 , 23 , 43 , 53 , 73 , and 83 , are all prime . ;; By replacing the 3rd and 4th digits of 56**3 with the same digit , this 5 - digit number is the first example having seven primes among the ten generated numbers , yielding the family : 56003 , 56113 , 56333 , 56443 , 56663 , 56773 , and 56993 . Consequently 56003 , being the first member of this ;; family, is the smallest prime with this property. ;; ;; Find the smallest prime which, by replacing part of the number (not necessarily adjacent digits ) with the same digit , is part of an eight prime ;; value family. (labels ((patterns (prime) (iterate (with size = (digits-length prime)) (with indices = (range 0 size)) (for i :from 1 :below size) (appending (combinations indices :length i)))) (apply-pattern-digit (prime pattern new-digit) (iterate (with result = (digits prime)) (for index :in pattern) (when (and (zerop index) (zerop new-digit)) (leave)) (setf (nth index result) new-digit) (finally (return (digits-to-number result))))) (apply-pattern (prime pattern) (iterate (for digit in (irange 0 9)) (for result = (apply-pattern-digit prime pattern digit)) (when (and result (primep result)) (collect result)))) (apply-patterns (prime) (mapcar (curry #'apply-pattern prime) (patterns prime))) (winnerp (prime) (find-if (curry #'length= 8) (apply-patterns prime)))) (-<> (iterate (for i :from 3 :by 2) (thereis (and (primep i) (winnerp i)))) (sort< <>) first))) (defun problem-52 () It can be seen that the number , 125874 , and its double , 251748 , contain ;; exactly the same digits, but in a different order. ;; Find the smallest positive integer , x , such that 2x , 3x , 4x , 5x , and 6x , ;; contain the same digits. (iterate (for i :from 1) (for digits = (digits i)) (finding i :such-that (every (lambda (n) (orderless-equal digits (digits (* n i)))) '(2 3 4 5 6))))) (defun problem-53 () There are exactly ten ways of selecting three from five , 12345 : ;; 123 , 124 , 125 , 134 , 135 , 145 , 234 , 235 , 245 , and 345 ;; In combinatorics , we use the notation , 5C3 = 10 . ;; ;; In general, ;; nCr = n ! / r!(n−r ) ! ;; where r ≤ n , n ! = n×(n−1)× ... ×3×2×1 , and 0 ! = 1 . ;; It is not until n = 23 , that a value exceeds one - million : 23C10 = 1144066 . ;; How many , not necessarily distinct , values of nCr , for 1 ≤ n ≤ 100 , are greater than one - million ? (iterate main (for n :from 1 :to 100) (iterate (for r :from 1 :to n) (for nCr = (binomial-coefficient n r)) (in main (counting (> nCr 1000000)))))) (defun problem-54 () In the card game poker , a hand consists of five cards and are ranked , from ;; lowest to highest, in the following way: ;; ;; High Card: Highest value card. One Pair : Two cards of the same value . Two Pairs : Two different pairs . Three of a Kind : Three cards of the same value . ;; Straight: All cards are consecutive values. ;; Flush: All cards of the same suit. Full House : Three of a kind and a pair . Four of a Kind : Four cards of the same value . Straight Flush : All cards are consecutive values of same suit . Royal Flush : Ten , , Queen , King , Ace , in same suit . ;; ;; The cards are valued in the order: 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , , Queen , King , Ace . ;; If two players have the same ranked hands then the rank made up of the highest value wins ; for example , a pair of eights beats a pair of fives ( see example 1 below ) . But if two ranks tie , for example , both players have ;; a pair of queens, then highest cards in each hand are compared (see example 4 below ) ; if the highest cards tie then the next highest cards are ;; compared, and so on. ;; The file , poker.txt , contains one - thousand random hands dealt to two players . Each line of the file contains ten cards ( separated by a single space ): the first five are Player 1 's cards and the last five are Player ;; 2's cards. You can assume that all hands are valid (no invalid characters ;; or repeated cards), each player's hand is in no specific order, and in each ;; hand there is a clear winner. ;; How many hands does Player 1 win ? (iterate (for line :in-file "data/054-poker.txt" :using #'read-line) (for cards = (mapcar #'euler.poker::parse-card (str:split #\space line))) (for p1 = (take 5 cards)) (for p2 = (drop 5 cards)) (counting (euler.poker::poker-hand-beats-p p1 p2)))) (defun problem-55 () If we take 47 , reverse and add , 47 + 74 = 121 , which is palindromic . ;; ;; Not all numbers produce palindromes so quickly. For example, ;; 349 + 943 = 1292 , 1292 + 2921 = 4213 4213 + 3124 = 7337 ;; That is , 349 took three iterations to arrive at a palindrome . ;; ;; Although no one has proved it yet, it is thought that some numbers, like 196 , never produce a palindrome . A number that never forms a palindrome through the reverse and add process is called a Lychrel number . Due to the ;; theoretical nature of these numbers, and for the purpose of this problem, we shall assume that a number is Lychrel until proven otherwise . In addition you are given that for every number below ten - thousand , it will either ( i ) become a palindrome in less than fifty iterations , or , ( ii ) no ;; one, with all the computing power that exists, has managed so far to map it to a palindrome . In fact , 10677 is the first number to be shown to require ;; over fifty iterations before producing a palindrome: 4668731596684224866951378664 ( 53 iterations , 28 - digits ) . ;; Surprisingly , there are palindromic numbers that are themselves Lychrel numbers ; the first example is 4994 . ;; How many Lychrel numbers are there below ten - thousand ? (labels ((lychrel (n) (+ n (reverse-integer n))) (lychrelp (n) (iterate (repeat 50) (for i :iterating #'lychrel :seed n) (never (palindromep i))))) (iterate (for i :from 0 :below 10000) (counting (lychrelp i))))) (defun problem-56 () A googol ( 10 ^ 100 ) is a massive number : one followed by one - hundred zeros ; 100 ^ 100 is almost unimaginably large : one followed by two - hundred zeros . Despite their size , the sum of the digits in each number is only 1 . ;; Considering natural numbers of the form , a^b , where a , b < 100 , what is the ;; maximum digital sum? (iterate (for-nested ((a :from 1 :below 100) (b :from 1 :below 100))) (maximizing (digital-sum (expt a b))))) (defun problem-57 () It is possible to show that the square root of two can be expressed as an ;; infinite continued fraction. ;; √ 2 = 1 + 1/(2 + 1/(2 + 1/(2 + ... ) ) ) = 1.414213 ... ;; By expanding this for the first four iterations , we get : ;; 1 + 1/2 = 3/2 = 1.5 1 + 1/(2 + 1/2 ) = 7/5 = 1.4 1 + 1/(2 + 1/(2 + 1/2 ) ) = 17/12 = 1.41666 ... 1 + 1/(2 + 1/(2 + 1/(2 + 1/2 ) ) ) = 41/29 = 1.41379 ... ;; The next three expansions are 99/70 , 239/169 , and 577/408 , but the eighth expansion , 1393/985 , is the first example where the number of digits in the ;; numerator exceeds the number of digits in the denominator. ;; In the first one - thousand expansions , how many fractions contain ;; a numerator with more digits than denominator? (iterate (repeat 1000) (for i :initially 1/2 :then (/ (+ 2 i))) (for expansion = (1+ i)) (counting (> (digits-length (numerator expansion)) (digits-length (denominator expansion)))))) (defun problem-58 () Starting with 1 and spiralling anticlockwise in the following way , a square spiral with side length 7 is formed . ;; 37 36 35 34 33 32 31 38 17 16 15 14 13 30 39 18 5 4 3 12 29 40 19 6 1 2 11 28 41 20 7 8 9 10 27 42 21 22 23 24 25 26 43 44 45 46 47 48 49 ;; ;; It is interesting to note that the odd squares lie along the bottom right diagonal , but what is more interesting is that 8 out of the 13 numbers lying along both diagonals are prime ; that is , a ratio of 8/13 ≈ 62 % . ;; If one complete new layer is wrapped around the spiral above , a square spiral with side length 9 will be formed . If this process is continued , ;; what is the side length of the square spiral for which the ratio of primes along both diagonals first falls below 10 % ? (labels ((score (value) (if (primep value) 1 0)) (primes-in-layer (size) (summation (number-spiral-corners size) :key #'score))) (iterate (for size :from 3 :by 2) (for count :from 5 :by 4) (summing (primes-in-layer size) :into primes) (for ratio = (/ primes count)) (finding size :such-that (< ratio 1/10))))) (defun problem-59 () ;; Each character on a computer is assigned a unique code and the preferred standard is ASCII ( American Standard Code for Information Interchange ) . For example , uppercase A = 65 , asterisk ( * ) = 42 , and lowercase k = 107 . ;; ;; A modern encryption method is to take a text file, convert the bytes to ;; ASCII, then XOR each byte with a given value, taken from a secret key. The ;; advantage with the XOR function is that using the same encryption key on the cipher text , restores the plain text ; for example , 65 XOR 42 = 107 , then 107 XOR 42 = 65 . ;; ;; For unbreakable encryption, the key is the same length as the plain text ;; message, and the key is made up of random bytes. The user would keep the ;; encrypted message and the encryption key in different locations, and ;; without both "halves", it is impossible to decrypt the message. ;; ;; Unfortunately, this method is impractical for most users, so the modified ;; method is to use a password as a key. If the password is shorter than the ;; message, which is likely, the key is repeated cyclically throughout the ;; message. The balance for this method is using a sufficiently long password ;; key for security, but short enough to be memorable. ;; Your task has been made easy , as the encryption key consists of three lower ;; case characters. Using cipher.txt (right click and 'Save Link/Target ;; As...'), a file containing the encrypted ASCII codes, and the knowledge that the plain text must contain common English words , decrypt the message ;; and find the sum of the ASCII values in the original text. (let* ((data (-<> "data/059-cipher.txt" read-file-into-string (substitute #\space #\, <>) read-all-from-string)) (raw-words (-<> "/usr/share/dict/words" read-file-into-string (str:split #\newline <>) (mapcar #'string-downcase <>))) (words (make-hash-set :test 'equal :initial-contents raw-words))) (labels ((stringify (codes) (map 'string #'code-char codes)) (apply-cipher (key) (iterate (for number :in data) (for k :in-looping key) (collect (logxor number k)))) (score-keyword (keyword) (-<> (apply-cipher keyword) (stringify <>) (string-downcase <>) (str:words <>) (remove-if-not (curry #'hset-contains-p words) <>) length)) (answer (keyword) ;; (pr (stringify keyword)) ; keyword is "god", lol (summation (apply-cipher keyword)))) (iterate (for-nested ((a :from (char-code #\a) :to (char-code #\z)) (b :from (char-code #\a) :to (char-code #\z)) (c :from (char-code #\a) :to (char-code #\z)))) (for keyword = (list a b c)) (finding (answer keyword) :maximizing (score-keyword keyword)))))) (defun problem-60 () The primes 3 , 7 , 109 , and 673 , are quite remarkable . By taking any two ;; primes and concatenating them in any order the result will always be prime. For example , taking 7 and 109 , both 7109 and 1097 are prime . The sum of these four primes , 792 , represents the lowest sum for a set of four primes ;; with this property. ;; Find the lowest sum for a set of five primes for which any two primes ;; concatenate to produce another prime. (labels-memoized ((concatenates-prime-p (a b) (and (primep (concatenate-integers a b)) (primep (concatenate-integers b a))))) (flet ((satisfiesp (prime primes) (every (curry #'concatenates-prime-p prime) primes))) (iterate main ;; 2 can never be part of the winning set, because if you concatenate it ;; in the last position you get an even number. (with primes = (subseq (sieve 10000) 1)) (for a :in-vector primes :with-index ai) (iterate (for b :in-vector primes :with-index bi :from (1+ ai)) (when (satisfiesp b (list a)) (iterate (for c :in-vector primes :with-index ci :from (1+ bi)) (when (satisfiesp c (list a b)) (iterate (for d :in-vector primes :with-index di :from (1+ ci)) (when (satisfiesp d (list a b c)) (iterate (for e :in-vector primes :from (1+ di)) (when (satisfiesp e (list a b c d)) (in main (return-from problem-60 (+ a b c d e))))))))))))))) (defun problem-61 () Triangle , square , pentagonal , hexagonal , heptagonal , and octagonal numbers ;; are all figurate (polygonal) numbers and are generated by the following ;; formulae: ;; Triangle P3,n = n(n+1)/2 1 , 3 , 6 , 10 , 15 , ... Square P4,n = n² 1 , 4 , 9 , 16 , 25 , ... Pentagonal P5,n = n(3n−1)/2 1 , 5 , 12 , 22 , 35 , ... Hexagonal P6,n = n(2n−1 ) 1 , 6 , 15 , 28 , 45 , ... Heptagonal P7,n = n(5n−3)/2 1 , 7 , 18 , 34 , 55 , ... Octagonal P8,n = n(3n−2 ) 1 , 8 , 21 , 40 , 65 , ... ;; The ordered set of three 4 - digit numbers : 8128 , 2882 , 8281 , has three ;; interesting properties. ;; 1 . The set is cyclic , in that the last two digits of each number is the first two digits of the next number ( including the last number with the first ) . 2 . Each polygonal type : triangle ( P3,127=8128 ) , square ( P4,91=8281 ) , and pentagonal ( ) , is represented by a different number in the ;; set. 3 . This is the only set of 4 - digit numbers with this property . ;; Find the sum of the only ordered set of six cyclic 4 - digit numbers for ;; which each polygonal type: triangle, square, pentagonal, hexagonal, ;; heptagonal, and octagonal, is represented by a different number in the set. (labels ((numbers (generator) (iterate (for i :from 1) (for n = (funcall generator i)) (while (<= n 9999)) (when (>= n 1000) (collect n)))) (split (number) (truncate number 100)) (prefix (number) (when number (nth-value 0 (split number)))) (suffix (number) (when number (nth-value 1 (split number)))) (matches (prefix suffix number) (multiple-value-bind (p s) (split number) (and (or (not prefix) (= prefix p)) (or (not suffix) (= suffix s))))) (choose (numbers used prefix &optional suffix) (-<> numbers (remove-if-not (curry #'matches prefix suffix) <>) (set-difference <> used))) (search-sets (sets) (recursively ((sets sets) (path nil)) (destructuring-bind (set . remaining) sets (if remaining ;; We're somewhere in the middle, recur on any number whose ;; prefix matches the suffix of the previous element. (iterate (for number :in (choose set path (suffix (car path)))) (recur remaining (cons number path))) ;; We're on the last set, we need to find a number that fits between the penultimate element and first element to ;; complete the cycle. (when-let* ((init (first (last path))) (prev (car path)) (final (choose set path (suffix prev) (prefix init)))) (return-from problem-61 (summation (reverse (cons (first final) path)))))))))) (map-permutations #'search-sets (list (numbers #'triangle) (numbers #'square) (numbers #'pentagon) (numbers #'hexagon) (numbers #'heptagon) (numbers #'octagon))))) (defun problem-62 () The cube , 41063625 ( 345³ ) , can be permuted to produce two other cubes : 56623104 ( 384³ ) and 66430125 ( 405³ ) . In fact , 41063625 is the smallest cube which has exactly three permutations of its digits which are also cube . ;; Find the smallest cube for which exactly five permutations of its digits ;; are cube. canonical - repr = > ( count . first - cube ) Basic strategy from [ 1 ] but with some bug fixes . His strategy happens to ;; work for this specific case, but could be incorrect for others. ;; We ca n't just return as soon as we hit the 5th cubic permutation , because what if this cube is actually part of a family of 6 ? Instead we need to ;; check all other cubes with the same number of digits before making a ;; final decision to be sure we don't get fooled. ;; [ 1 ] : -euler-62-cube-five-permutations/ (labels ((canonicalize (cube) (digits-to-number (sort (digits cube) #'>))) (mark (cube) (let ((entry (ensure-gethash (canonicalize cube) scores (cons 0 cube)))) (incf (car entry)) entry))) (iterate (with i = 1) (with target = 5) (with candidates = nil) (for limit :initially 10 :then (* 10 limit)) (iterate (for cube = (cube i)) (while (< cube limit)) (incf i) (for (score . first) = (mark cube)) (cond ((= score target) (push first candidates)) ((> score target) (removef candidates first)))) ; tricksy hobbitses (thereis (apply (nullary #'min) candidates)))))) (defun problem-63 () The 5 - digit number , 16807=7 ^ 5 , is also a fifth power . Similarly , the 9 - digit number , 134217728=8 ^ 9 , is a ninth power . ;; ;; How many n-digit positive integers exist which are also an nth power? (flet ((score (n) ;; 10^n will have n+1 digits, so we never need to check beyond that (iterate (for base :from 1 :below 10) (for value = (expt base n)) (counting (= n (digits-length value))))) (find-bound () it 's 21.something , but I do n't really grok why yet (iterate (for power :from 1) (for maximum-possible-digits = (digits-length (expt 9 power))) (while (>= maximum-possible-digits power)) (finally (return power))))) (iterate (for n :from 1 :below (find-bound)) (summing (score n))))) (defun problem-67 () ;; By starting at the top of the triangle below and moving to adjacent numbers on the row below , the maximum total from top to bottom is 23 . ;; 3 ;; 7 4 2 4 6 ;; 8 5 9 3 ;; That is , 3 + 7 + 4 + 9 = 23 . ;; Find the maximum total from top to bottom in triangle.txt , a 15 K text file containing a triangle with one - hundred rows . ;; NOTE : This is a much more difficult version of Problem 18 . It is not possible to try every route to solve this problem , as there are 299 altogether ! If you could check one trillion ( 1012 ) routes every second it would take over twenty billion years to check them all . There is an ;; efficient algorithm to solve it. (car (reduce (lambda (prev last) (mapcar #'+ prev (mapcar #'max last (rest last)))) (iterate (for line :in-csv-file "data/067-triangle.txt" :delimiter #\space :key #'parse-integer) (collect line)) :from-end t))) (defun problem-69 () Euler 's Totient function , ) [ sometimes called the phi function ] , is ;; used to determine the number of numbers less than n which are relatively prime to n. For example , as 1 , 2 , 4 , 5 , 7 , and 8 , are all less than nine and relatively prime to nine , φ(9)=6 . ;; It can be seen that n=6 produces a maximum n / φ(n ) for n ≤ 10 . ;; Find the value of n ≤ 1,000,000 for which n / φ(n ) is a maximum . (iterate Euler 's Totient function is defined to be : ;; φ(n ) = n * Πₓ(1 - 1 / x ) where x ∈ { prime factors of n } ;; ;; We're looking for the number n that maximizes f(n) = n/φ(n). ;; We can expand this out into: ;; _ n _ _ = _ _ _ _ _ _ _ n _ _ _ _ _ _ _ = _ _ _ _ _ 1 _ _ _ _ _ φ(n ) n * Πₓ(1 - 1 / x ) Πₓ(1 - 1 / x ) ;; ;; We're trying to MAXMIZE this function, which means we're trying to MINIMIZE the denominator : Πₓ(1 - 1 / x ) . ;; ;; Each term in this product is (1 - 1/x), which means that our goals are: ;; 1 . Have as many terms as possible in the product , because all terms are between 0 and 1 , and so decrease the total product when multiplied . 2 . Prefer smaller values of x , because this minimizes ( 1 - 1 / x ) , which ;; minimizes the product as a whole. ;; ;; Note that because we're taking the product over the UNIQUE prime factors ;; of n, and because the n itself has canceled out, all numbers with the same unique prime factorization will have the same value for n / φ(n ) . ;; For example: ;; f(2 * 3 * 5 ) = f(2² * 3⁸ * 5 ) ;; ;; The problem description implies that there is a single number with the maximum value below 1,000,000 , but even if there were multiple answers , it seems reasonable to return the first . This means that the answer ;; we'll be giving will be square-free, because all the larger, squareful ;; versions of that factorization would have the same value for f(n). ;; Not only is it square - free , it must be the product of the first k primes , for some number see why , consider two possible square - free ;; numbers: ;; ;; (p₁ * p₂ * ... * pₓ) ;; (p₂ * p₃ * ... * pₓ₊₁) ;; ;; We noted above that smaller values would minimize the product in the denominator , thus maximizing the result . So given two sets of prime ;; factors with the same cardinality, we prefer the one with smaller ;; numbers. ;; ;; We also noted above that we want as many numbers as possible, without ;; exceeding the limit. ;; Together we can use these two notes to conclude that we simply want the ;; product (p₁ * p₂ * ... * pₓ) for as large an x as possible without ;; exceeding the limit! (for p :in-primes t) (for n :initially 1 :then (* n p)) (for result :previous n) (while (<= n 1000000)) (finally (return result)))) (defun problem-71 () ;; Consider the fraction, n/d, where n and d are positive integers. If n<d and ;; HCF(n,d)=1, it is called a reduced proper fraction. ;; If we list the set of reduced proper fractions for d ≤ 8 in ascending order ;; of size, we get: ;; 1/8 , 1/7 , 1/6 , 1/5 , 1/4 , 2/7 , 1/3 , 3/8 , 2/5 , 3/7 , 1/2 , 4/7 , 3/5 , 5/8 , 2/3 , 5/7 , 3/4 , 4/5 , 5/6 , 6/7 , 7/8 ;; It can be seen that 2/5 is the fraction immediately to the left of 3/7 . ;; By listing the set of reduced proper fractions for d ≤ 1,000,000 in ;; ascending order of size, find the numerator of the fraction immediately to the left of 3/7 . (iterate We could theoretically iterate through F_1000000 til we find 3/7 , but we 'd have about 130000000000 elements to churn though . We can do it much ;; faster. ;; Instead , we start by computing F₇ and finding 3/7 and whatever 's to the left of it . We can find what 's in between these two in the next ;; iteration by taking their mediant, then just repeat until we hit the ;; limit. (with limit = 1000000) (with target = 3/7) (with guess = (iterate (for x :in-farey-sequence (denominator target)) (for px :previous x) (finding px :such-that (= x target)))) (for next = (mediant guess target)) (if (> (denominator next) limit) (return (numerator guess)) (setf guess next)))) (defun problem-73 () ;; Consider the fraction, n/d, where n and d are positive integers. If n<d and ;; HCF(n,d)=1, it is called a reduced proper fraction. ;; If we list the set of reduced proper fractions for d ≤ 8 in ascending order ;; of size, we get: ;; 1/8 , 1/7 , 1/6 , 1/5 , 1/4 , 2/7 , 1/3 , 3/8 , 2/5 , 3/7 , 1/2 , 4/7 , 3/5 , 5/8 , 2/3 , 5/7 , 3/4 , 4/5 , 5/6 , 6/7 , 7/8 ;; It can be seen that there are 3 fractions between 1/3 and 1/2 . ;; How many fractions lie between 1/3 and 1/2 in the sorted set of reduced proper fractions for d ≤ 12,000 ? (iterate Just brute force this one with our fancy sequence iterator . (for x :in-farey-sequence 12000) (while (< x 1/2)) (counting (< 1/3 x)))) (defun problem-74 () The number 145 is well known for the property that the sum of the factorial of its digits is equal to 145 : ;; 1 ! + 4 ! + 5 ! = 1 + 24 + 120 = 145 ;; Perhaps less well known is 169 , in that it produces the longest chain of numbers that link back to 169 ; it turns out that there are only three such ;; loops that exist: ;; 169 → 363601 → 1454 → 169 871 → 45361 → 871 872 → 45362 → 872 ;; ;; It is not difficult to prove that EVERY starting number will eventually get ;; stuck in a loop. For example, ;; 69 → 363600 → 1454 → 169 → 363601 ( → 1454 ) 78 → 45360 → 871 → 45361 ( → 871 ) 540 → 145 ( → 145 ) ;; Starting with 69 produces a chain of five non - repeating terms , but the longest non - repeating chain with a starting number below one million is sixty terms . ;; How many chains , with a starting number below one million , contain exactly sixty non - repeating terms ? (labels ((digit-factorial (n) (summation (digits n) :key #'factorial)) (term-count (n) (iterate (for i :initially n :then (digit-factorial i)) (until (member i prev)) (collect i :into prev) (counting t)))) (iterate (for i :from 1 :below 1000000) (counting (= 60 (term-count i)))))) (defun problem-79 () ;; A common security method used for online banking is to ask the user for three random characters from a passcode . For example , if the passcode was 531278 , they may ask for the 2nd , 3rd , and 5th characters ; the expected reply would be : 317 . ;; The text file , keylog.txt , contains fifty successful login attempts . ;; Given that the three characters are always asked for in order , analyse ;; the file so as to determine the shortest possible secret passcode of ;; unknown length. (let ((attempts (-<> "data/079-keylog.txt" read-all-from-file (mapcar #'digits <>) (mapcar (rcurry #'coerce 'vector) <>)))) ;; Everyone in the forum is assuming that there are no duplicate digits in ;; the passcode, but as someone pointed out this isn't necessarily a safe assumption . If you have attempts of ( 12 21 ) then the shortest passcode would be 121 . So we 'll do things the safe way and just brute force it . (iterate (for passcode :from 1) (finding passcode :such-that (every (rcurry #'subsequencep (digits passcode)) attempts))))) (defun problem-81 () In the 5 by 5 matrix below , the minimal path sum from the top left to the ;; bottom right, by only moving to the right and down, is indicated in bold red and is equal to 2427 . ;; Find the minimal path sum , in matrix.txt , a 31 K text file containing a 80 by 80 matrix , from the top left to the bottom right by only moving right ;; and down. (let* ((data (convert-to-multidimensional-array (iterate (for line :in-csv-file "data/081-matrix.txt" :key #'parse-integer) (collect line)))) (rows (array-dimension data 0)) (cols (array-dimension data 1)) (last-row (1- rows)) (last-col (1- cols)) (down (vec2 0 1)) (right (vec2 1 0)) (top-left (vec2 0 0)) (bottom-right (vec2 last-col last-row)) (minimum-value (iterate (for value :in-array data) (minimizing value)))) (labels ((value-at (point) (aref data (vy point) (vx point))) (neighbors (point) (remove nil (list (when (< (vx point) last-col) (vec2+ point right)) (when (< (vy point) last-row) (vec2+ point down))))) (remaining-moves (point) (+ (- cols (vx point)) (- rows (vy point)))) (heuristic (point) (* minimum-value (remaining-moves point))) (cost (prev point) (declare (ignore prev)) (value-at point))) (summation (astar :start top-left :neighbors #'neighbors :goalp (curry #'vec2= bottom-right) :cost #'cost :heuristic #'heuristic :test #'equalp) :key #'value-at)))) (defun problem-82 () NOTE : This problem is a more challenging version of Problem 81 . ;; The minimal path sum in the 5 by 5 matrix below , by starting in any cell in ;; the left column and finishing in any cell in the right column, and only ;; moving up, down, and right, is indicated in red and bold; the sum is equal to 994 . ;; Find the minimal path sum , in matrix.txt , a 31 K text file containing a 80 by 80 matrix , from the left column to the right column . (let* ((data (convert-to-multidimensional-array (iterate (for line :in-csv-file "data/082-matrix.txt" :key #'parse-integer) (collect line)))) (rows (array-dimension data 0)) (cols (array-dimension data 1)) (last-row (1- rows)) (last-col (1- cols)) (up (vec2 0 -1)) (down (vec2 0 1)) (right (vec2 1 0)) (minimum-value (iterate (for value :in-array data) (minimizing value)))) ;; We can still use A*, we just need to do a little hack to allow it to choose anything in the first column as a starting state : we 'll make the starting state NIL and make everything in the first column its neighbors . (labels ((value-at (point) (aref data (vy point) (vx point))) (neighbors (point) (if (null point) (mapcar (curry #'vec2 0) (range 0 rows)) (remove nil (list (when (< (vx point) last-col) (vec2+ point right)) (when (< 0 (vy point)) (vec2+ point up)) (when (< (vy point) last-row) (vec2+ point down)))))) (remaining-moves (point) (+ (- cols (vx point)) (- rows (vy point)))) (goalp (point) (and point (= last-col (vx point)))) (heuristic (point) (* minimum-value (remaining-moves point))) (cost (prev point) (declare (ignore prev)) (value-at point))) (summation (rest (astar :start nil :neighbors #'neighbors :goalp #'goalp :cost #'cost :heuristic #'heuristic :test #'equalp)) :key #'value-at)))) (defun problem-92 () ;; A number chain is created by continuously adding the square of the digits ;; in a number to form a new number until it has been seen before. ;; ;; For example, 44 → 32 → 13 → 10 → 1 → 1 85 → 89 → 145 → 42 → 20 → 4 → 16 → 37 → 58 → 89 ;; Therefore any chain that arrives at 1 or 89 will become stuck in an ;; endless loop. What is most amazing is that EVERY starting number will eventually arrive at 1 or 89 . ;; How many starting numbers below ten million will arrive at 89 ? (labels ((square-chain-end (i) (if (or (= 1 i) (= 89 i)) i (square-chain-end (iterate (for d :in-digits-of i) (summing (square d))))))) (iterate (for i :from 1 :below 10000000) (counting (= 89 (square-chain-end i)))))) (defun problem-97 () The first known prime found to exceed one million digits was discovered in 1999 , and is a prime of the form 2 ^ 6972593−1 ; it contains exactly 2,098,960 digits . Subsequently other primes , of the form 2^p−1 , ;; have been found which contain more digits. ;; However , in 2004 there was found a massive non - Mersenne prime which contains 2,357,207 digits : 28433×2 ^ 7830457 + 1 . ;; Find the last ten digits of this prime number . (-<> 2 (expt <> 7830457) (* 28433 <>) 1+ (mod <> (expt 10 10)))) (defun problem-99 () Comparing two numbers written in index form like 2 ^ 11 and 3 ^ 7 is not difficult , as any calculator would confirm that 2 ^ 11 = 2048 < 3 ^ 7 = 2187 . ;; However , confirming that 632382 ^ 518061 > 519432 ^ 525806 would be much more difficult , as both numbers contain over three million digits . ;; Using base_exp.txt ( right click and ' Save Link / Target As ... ' ) , a 22 K text file containing one thousand lines with a base / exponent pair on each line , ;; determine which line number has the greatest numerical value. ;; NOTE : The first two lines in the file represent the numbers in the example ;; given above. (iterate (for line-number :from 1) ;; Lisp can compute the exponents, but it takes a really long time. We can ;; avoid having to compute the full values using: ;; ;; log(base^expt) = expt * log(base) ;; ;; Taking the log of each number preserves their ordering, so we can compare ;; the results and still be correct. (for (base exponent) :in-csv-file "data/099-exponents.txt" :key #'parse-integer) (finding line-number :maximizing (* exponent (log base))))) (defun problem-102 () Three distinct points are plotted at random on a Cartesian plane , for which -1000 ≤ x , y ≤ 1000 , such that a triangle is formed . ;; Consider the following two triangles : ;; A(-340,495 ) , B(-153,-910 ) , C(835,-947 ) ;; X(-175,41 ) , ) , Z(574,-645 ) ;; It can be verified that triangle ABC contains the origin , whereas triangle XYZ does not . ;; Using triangles.txt ( right click and ' Save Link / Target As ... ' ) , a 27 K text file containing the co - ordinates of one thousand " random " triangles , find ;; the number of triangles for which the interior contains the origin. ;; NOTE : The first two examples in the file represent the triangles in the ;; example given above. (flet ((parse-file (file) (iterate (for (ax ay bx by cx cy) :in-csv-file file :key #'parse-integer) (collect (list (vec2 ax ay) (vec2 bx by) (vec2 cx cy))))) (check-triangle (a b c) ;; A point is within a triangle if its barycentric coordinates ( with respect to that triangle ) are all within 0 to 1 . (multiple-value-bind (u v w) (barycentric a b c (vec2 0 0)) (and (<= 0 u 1) (<= 0 v 1) (<= 0 w 1))))) (iterate (for (a b c) :in (parse-file "data/102-triangles.txt")) (counting (check-triangle a b c))))) (defun problem-112 () Working from left - to - right if no digit is exceeded by the digit to its left it is called an increasing number ; for example , 134468 . ;; ;; Similarly if no digit is exceeded by the digit to its right it is called a decreasing number ; for example , 66420 . ;; ;; We shall call a positive integer that is neither increasing nor decreasing a " bouncy " number ; for example , . ;; Clearly there can not be any bouncy numbers below one - hundred , but just over half of the numbers below one - thousand ( 525 ) are bouncy . In fact , the least number for which the proportion of bouncy numbers first reaches 50 % is 538 . ;; ;; Surprisingly, bouncy numbers become more and more common and by the time we reach 21780 the proportion of bouncy numbers is equal to 90 % . ;; ;; Find the least number for which the proportion of bouncy numbers is exactly 99 % . (flet ((bouncyp (integer) (iterate (for digit :in-digits-of integer) (for prev :previous digit) (unless-first-time (oring (< prev digit) :into increasing) (oring (> prev digit) :into decreasing)) (thereis (and increasing decreasing))))) (iterate (for i :from 1) (for total :from 1) (counting (bouncyp i) :into bouncy) (finding i :such-that (= (/ bouncy total) 99/100))))) (defun problem-145 () ;; Some positive integers n have the property that the sum [ n + reverse(n) ] consists entirely of odd ( decimal ) digits . For instance , 36 + 63 = 99 and 409 + 904 = 1313 . We will call such numbers reversible ; so 36 , 63 , 409 , and 904 are reversible . Leading zeroes are not allowed in either n or ;; reverse(n). ;; There are 120 reversible numbers below one - thousand . ;; How many reversible numbers are there below one - billion ( 10 ^ 9 ) ? (flet ((reversiblep (n) (let ((reversed (reverse-integer n))) (values (unless (zerop (digit 0 n)) (every #'oddp (digits (+ n reversed)))) reversed)))) (iterate TODO : improve this one ( with limit = 1000000000 ) there are no 9 - digit reversible numbers ... (with limit = 100000000) (with done = (make-array limit :element-type 'bit :initial-element 0)) (for i :from 1 :below limit) (unless (= 1 (aref done i)) (for (values reversible j) = (reversiblep i)) (setf (aref done j) 1) (when reversible (summing (if (= i j) 1 2))))))) (defun problem-206 () (declare (optimize speed)) ;; Find the unique positive integer whose square has the form 1_2_3_4_5_6_7_8_9_0 , where each “ _ ” is a single digit . (flet ((targetp (i) (declare (type fixnum i)) (and (= 0 (nth-digit 0 i)) (= 9 (nth-digit 2 i)) (= 8 (nth-digit 4 i)) (= 7 (nth-digit 6 i)) (= 6 (nth-digit 8 i)) (= 5 (nth-digit 10 i)) (= 4 (nth-digit 12 i)) (= 3 (nth-digit 14 i)) (= 2 (nth-digit 16 i)) (= 1 (nth-digit 18 i))))) ;; The square ends with a 0, which means the original number must also end in 0 . This means the original number has to be divisible by 10 , so we ;; can take bigger steps. (iterate (with min = (round-to (sqrt 1020304050607080900) 10)) (with max = (floor (sqrt 1929394959697989990))) (for i :from min :to max :by 10) (finding i :such-that (targetp (square i)))))) (defun problem-315 () Full description too long , see (labels ((digit-to-bits (n) ;; We'll represent the lit segments of a clock as bits: ;; ;; - 1 ;; | | 2 3 ;; - 0 ;; | | 4 5 ;; - 6 (case n ;; 6543210 (0 #b1111110) (1 #b0101000) (2 #b1011011) (3 #b1101011) (4 #b0101101) (5 #b1100111) (6 #b1110111) (7 #b0101110) (8 #b1111111) (9 #b1101111) (t #b0000000))) (transition-sam (previous current) turns off everything lit in the previous number , and turns ;; on everything lit in the current one. (let ((p (digit-to-bits previous)) (c (digit-to-bits current))) (+ (logcount p) (logcount c)))) (transition-max (previous current) only turns off the things that need to be turned off , and ;; only turns on the things that need to be turned on. This is ;; just xor. (let ((p (digit-to-bits previous)) (c (digit-to-bits current))) (logcount (logxor p c)))) (transition (transition-function previous-digits current-digits) ;; The new digits will probably be shorter than the old digits. (summation (mapcar-long transition-function nil previous-digits current-digits))) (run-clock (seed) (iterate (for current :in-list (mapcar (rcurry #'digits :from-end t) (digital-roots seed)) :finally nil) (for prev :previous current :initially nil) (summing (transition #'transition-sam prev current) :into sam) (summing (transition #'transition-max prev current) :into max) (finally (return (values sam max)))))) (iterate (for n :from (expt 10 7) :to (* 2 (expt 10 7))) (when (primep n) (summing (multiple-value-call #'- (run-clock n))))))) (defun problem-323 () Let y0 , y1 , y2 , ... be a sequence of random unsigned 32 bit integers ( i.e. 0 ≤ yi < 2 ^ 32 , every value equally likely ) . ;; ;; For the sequence xi the following recursion is given: ;; ;; x0 = 0 and ;; xi = x_i-1 | y_i-1, for i > 0. (| is the bitwise-OR operator) ;; ;; It can be seen that eventually there will be an index N such that xi = 2 ^ 32 - 1 ( a bit - pattern of all ones ) for all i ≥ N. ;; ;; Find the expected value of N. ;; Give your answer rounded to 10 digits after the decimal point . (labels ;; Assuming a perfectly uniform random number generator, each bit of each ;; randomly-generated bit will be independent of the others. So we can treat this problem as a set of 32 independent trials , and are trying to find the expected numbers of iterations required for all 32 ;; trials to succeed at least once. ;; ;; We can start by actually doing the experiments. This will be ;; impractical for large numbers of parallel trials, but gives us a way to ;; sanity check our work later. ((empirical-test () (iterate (counting t) (until (randomp)))) (empirical-tests (runners) (iterate (repeat runners) (maximizing (empirical-test)))) (run-empirical-tests (runners) (coerce (iterate (repeat 1000000) (averaging (empirical-tests runners))) 'double-float)) Running the experiments for 32 parallel trials enough times to get 10 ;; digits of accuracy is computationally infeasible, so we'll need to use ;; some math. ;; ;; The expected value the problem is looking for is: ;; ( 1 * P(finishing on turn 1 ) ) + ( 2 * P(finishing on turn 2 ) ) + ;; ... + ;; (n * P(finishing on turn n)) ;; ;; We solve this by finding a closed form solution for P(finishing on turn n ) , and then adding enough terms to get our ten digits of ;; precision. (probability-of-finishing-by (runners n) ;; The probability of a single run finishing on or before turn N is ;; given by the cumulative distribution function of the geometric ;; distribution. ;; ;; Because all the trials are independent, we can multiply their ;; probabilities to find the probability for the group as a whole. (expt (geometric-cdf 0.5d0 n) runners)) (probability-of-finishing-on (runners n) ;; The probability of finishing EXACTLY on turn N can be found by taking N 's cumulative probability and subtracting N-1 's cumulative ;; probability. (- (probability-of-finishing-by runners n) (probability-of-finishing-by runners (1- n)))) (expected-value (runners) (iterate (for n :from 1 :below 1000) (for prob = (probability-of-finishing-on runners n)) (summing (* n prob)))) (sanity-check (runners) (assert (= (round-decimal (run-empirical-tests runners) 1) (round-decimal (expected-value runners) 1))))) (when nil (iterate (for i :from 1 :to 6) (sanity-check i))) (round-decimal (expected-value 32) 10))) (defun problem-345 () ;; We define the Matrix Sum of a matrix as the maximum sum of matrix elements ;; with each element being the only one in his row and column. For example, the Matrix Sum of the matrix below equals 3315 ( = 863 + 383 + 343 + 959 ;; + 767): ;; 7 53 183 439 863 497 383 563 79 973 287 63 343 169 583 627 343 773 959 943 767 473 103 699 303 ;; ;; Find the Matrix Sum of: ... (let ((matrix (copy-array #2a(( 7 53 183 439 863 497 383 563 79 973 287 63 343 169 583) (627 343 773 959 943 767 473 103 699 303 957 703 583 639 913) (447 283 463 29 23 487 463 993 119 883 327 493 423 159 743) (217 623 3 399 853 407 103 983 89 463 290 516 212 462 350) (960 376 682 962 300 780 486 502 912 800 250 346 172 812 350) (870 456 192 162 593 473 915 45 989 873 823 965 425 329 803) (973 965 905 919 133 673 665 235 509 613 673 815 165 992 326) (322 148 972 962 286 255 941 541 265 323 925 281 601 95 973) (445 721 11 525 473 65 511 164 138 672 18 428 154 448 848) (414 456 310 312 798 104 566 520 302 248 694 976 430 392 198) (184 829 373 181 631 101 969 613 840 740 778 458 284 760 390) (821 461 843 513 17 901 711 993 293 157 274 94 192 156 574) ( 34 124 4 878 450 476 712 914 838 669 875 299 823 329 699) (815 559 813 459 522 788 168 586 966 232 308 833 251 631 107) (813 883 451 509 615 77 281 613 459 205 380 274 302 35 805))))) The hungarian algorithm finds a minimal assignment , but we want a maximal ;; one, so we'll just negate all the values and flip the sign at the end. (do-array (val matrix) (negatef val)) (iterate (for (row . col) :in (euler.hungarian:find-minimal-assignment matrix)) (summing (- (aref matrix row col)))))) (defun problem-346 () The number 7 is special , because 7 is 111 written in base 2 , and 11 written in base 6 ( i.e. 7_10 = 11_6 = 111_2 ) . In other words , 7 is a repunit in at least two bases b > 1 . ;; ;; We shall call a positive integer with this property a strong repunit. It can be verified that there are 8 strong repunits below 50 : { 1,7,13,15,21,31,40,43 } . Furthermore , the sum of all strong repunits below 1000 equals 15864 . ;; Find the sum of all strong repunits below 10 ^ 12 . (iterate Let 's start with a few observations . First , 1 is a repunit in ALL bases , and 2 is n't a repunit in any base . ;; Next , EVERY number ` n ` greater than 2 is a repunit in base ` n - 1 ` , because it will be ` 11 ` in that base . So every number already fulfills half the requirements of the problem . This means we only need to find and sum all the numbers are repunits in at least one more base , and they 'll be of the form ` 11[1]+ ` in that base . ;; ;; Instead of iterating through each number trying to search for a base that ;; it happens to be a repunit in, it's faster if we iterate through the ;; possible BASES instead and generate all their repunits below the limit. ;; Observe how new repunits can be iteratively formed for a given base `b`: ;; R₁ = 1 = 1 R₂ = 11 = 1 + b¹ = 111 = 1 + b¹ + b² R₄ = 1111 = 1 + b¹ + b² + b³ ;; ... ;; ;; We can use a set to store the results to avoid overcounting numbers that are repunits in more than two bases . (with limit = (expt 10 12)) (with strong-repunits = (make-hash-set :initial-contents '(1))) (for base :from 2 :to (sqrt limit)) (iterate To check a particular base we 'll start at number 111 in that base , because we 've already accounted for 1 and 11 in our previous ;; assumptions. ;; This is why we only iterate up to √b in the outer loop : the first number we 're going to be checking is ` 111 = 1 + b¹ + b² ` , and so any ;; base higher than √b would immediately exceed the limit. We could ;; probably narrow the range a bit further, but it's plenty fast already. (for n :first (+ 1 base (expt base 2)) :then (+ 1 (* base n))) (while (< n limit)) (hset-insert! strong-repunits n)) (finally (return (hset-reduce strong-repunits #'+))))) (defun problem-357 () Consider the divisors of 30 : 1,2,3,5,6,10,15,30 . It can be seen that for every divisor d of 30 , d+30 / d is prime . ;; Find the sum of all positive integers n not exceeding 100 000 000 such that ;; for every divisor d of n, d+n/d is prime. (labels ((check-divisor (n d) (primep (+ d (truncate n d)))) (prime-generating-integer-p (n) (declare (optimize speed) (type fixnum n) (inline divisors-up-to-square-root)) (every (curry #'check-divisor n) (divisors-up-to-square-root n)))) ;; Observations about the candidate numbers, from various places around the ;; web, with my notes for humans: ;; ;; * n+1 must be prime. ;; Every number has 1 has a factor , which means one of the tests will be to see if ) is prime . ;; * n must be even ( except the edge case of 1 ) . ;; ;; We know this because n+1 must be prime, and therefore odd, so n itself ;; must be even. ;; * ) must be prime . ;; Because all candidates are even , they all have 2 as a divisor ( see ;; above), and so we can do this check before finding all the divisors. ;; ;; * n must be squarefree. ;; ;; Consider when n is squareful: then there is some prime that occurs more ;; than once in its factorization. Choosing this prime as the divisor for the formula gives us d+(n / d ) . We know that n / d will still be divisible ;; by d, because we chose a d that occurs multiple times in the factorization . Obviously d itself is divisible by our entire ;; formula is divisible by d, and so not prime. ;; ;; Unfortunately this doesn't really help us much, because there's no ;; efficient way to tell if a number is squarefree (see ;; ). ;; ;; * We only have to check d <= sqrt(n). ;; ;; For each divisor d of n we know there's a twin divisor d' such that ;; d * d' = n (that's what it MEANS for d to be a divisor of n). ;; ;; If we plug d into the formula we have d + n/d. ;; We know that n/d = d', and so we have d + d'. ;; ;; If we plug d' into the formula we have d' + n/d'. ;; We know that n/d' = d, and so we have d' + d. ;; ;; This means that plugging d or d' into the formula both result in the same number , so we only need to bother checking one of them . (1+ (iterate edge case : skip 2 ( candidiate 1 ) , we 'll add it at the end (for prime :in-vector (sieve (1+ 100000000)) :from 1) (for candidate = (1- prime)) (when (and (check-divisor candidate 2) (prime-generating-integer-p candidate)) (summing candidate)))))) (defun problem-387 () A or Niven number is a number that is divisible by the sum of its digits . 201 is a number because it is divisible by 3 ( the sum of its digits . ) When we truncate the last digit from 201 , we get 20 , which is a number . When we truncate the last digit from 20 , we get 2 , which is also a number . ;; Let 's call a number that , while recursively truncating the last digit , always results in a number a right truncatable ;; number. ;; Also : 201/3=67 which is prime . Let 's call a number that , when divided by the sum of its digits , results in a prime a strong number . ;; Now take the number 2011 which is prime . When we truncate the last digit from it we get 201 , a strong number that is also right truncatable . Let 's call such primes strong , right truncatable primes . ;; You are given that the sum of the strong , right truncatable primes less than 10000 is 90619 . ;; Find the sum of the strong , right truncatable primes less than 10 ^ 14 . (labels ((harshadp (number) (dividesp number (digital-sum number))) (strong-harshad-p (number) (multiple-value-bind (result remainder) (truncate number (digital-sum number)) (and (zerop remainder) (primep result)))) (right-truncatable-harshad-p (number) (iterate (for i :first number :then (truncate-number-right i 1)) (until (zerop i)) (always (harshadp i)))) (strong-right-truncatable-harshad-p (number) A " strong , right - truncatable number " is a number that is both a strong number and a right - truncatable number . Note that after the first truncation the rest no longer ;; need to be strong -- it's enough for this number itself to be ;; strong. (and (strong-harshad-p number) (right-truncatable-harshad-p number))) (strong-right-truncatable-harshad-prime-p (number) A " strong , right - truncatable prime " is not itself a number ! Prime numbers can never be numbers ;; (except for single-digit numbers), because otherwise they would ;; have to have a divisor (the sum of their digits) (thanks ;; lebossle). ;; ;; What we're looking for here are prime numbers for whom we can chop off the right digit and get strong , truncatable ;; numbers. (and (primep number) (strong-right-truncatable-harshad-p (truncate-number-right number 1)))) (harshad-total (limit) Instead of trying to check every number below 10 ^ 14 for primality , we can recursively build right - truncatable ;; numbers until we hit a non-Harshad (or the limit), then test ;; that for strong-right-truncatable-harshad-prime-ness. ;; ;; If we work from the left (starting at the high order digits) and make sure the number is a number at each step , ;; we automatically ensure it's right truncatable. (recursively ((n 0)) (cond ((>= n limit) 0) ((or (zerop n) (harshadp n)) (iterate (for digit :from (if (zerop n) 1 0) :to 9) (summing (recur (append-digit digit n))))) ((strong-right-truncatable-harshad-prime-p n) n) (t 0))))) (harshad-total (expt 10 14)))) ;;;; Tests -------------------------------------------------------------------- (test p10 (is (= 142913828922 (problem-10)))) (test p11 (is (= 70600674 (problem-11)))) (test p12 (is (= 76576500 (problem-12)))) (test p13 (is (= 5537376230 (problem-13)))) (test p14 (is (= 837799 (problem-14)))) (test p15 (is (= 137846528820 (problem-15)))) (test p16 (is (= 1366 (problem-16)))) (test p17 (is (= 21124 (problem-17)))) (test p18 (is (= 1074 (problem-18)))) (test p19 (is (= 171 (problem-19)))) (test p20 (is (= 648 (problem-20)))) (test p21 (is (= 31626 (problem-21)))) (test p22 (is (= 871198282 (problem-22)))) (test p23 (is (= 4179871 (problem-23)))) (test p24 (is (= 2783915460 (problem-24)))) (test p25 (is (= 4782 (problem-25)))) (test p26 (is (= 983 (problem-26)))) (test p27 (is (= -59231 (problem-27)))) (test p28 (is (= 669171001 (problem-28)))) (test p29 (is (= 9183 (problem-29)))) (test p30 (is (= 443839 (problem-30)))) (test p31 (is (= 73682 (problem-31)))) (test p32 (is (= 45228 (problem-32)))) (test p33 (is (= 100 (problem-33)))) (test p34 (is (= 40730 (problem-34)))) (test p35 (is (= 55 (problem-35)))) (test p36 (is (= 872187 (problem-36)))) (test p37 (is (= 748317 (problem-37)))) (test p38 (is (= 932718654 (problem-38)))) (test p39 (is (= 840 (problem-39)))) (test p40 (is (= 210 (problem-40)))) (test p41 (is (= 7652413 (problem-41)))) (test p42 (is (= 162 (problem-42)))) (test p43 (is (= 16695334890 (problem-43)))) (test p44 (is (= 5482660 (problem-44)))) (test p45 (is (= 1533776805 (problem-45)))) (test p46 (is (= 5777 (problem-46)))) (test p47 (is (= 134043 (problem-47)))) (test p48 (is (= 9110846700 (problem-48)))) (test p49 (is (= 296962999629 (problem-49)))) (test p50 (is (= 997651 (problem-50)))) (test p51 (is (= 121313 (problem-51)))) (test p52 (is (= 142857 (problem-52)))) (test p53 (is (= 4075 (problem-53)))) (test p54 (is (= 376 (problem-54)))) (test p55 (is (= 249 (problem-55)))) (test p56 (is (= 972 (problem-56)))) (test p57 (is (= 153 (problem-57)))) (test p58 (is (= 26241 (problem-58)))) (test p59 (is (= 107359 (problem-59)))) (test p60 (is (= 26033 (problem-60)))) (test p61 (is (= 28684 (problem-61)))) (test p62 (is (= 127035954683 (problem-62)))) (test p63 (is (= 49 (problem-63)))) (test p67 (is (= 7273 (problem-67)))) (test p69 (is (= 510510 (problem-69)))) (test p71 (is (= 428570 (problem-71)))) (test p73 (is (= 7295372 (problem-73)))) (test p74 (is (= 402 (problem-74)))) (test p79 (is (= 73162890 (problem-79)))) (test p81 (is (= 427337 (problem-81)))) (test p82 (is (= 260324 (problem-82)))) (test p92 (is (= 8581146 (problem-92)))) (test p97 (is (= 8739992577 (problem-97)))) (test p99 (is (= 709 (problem-99)))) (test p102 (is (= 228 (problem-102)))) (test p145 (is (= 608720 (problem-145)))) (test p206 (is (= 1389019170 (problem-206)))) (test p315 (is (= 13625242 (problem-315)))) (test p323 (is (= 6.3551758451d0 (problem-323)))) (test p345 (is (= 13938 (problem-345)))) (test p346 (is (= 336108797689259276 (problem-346)))) (test p357 (is (= 1739023853137 (problem-357)))) (test p387 (is (= 696067597313468 (problem-387)))) (defun run-tests () (1am:run))
null
https://raw.githubusercontent.com/sjl/euler/29cd8242172a2d11128439bb99217a0a859057ed/src/problems.lisp
lisp
in red. horizontal vertical backslash \ slash / The sequence of triangle numbers is generated by adding the natural divisors? The following iterative sequence is defined for the set of positive integers: n → n/2 (n is even) n → 3n + 1 (n is odd) sequence: corner. in words, how many letters would be used? By starting at the top of the triangle below and moving to adjacent numbers 3 8 5 9 3 Find the maximum total from top to bottom of the triangle below. it can not be solved by brute force , and requires a clever method! ;o) You are given the following information, but you may prefer to do some research for yourself. Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers. therefore d(220 ) = 284 . The proper divisors of 284 are 1 , 2 , 4 , so d(284 ) = 220 . begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score. What is the total of all the name scores in the file? A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of number. A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n. limit cannot be reduced any further by analysis even though it is known abundant numbers is less than this limit. Find the sum of all the positive integers which cannot be written as the permutations are listed numerically or alphabetically, we call it The Fibonacci sequence is defined by the recurrence relation: cycle in its decimal fraction part. Euler discovered the remarkable quadratic formula: n² + n + 41 Considering quadratics of the form: where |n| is the modulus/absolute value of n Find the product of the coefficients, a and b, for the quadratic expression that produces the maximum number of primes for consecutive values of n, formed in the same way? If they are then placed in numerical order, with any repeats removed, we How many distinct terms are in the sequence generated by a^b for powers of their digits. We want to find a limit N that's bigger than the maximum possible sum for its number of digits. Then just brute-force the thing. for example , the 5 - digit number , 15234 , is Find the sum of all products whose multiplicand/multiplier/product identity include it once in your sum. denominator. find the value of the denominator. Find the sum of all numbers which are equal to the sum of the factorial of their digits. bases. (Please note that the palindromic number, in either base, may not include possible to continuously remove digits from left to right, and remain prime to right and right to left. least two products of it result is only ever going to grow larger, so once we pass the An irrational decimal fraction is created by concatenating the positive integers: If dn represents the nth digit of the fractional part, find the value of the following expression. and is also prime. The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a word value. For value is a triangle number then we shall call the word a triangle word. words? interesting sub-string divisibility property. note the following: difference are pentagonal and D = |Pk − Pj| is minimised; what is the value of D? number we find -- we haven't guaranteed that it's the SMALLEST one we'll ever see. But it happens to accidentally be the correct one, and until I get around to rewriting this with priority queues it'll have to do. formulae: Find the next triangle number that is also pentagonal and hexagonal. be written as the sum of a prime and twice a square. It turns out that the conjecture was false. What is the smallest odd composite that cannot be written as the sum of a prime and twice a square? another. sequence. sequence? find all permutation groups remove the example This is the longest sum of consecutive primes that adds to a prime below consecutive primes? family, is the smallest prime with this property. Find the smallest prime which, by replacing part of the number (not value family. exactly the same digits, but in a different order. contain the same digits. In general, lowest to highest, in the following way: High Card: Highest value card. Straight: All cards are consecutive values. Flush: All cards of the same suit. The cards are valued in the order: for example , a pair of eights beats a pair of fives a pair of queens, then highest cards in each hand are compared (see example if the highest cards tie then the next highest cards are compared, and so on. 2's cards. You can assume that all hands are valid (no invalid characters or repeated cards), each player's hand is in no specific order, and in each hand there is a clear winner. Not all numbers produce palindromes so quickly. For example, Although no one has proved it yet, it is thought that some numbers, like theoretical nature of these numbers, and for the purpose of this problem, one, with all the computing power that exists, has managed so far to map it over fifty iterations before producing a palindrome: the first example is 4994 . maximum digital sum? infinite continued fraction. numerator exceeds the number of digits in the denominator. a numerator with more digits than denominator? It is interesting to note that the odd squares lie along the bottom right that is , a ratio of 8/13 ≈ 62 % . what is the side length of the square spiral for which the ratio of primes Each character on a computer is assigned a unique code and the preferred A modern encryption method is to take a text file, convert the bytes to ASCII, then XOR each byte with a given value, taken from a secret key. The advantage with the XOR function is that using the same encryption key on for example , 65 XOR 42 = 107 , For unbreakable encryption, the key is the same length as the plain text message, and the key is made up of random bytes. The user would keep the encrypted message and the encryption key in different locations, and without both "halves", it is impossible to decrypt the message. Unfortunately, this method is impractical for most users, so the modified method is to use a password as a key. If the password is shorter than the message, which is likely, the key is repeated cyclically throughout the message. The balance for this method is using a sufficiently long password key for security, but short enough to be memorable. case characters. Using cipher.txt (right click and 'Save Link/Target As...'), a file containing the encrypted ASCII codes, and the knowledge and find the sum of the ASCII values in the original text. (pr (stringify keyword)) ; keyword is "god", lol primes and concatenating them in any order the result will always be prime. with this property. concatenate to produce another prime. 2 can never be part of the winning set, because if you concatenate it in the last position you get an even number. are all figurate (polygonal) numbers and are generated by the following formulae: interesting properties. set. which each polygonal type: triangle, square, pentagonal, hexagonal, heptagonal, and octagonal, is represented by a different number in the set. We're somewhere in the middle, recur on any number whose prefix matches the suffix of the previous element. We're on the last set, we need to find a number that fits complete the cycle. are cube. work for this specific case, but could be incorrect for others. check all other cubes with the same number of digits before making a final decision to be sure we don't get fooled. tricksy hobbitses How many n-digit positive integers exist which are also an nth power? 10^n will have n+1 digits, so we never need to check beyond that By starting at the top of the triangle below and moving to adjacent numbers 7 4 8 5 9 3 efficient algorithm to solve it. used to determine the number of numbers less than n which are relatively We're looking for the number n that maximizes f(n) = n/φ(n). We can expand this out into: We're trying to MAXMIZE this function, which means we're trying to Each term in this product is (1 - 1/x), which means that our goals are: minimizes the product as a whole. Note that because we're taking the product over the UNIQUE prime factors of n, and because the n itself has canceled out, all numbers with the For example: The problem description implies that there is a single number with the we'll be giving will be square-free, because all the larger, squareful versions of that factorization would have the same value for f(n). numbers: (p₁ * p₂ * ... * pₓ) (p₂ * p₃ * ... * pₓ₊₁) We noted above that smaller values would minimize the product in the factors with the same cardinality, we prefer the one with smaller numbers. We also noted above that we want as many numbers as possible, without exceeding the limit. product (p₁ * p₂ * ... * pₓ) for as large an x as possible without exceeding the limit! Consider the fraction, n/d, where n and d are positive integers. If n<d and HCF(n,d)=1, it is called a reduced proper fraction. of size, we get: ascending order of size, find the numerator of the fraction immediately to faster. iteration by taking their mediant, then just repeat until we hit the limit. Consider the fraction, n/d, where n and d are positive integers. If n<d and HCF(n,d)=1, it is called a reduced proper fraction. of size, we get: it turns out that there are only three such loops that exist: It is not difficult to prove that EVERY starting number will eventually get stuck in a loop. For example, A common security method used for online banking is to ask the user for the expected the file so as to determine the shortest possible secret passcode of unknown length. Everyone in the forum is assuming that there are no duplicate digits in the passcode, but as someone pointed out this isn't necessarily a safe bottom right, by only moving to the right and down, is indicated in bold and down. the left column and finishing in any cell in the right column, and only moving up, down, and right, is indicated in red and bold; the sum is equal We can still use A*, we just need to do a little hack to allow it to A number chain is created by continuously adding the square of the digits in a number to form a new number until it has been seen before. For example, endless loop. What is most amazing is that EVERY starting number will it contains exactly have been found which contain more digits. determine which line number has the greatest numerical value. given above. Lisp can compute the exponents, but it takes a really long time. We can avoid having to compute the full values using: log(base^expt) = expt * log(base) Taking the log of each number preserves their ordering, so we can compare the results and still be correct. the number of triangles for which the interior contains the origin. example given above. A point is within a triangle if its barycentric coordinates for example , 134468 . Similarly if no digit is exceeded by the digit to its right it is called for example , 66420 . We shall call a positive integer that is neither increasing nor decreasing for example , . Surprisingly, bouncy numbers become more and more common and by the time we Find the least number for which the proportion of bouncy numbers is exactly Some positive integers n have the property that the sum [ n + reverse(n) ] so 36 , 63 , 409 , and reverse(n). Find the unique positive integer whose square has the form The square ends with a 0, which means the original number must also end can take bigger steps. We'll represent the lit segments of a clock as bits: - 1 | | 2 3 - 0 | | 4 5 - 6 6543210 on everything lit in the current one. only turns on the things that need to be turned on. This is just xor. The new digits will probably be shorter than the old digits. For the sequence xi the following recursion is given: x0 = 0 and xi = x_i-1 | y_i-1, for i > 0. (| is the bitwise-OR operator) It can be seen that eventually there will be an index N such that Find the expected value of N. Assuming a perfectly uniform random number generator, each bit of each randomly-generated bit will be independent of the others. So we can trials to succeed at least once. We can start by actually doing the experiments. This will be impractical for large numbers of parallel trials, but gives us a way to sanity check our work later. digits of accuracy is computationally infeasible, so we'll need to use some math. The expected value the problem is looking for is: ... + (n * P(finishing on turn n)) We solve this by finding a closed form solution for P(finishing on precision. The probability of a single run finishing on or before turn N is given by the cumulative distribution function of the geometric distribution. Because all the trials are independent, we can multiply their probabilities to find the probability for the group as a whole. The probability of finishing EXACTLY on turn N can be found by probability. We define the Matrix Sum of a matrix as the maximum sum of matrix elements with each element being the only one in his row and column. For example, + 767): Find the Matrix Sum of: ... one, so we'll just negate all the values and flip the sign at the end. We shall call a positive integer with this property a strong repunit. It Instead of iterating through each number trying to search for a base that it happens to be a repunit in, it's faster if we iterate through the possible BASES instead and generate all their repunits below the limit. Observe how new repunits can be iteratively formed for a given base `b`: ... We can use a set to store the results to avoid overcounting numbers that assumptions. base higher than √b would immediately exceed the limit. We could probably narrow the range a bit further, but it's plenty fast already. for every divisor d of n, d+n/d is prime. Observations about the candidate numbers, from various places around the web, with my notes for humans: * n+1 must be prime. We know this because n+1 must be prime, and therefore odd, so n itself must be even. above), and so we can do this check before finding all the divisors. * n must be squarefree. Consider when n is squareful: then there is some prime that occurs more than once in its factorization. Choosing this prime as the divisor for by d, because we chose a d that occurs multiple times in the formula is divisible by d, and so not prime. Unfortunately this doesn't really help us much, because there's no efficient way to tell if a number is squarefree (see ). * We only have to check d <= sqrt(n). For each divisor d of n we know there's a twin divisor d' such that d * d' = n (that's what it MEANS for d to be a divisor of n). If we plug d into the formula we have d + n/d. We know that n/d = d', and so we have d + d'. If we plug d' into the formula we have d' + n/d'. We know that n/d' = d, and so we have d' + d. This means that plugging d or d' into the formula both result in the number. need to be strong -- it's enough for this number itself to be strong. (except for single-digit numbers), because otherwise they would have to have a divisor (the sum of their digits) (thanks lebossle). What we're looking for here are prime numbers for whom we can numbers. numbers until we hit a non-Harshad (or the limit), then test that for strong-right-truncatable-harshad-prime-ness. If we work from the left (starting at the high order digits) we automatically ensure it's right truncatable. Tests --------------------------------------------------------------------
(in-package :euler) (defun problem-10 () The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17 . Find the sum of all the primes below two million . (summation (sieve 2000000))) (defun problem-11 () In the 20×20 grid below , four numbers along a diagonal line have been marked The product of these numbers is 26 × 63 × 78 × 14 = 1788696 . What is the greatest product of four adjacent numbers in the same direction ( up , down , left , right , or diagonally ) in the 20×20 grid ? (let ((grid #2A((08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08) (49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00) (81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65) (52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91) (22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80) (24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50) (32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70) (67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21) (24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72) (21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95) (78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92) (16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57) (86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58) (19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40) (04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66) (88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69) (04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36) (20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16) (20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54) (01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48)))) (max (iterate (for-nested ((row :from 0 :below 20) (col :from 0 :below 16))) (maximize (* (aref grid row (+ 0 col)) (aref grid row (+ 1 col)) (aref grid row (+ 2 col)) (aref grid row (+ 3 col))))) (iterate (for-nested ((row :from 0 :below 16) (col :from 0 :below 20))) (maximize (* (aref grid (+ 0 row) col) (aref grid (+ 1 row) col) (aref grid (+ 2 row) col) (aref grid (+ 3 row) col)))) (iterate (for-nested ((row :from 0 :below 16) (col :from 0 :below 16))) (maximize (* (aref grid (+ 0 row) (+ 0 col)) (aref grid (+ 1 row) (+ 1 col)) (aref grid (+ 2 row) (+ 2 col)) (aref grid (+ 3 row) (+ 3 col))))) (iterate (for-nested ((row :from 3 :below 20) (col :from 0 :below 16))) (maximize (* (aref grid (- row 0) (+ 0 col)) (aref grid (- row 1) (+ 1 col)) (aref grid (- row 2) (+ 2 col)) (aref grid (- row 3) (+ 3 col)))))))) (defun problem-12 () numbers . So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28 . The first ten terms would be : 1 , 3 , 6 , 10 , 15 , 21 , 28 , 36 , 45 , 55 , ... Let us list the factors of the first seven triangle numbers : 1 : 1 3 : 1,3 6 : 1,2,3,6 10 : 1,2,5,10 15 : 1,3,5,15 21 : 1,3,7,21 28 : 1,2,4,7,14,28 We can see that 28 is the first triangle number to have over five divisors . What is the value of the first triangle number to have over five hundred (iterate (for tri :key #'triangle :from 1) (finding tri :such-that (> (count-divisors tri) 500)))) (defun problem-13 () Work out the first ten digits of the sum of the following one - hundred 50 - digit numbers . (-<> (read-all-from-file "data/013-numbers.txt") summation aesthetic-string (subseq <> 0 10) parse-integer (nth-value 0 <>))) (defun problem-14 () Using the rule above and starting with 13 , we generate the following 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 It can be seen that this sequence ( starting at 13 and finishing at 1 ) contains 10 terms . Although it has not been proved yet ( Collatz Problem ) , it is thought that all starting numbers finish at 1 . Which starting number , under one million , produces the longest chain ? NOTE : Once the chain starts the terms are allowed to go above one million . (iterate (for i :from 1 :below 1000000) (finding i :maximizing #'collatz-length))) (defun problem-15 () Starting in the top left corner of a 2×2 grid , and only being able to move to the right and down , there are exactly 6 routes to the bottom right How many such routes are there through a 20×20 grid ? (binomial-coefficient 40 20)) (defun problem-16 () 2 ^ 15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26 . What is the sum of the digits of the number 2 ^ 1000 ? (digital-sum (expt 2 1000))) (defun problem-17 () If the numbers 1 to 5 are written out in words : one , two , three , four , five , then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total . If all the numbers from 1 to 1000 ( one thousand ) inclusive were written out NOTE : Do not count spaces or hyphens . For example , 342 ( three hundred and forty - two ) contains 23 letters and 115 ( one hundred and fifteen ) contains 20 letters . The use of " and " when writing out numbers is in compliance with British usage , which is awful . (labels ((letters (n) (-<> n (format nil "~R" <>) (count-if #'alpha-char-p <>))) (has-british-and (n) (or (< n 100) (zerop (mod n 100)))) (silly-british-letters (n) (+ (letters n) (if (has-british-and n) 0 3)))) (summation (irange 1 1000) :key #'silly-british-letters))) (defun problem-18 () on the row below , the maximum total from top to bottom is 23 . 7 4 2 4 6 That is , 3 + 7 + 4 + 9 = 23 . NOTE : As there are only 16384 routes , it is possible to solve this problem by trying every route . However , Problem 67 , is the same challenge with (let ((triangle (iterate (for line :in-csv-file "data/018-triangle.txt" :delimiter #\space :key #'parse-integer) (collect line)))) (car (reduce (lambda (prev last) (mapcar #'+ prev (mapcar #'max last (rest last)))) triangle :from-end t)))) (defun problem-19 () 1 Jan 1900 was a Monday . Thirty days has September , April , June and November . All the rest have thirty - one , Saving February alone , Which has twenty - eight , rain or shine . And on leap years , twenty - nine . A leap year occurs on any year evenly divisible by 4 , but not on a century unless it is divisible by 400 . How many Sundays fell on the first of the month during the twentieth century ( 1 Jan 1901 to 31 Dec 2000 ) ? (iterate (for-nested ((year :from 1901 :to 2000) (month :from 1 :to 12))) (counting (-<> (local-time:encode-timestamp 0 0 0 0 1 month year) local-time:timestamp-day-of-week zerop)))) (defun problem-20 () n ! means n × ( n − 1 ) × ... × 3 × 2 × 1 For example , 10 ! = 10 × 9 × ... × 3 × 2 × 1 = 3628800 , and the sum of the digits in the number 10 ! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27 . Find the sum of the digits in the number 100 ! (digital-sum (factorial 100))) (defun problem-21 () For example , the proper divisors of 220 are 1 , 2 , 4 , 5 , 10 , 11 , 20 , 22 , 44 , Evaluate the sum of all the amicable numbers under 10000 . (summation (remove-if-not #'amicablep (range 1 10000)))) (defun problem-22 () Using names.txt , a 46 K text file containing over five - thousand first names , For example , when the list is sorted into alphabetical order , , which is worth 3 + 15 + 12 + 9 + 14 = 53 , is the 938th name in the list . So , would obtain a score of 938 × 53 = 49714 . (labels ((read-names () (-<> "data/022-names.txt" parse-strings-file (sort <> #'string<))) (name-score (name) (summation name :key #'letter-number))) (iterate (for position :from 1) (for name :in (read-names)) (summing (* position (name-score name)))))) (defun problem-23 () 28 would be 1 + 2 + 4 + 7 + 14 = 28 , which means that 28 is a perfect As 12 is the smallest abundant number , 1 + 2 + 3 + 4 + 6 = 16 , the smallest number that can be written as the sum of two abundant numbers is 24 . By mathematical analysis , it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers . However , this upper that the greatest number that can not be expressed as the sum of two sum of two abundant numbers . (let* ((limit 28123) (abundant-numbers (make-hash-set :initial-contents (remove-if-not #'abundantp (irange 1 limit))))) (flet ((abundant-sum-p (n) (iterate (for a :in-hashset abundant-numbers) (when (hset-contains-p abundant-numbers (- n a)) (return t))))) (summation (remove-if #'abundant-sum-p (irange 1 limit)))))) (defun problem-24 () A permutation is an ordered arrangement of objects . For example , 3124 is one possible permutation of the digits 1 , 2 , 3 and 4 . If all of the lexicographic order . The lexicographic permutations of 0 , 1 and 2 are : 012 021 102 120 201 210 What is the millionth lexicographic permutation of the digits 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 and 9 ? (-<> "0123456789" (gathering-vector (:size (factorial (length <>))) (map-permutations (compose #'gather #'parse-integer) <> :copy nil)) (sort <> #'<) (elt <> (1- 1000000)))) (defun problem-25 () Fn = Fn−1 + Fn−2 , where F1 = 1 and F2 = 1 . Hence the first 12 terms will be : F1 = 1 F2 = 1 F3 = 2 F4 = 3 F5 = 5 F6 = 8 F7 = 13 F8 = 21 F9 = 34 F10 = 55 F11 = 89 F12 = 144 The 12th term , F12 , is the first term to contain three digits . What is the index of the first term in the sequence to contain 1000 digits ? (iterate (for f :in-fibonacci t) (for i :from 1) (finding i :such-that (= 1000 (digits-length f))))) (defun problem-26 () A unit fraction contains 1 in the numerator . The decimal representation of the unit fractions with denominators 2 to 10 are given : 1/2 = 0.5 1/3 = 0.(3 ) 1/4 = 0.25 1/5 = 0.2 1/6 = 0.1(6 ) 1/7 = 0.(142857 ) 1/8 = 0.125 1/9 = 0.(1 ) 1/10 = 0.1 Where 0.1(6 ) means 0.166666 ... , and has a 1 - digit recurring cycle . It can be seen that 1/7 has a 6 - digit recurring cycle . Find the value of d < 1000 for which 1 / d contains the longest recurring (iterate 2 and 5 are the only primes that are n't coprime to 10 (for i :in (set-difference (primes-below 1000) '(2 5))) (finding i :maximizing (multiplicative-order 10 i)))) (defun problem-27 () It turns out that the formula will produce 40 primes for the consecutive integer values 0 ≤ n ≤ 39 . However , when n=40 , 40² + 40 + 41 = 40(40 + 1 ) + 41 is divisible by 41 , and certainly when n=41 , 41² + 41 + 41 is clearly divisible by 41 . The incredible formula n² − 79n + 1601 was discovered , which produces 80 primes for the consecutive values 0 ≤ n ≤ 79 . The product of the coefficients , −79 and 1601 , is −126479 . n² + an + b , where |a| < 1000 and |b| ≤ 1000 e.g. |11| = 11 and |−4| = 4 starting with n=0 . (flet ((primes-produced (a b) (iterate (for n :from 0) (while (primep (math n ^ 2 + a n + b))) (counting t)))) (iterate (for-nested ((a :from -999 :to 999) (b :from -1000 :to 1000))) (finding (* a b) :maximizing (primes-produced a b))))) (defun problem-28 () Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows : 21 22 23 24 25 20 7 8 9 10 19 6 1 2 11 18 5 4 3 12 17 16 15 14 13 It can be verified that the sum of the numbers on the diagonals is 101 . What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral (iterate (for size :from 1 :to 1001 :by 2) (summing (apply #'+ (number-spiral-corners size))))) (defun problem-29 () Consider all integer combinations of a^b for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5 : 2²=4 , 2³=8 , 2⁴=16 , 2⁵=32 3²=9 , 3³=27 , 3⁴=81 , 3⁵=243 4²=16 , 4³=64 , 4⁴=256 , 4⁵=1024 5²=25 , 5³=125 , 5⁴=625 , 5⁵=3125 get the following sequence of 15 distinct terms : 4 , 8 , 9 , 16 , 25 , 27 , 32 , 64 , 81 , 125 , 243 , 256 , 625 , 1024 , 3125 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100 ? (length (iterate (for-nested ((a :from 2 :to 100) (b :from 2 :to 100))) (adjoining (expt a b))))) (defun problem-30 () Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits : 1634 = 1⁴ + 6⁴ + 3⁴ + 4⁴ 8208 = 8⁴ + 2⁴ + 0⁴ + 8⁴ 9474 = 9⁴ + 4⁴ + 7⁴ + 4⁴ As 1 = 1⁴ is not a sum it is not included . The sum of these numbers is 1634 + 8208 + 9474 = 19316 . Find the sum of all the numbers that can be written as the sum of fifth (flet ((maximum-sum-for-digits (n) (* (expt 9 5) n)) (digit-power-sum (n) (summation (digits n) :key (rcurry #'expt 5)))) (iterate (with limit = (iterate (for digits :from 1) (for n = (expt 10 digits)) (while (< n (maximum-sum-for-digits digits))) (finally (return n)))) (for i :from 2 :to limit) (when (= i (digit-power-sum i)) (summing i))))) (defun problem-31 () In England the currency is made up of pound , £ , and pence , p , and there are eight coins in general circulation : 1p , 2p , 5p , 10p , 20p , 50p , £ 1 ( 100p ) and £ 2 ( 200p ) . It is possible to make £ 2 in the following way : 1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p How many different ways can £ 2 be made using any number of coins ? (recursively ((amount 200) (coins '(200 100 50 20 10 5 2 1))) (cond ((zerop amount) 1) ((minusp amount) 0) ((null coins) 0) (t (+ (recur (- amount (first coins)) coins) (recur amount (rest coins))))))) (defun problem-32 () We shall say that an n - digit number is pandigital if it makes use of all 1 through 5 pandigital . The product 7254 is unusual , as the identity , 39 × 186 = 7254 , containing multiplicand , multiplier , and product is 1 through 9 pandigital . can be written as a 1 through 9 pandigital . HINT : Some products can be obtained in more than one way so be sure to only (labels ((split (digits a b) (values (digits-to-number (subseq digits 0 a)) (digits-to-number (subseq digits a (+ a b))) (digits-to-number (subseq digits (+ a b))))) (check (digits a b) (multiple-value-bind (a b c) (split digits a b) (when (= (* a b) c) c)))) (-<> (gathering (map-permutations (lambda (digits) (let ((c1 (check digits 3 2)) (c2 (check digits 4 1))) (when c1 (gather c1)) (when c2 (gather c2)))) #(1 2 3 4 5 6 7 8 9) :copy nil)) remove-duplicates summation))) (defun problem-33 () The fraction 49/98 is a curious fraction , as an inexperienced mathematician in attempting to simplify it may incorrectly believe that 49/98 = 4/8 , which is correct , is obtained by cancelling the 9s . We shall consider fractions like , 30/50 = 3/5 , to be trivial examples . There are exactly four non - trivial examples of this type of fraction , less than one in value , and containing two digits in the numerator and If the product of these four fractions is given in its lowest common terms , (labels ((safe/ (a b) (unless (zerop b) (/ a b))) (cancel (digit other digits) (destructuring-bind (x y) digits (remove nil (list (when (= digit x) (safe/ other y)) (when (= digit y) (safe/ other x)))))) (cancellations (numerator denominator) (let ((nd (digits numerator)) (dd (digits denominator))) (append (cancel (first nd) (second nd) dd) (cancel (second nd) (first nd) dd)))) (curiousp (numerator denominator) (member (/ numerator denominator) (cancellations numerator denominator))) (trivialp (numerator denominator) (and (dividesp numerator 10) (dividesp denominator 10)))) (iterate (with result = 1) (for numerator :from 10 :to 99) (iterate (for denominator :from (1+ numerator) :to 99) (when (and (curiousp numerator denominator) (not (trivialp numerator denominator))) (mulf result (/ numerator denominator)))) (finally (return (denominator result)))))) (defun problem-34 () 145 is a curious number , as 1 ! + 4 ! + 5 ! = 1 + 24 + 120 = 145 . Note : as 1 ! = 1 and 2 ! = 2 are not sums they are not included . (iterate (for n :from 3 :to 1000000) (when (= n (summation (digits n) :key #'factorial)) (summing n)))) (defun problem-35 () The number , 197 , is called a circular prime because all rotations of the digits : 197 , 971 , and 719 , are themselves prime . There are thirteen such primes below 100 : 2 , 3 , 5 , 7 , 11 , 13 , 17 , 31 , 37 , 71 , 73 , 79 , and 97 . How many circular primes are there below one million ? (labels ((rotate (n distance) (multiple-value-bind (hi lo) (truncate n (expt 10 distance)) (math lo * 10 ^ #(digits-length hi) + hi))) (rotations (n) (mapcar (curry #'rotate n) (range 1 (digits-length n)))) (circular-prime-p (n) (every #'primep (rotations n)))) (iterate (for i :in-vector (sieve 1000000)) (counting (circular-prime-p i))))) (defun problem-36 () The decimal number , 585 = 1001001001 ( binary ) , is palindromic in both Find the sum of all numbers , less than one million , which are palindromic in base 10 and base 2 . leading zeros . ) (iterate (for i :from 1 :below 1000000) (when (and (palindromep i 10) (palindromep i 2)) (summing i)))) (defun problem-37 () The number 3797 has an interesting property . Being prime itself , it is at each stage : 3797 , 797 , 97 , and 7 . Similarly we can work from right to left : 3797 , 379 , 37 , and 3 . Find the sum of the only eleven primes that are both truncatable from left NOTE : 2 , 3 , 5 , and 7 are not considered to be truncatable primes . (labels ((truncations (n) (iterate (for i :from 0 :below (digits-length n)) (collect (truncate-number-left n i)) (collect (truncate-number-right n i)))) (truncatablep (n) (every #'primep (truncations n)))) (iterate (with count = 0) (for i :from 11 :by 2) (when (truncatablep i) (summing i) (incf count)) (while (< count 11))))) (defun problem-38 () Take the number 192 and multiply it by each of 1 , 2 , and 3 : 192 × 1 = 192 192 × 2 = 384 192 × 3 = 576 By concatenating each product we get the 1 to 9 pandigital , 192384576 . We will call 192384576 the concatenated product of 192 and ( 1,2,3 ) The same can be achieved by starting with 9 and multiplying by 1 , 2 , 3 , 4 , and 5 , giving the pandigital , 918273645 , which is the concatenated product of 9 and ( 1,2,3,4,5 ) . What is the largest 1 to 9 pandigital 9 - digit number that can be formed as the concatenated product of an integer with ( 1,2 , ... , n ) where n > 1 ? (labels ((concatenated-product (number i) (apply #'concatenate-integers (iterate (for n :from 1 :to i) (collect (* number n)))))) (iterate main (for base :from 1) base ca n't be more than 5 digits long because we have to concatenate at (while (<= (digits-length base) 5)) (iterate (for n :from 2) (for result = (concatenated-product base n)) nine digit mark we can stop (while (<= (digits-length result) 9)) (when (pandigitalp result) (in main (maximizing result))))))) (defun problem-39 () If p is the perimeter of a right angle triangle with integral length sides , { a , b , c } , there are exactly three solutions for p = 120 . { 20,48,52 } , { 24,45,51 } , { 30,40,50 } For which value of p ≤ 1000 , is the number of solutions maximised ? (iterate (for p :from 1 :to 1000) (finding p :maximizing (length (pythagorean-triplets-of-perimeter p))))) (defun problem-40 () 0.123456789101112131415161718192021 ... It can be seen that the 12th digit of the fractional part is 1 . d1 × d10 × d100 × d1000 × d10000 × d100000 × d1000000 (iterate top (with index = 0) (for digits :key #'digits :from 1) (iterate (for d :in digits) (incf index) (when (member index '(1 10 100 1000 10000 100000 1000000)) (in top (multiplying d)) (when (= index 1000000) (in top (terminate))))))) (defun problem-41 () We shall say that an n - digit number is pandigital if it makes use of all the digits 1 to n exactly once . For example , 2143 is a 4 - digit pandigital What is the largest n - digit pandigital prime that exists ? (iterate There 's a clever observation which reduces the upper bound from 9 to 7 from " gamma " in the forum : > Note : Nine numbers can not be done ( 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9=45 = > always dividable by 3 ) > Note : Eight numbers can not be done ( 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8=36 = > always dividable by 3 ) (for n :downfrom 7) (thereis (apply (nullary #'max) (remove-if-not #'primep (pandigitals 1 n)))))) (defun problem-42 () so the first ten triangle numbers are : 1 , 3 , 6 , 10 , 15 , 21 , 28 , 36 , 45 , 55 , ... example , the word value for SKY is 19 + 11 + 25 = 55 = t10 . If the word Using words.txt ( right click and ' Save Link / Target As ... ' ) , a 16 K text file containing nearly two - thousand common English words , how many are triangle (labels ((word-value (word) (summation word :key #'letter-number)) (triangle-word-p (word) (trianglep (word-value word)))) (count-if #'triangle-word-p (parse-strings-file "data/042-words.txt")))) (defun problem-43 () The number , 1406357289 , is a 0 to 9 pandigital number because it is made up of each of the digits 0 to 9 in some order , but it also has a rather Let d1 be the 1st digit , d2 be the 2nd digit , and so on . In this way , we d2d3d4=406 is divisible by 2 d3d4d5=063 is divisible by 3 d4d5d6=635 is divisible by 5 d5d6d7=357 is divisible by 7 d6d7d8=572 is divisible by 11 d7d8d9=728 is divisible by 13 d8d9d10=289 is divisible by 17 Find the sum of all 0 to 9 pandigital numbers with this property . (labels ((extract3 (digits start) (digits-to-number (subseq digits start (+ 3 start)))) (interestingp (n) (let ((digits (digits n))) eat shit mathematicians , indexes start from zero (and (dividesp (extract3 digits 1) 2) (dividesp (extract3 digits 2) 3) (dividesp (extract3 digits 3) 5) (dividesp (extract3 digits 4) 7) (dividesp (extract3 digits 5) 11) (dividesp (extract3 digits 6) 13) (dividesp (extract3 digits 7) 17))))) (summation (remove-if-not #'interestingp (pandigitals 0 9))))) (defun problem-44 () Pentagonal numbers are generated by the formula , Pn = n(3n−1)/2 . The first ten pentagonal numbers are : 1 , 5 , 12 , 22 , 35 , 51 , 70 , 92 , 117 , 145 , ... It can be seen that P4 + P7 = 22 + 70 = 92 = P8 . However , their difference , 70 − 22 = 48 , is not pentagonal . Find the pair of pentagonal numbers , and Pk , for which their sum and (flet ((interestingp (px py) (and (pentagonp (+ py px)) (pentagonp (- py px))))) (iterate my kingdom for ` CL : INFINITY ` (for y :from 2) (for z :from 3) (for py = (pentagon y)) (for pz = (pentagon z)) (when (>= (- pz py) result) (return result)) (iterate (for x :from (1- y) :downto 1) (for px = (pentagon x)) (when (interestingp px py) (let ((distance (- py px))) (when (< distance result) TODO : This is n't quite right , because this is just the FIRST (return-from problem-44 distance))) (return)))))) (defun problem-45 () Triangle , pentagonal , and hexagonal numbers are generated by the following Triangle Tn = n(n+1)/2 1 , 3 , 6 , 10 , 15 , ... Pentagonal Pn = n(3n−1)/2 1 , 5 , 12 , 22 , 35 , ... Hexagonal Hn = n(2n−1 ) 1 , 6 , 15 , 28 , 45 , ... It can be verified that T285 = P165 = H143 = 40755 . (iterate (for n :key #'triangle :from 286) (finding n :such-that (and (pentagonp n) (hexagonp n))))) (defun problem-46 () It was proposed by that every odd composite number can 9 = 7 + 2×1² 15 = 7 + 2×2² 21 = 3 + 2×3² 25 = 7 + 2×3² 27 = 19 + 2×2² 33 = 31 + 2×1² (flet ((counterexamplep (n) (iterate (for prime :in-vector (sieve n)) (never (squarep (/ (- n prime) 2)))))) (iterate (for i :from 1 :by 2) (finding i :such-that (and (compositep i) (counterexamplep i)))))) (defun problem-47 () The first two consecutive numbers to have two distinct prime factors are : 14 = 2 × 7 15 = 3 × 5 The first three consecutive numbers to have three distinct prime factors are : 644 = 2² × 7 × 23 645 = 3 × 5 × 43 646 = 2 × 17 × 19 Find the first four consecutive integers to have four distinct prime factors each . What is the first of these numbers ? (flet ((factor-count (n) (length (remove-duplicates (prime-factorization n))))) (iterate (with run = 0) (for i :from 1) (if (= 4 (factor-count i)) (incf run) (setf run 0)) (finding (- i 3) :such-that (= run 4))))) (defun problem-48 () The series , 1 ^ 1 + 2 ^ 2 + 3 ^ 3 + ... + 10 ^ 10 = 10405071317 . Find the last ten digits of the series , 1 ^ 1 + 2 ^ 2 + 3 ^ 3 + ... + 1000 ^ 1000 . (-<> (irange 1 1000) (mapcar #'expt <> <>) summation (mod <> (expt 10 10)))) (defun problem-49 () The arithmetic sequence , 1487 , 4817 , , in which each of the terms increases by 3330 , is unusual in two ways : ( i ) each of the three terms are prime , and , ( ii ) each of the 4 - digit numbers are permutations of one There are no arithmetic sequences made up of three 1- , 2- , or 3 - digit primes , exhibiting this property , but there is one other 4 - digit increasing What 12 - digit number do you form by concatenating the three terms in this (labels ((permutation= (a b) (orderless-equal (digits a) (digits b))) (length>=3 (list) (>= (length list) 3)) (arithmetic-sequence-p (seq) (apply #'= (mapcar (curry #'apply #'-) (n-grams 2 seq)))) (has-arithmetic-sequence-p (seq) (map-combinations (lambda (s) (when (arithmetic-sequence-p s) (return-from has-arithmetic-sequence-p s))) (sort seq #'<) :length 3) nil)) (-<> (primes-in 1000 9999) make sure they have at leat 3 elements (mapcar #'has-arithmetic-sequence-p <>) (remove nil <>) first (mapcan #'digits <>) digits-to-number))) (defun problem-50 () The prime 41 , can be written as the sum of six consecutive primes : 41 = 2 + 3 + 5 + 7 + 11 + 13 one - hundred . The longest sum of consecutive primes below one - thousand that adds to a prime , contains 21 terms , and is equal to 953 . Which prime , below one - million , can be written as the sum of the most (let ((primes (sieve 1000000))) (flet ((score (start) (iterate (with score = 0) (with winner = 0) (for run :from 1) (for prime :in-vector primes :from start) (summing prime :into sum) (while (< sum 1000000)) (when (primep sum) (setf score run winner sum)) (finally (return (values score winner)))))) (iterate (for (values score winner) :key #'score :from 0 :below (length primes)) (finding winner :maximizing score))))) (defun problem-51 () By replacing the 1st digit of the 2 - digit number * 3 , it turns out that six of the nine possible values : 13 , 23 , 43 , 53 , 73 , and 83 , are all prime . By replacing the 3rd and 4th digits of 56**3 with the same digit , this 5 - digit number is the first example having seven primes among the ten generated numbers , yielding the family : 56003 , 56113 , 56333 , 56443 , 56663 , 56773 , and 56993 . Consequently 56003 , being the first member of this necessarily adjacent digits ) with the same digit , is part of an eight prime (labels ((patterns (prime) (iterate (with size = (digits-length prime)) (with indices = (range 0 size)) (for i :from 1 :below size) (appending (combinations indices :length i)))) (apply-pattern-digit (prime pattern new-digit) (iterate (with result = (digits prime)) (for index :in pattern) (when (and (zerop index) (zerop new-digit)) (leave)) (setf (nth index result) new-digit) (finally (return (digits-to-number result))))) (apply-pattern (prime pattern) (iterate (for digit in (irange 0 9)) (for result = (apply-pattern-digit prime pattern digit)) (when (and result (primep result)) (collect result)))) (apply-patterns (prime) (mapcar (curry #'apply-pattern prime) (patterns prime))) (winnerp (prime) (find-if (curry #'length= 8) (apply-patterns prime)))) (-<> (iterate (for i :from 3 :by 2) (thereis (and (primep i) (winnerp i)))) (sort< <>) first))) (defun problem-52 () It can be seen that the number , 125874 , and its double , 251748 , contain Find the smallest positive integer , x , such that 2x , 3x , 4x , 5x , and 6x , (iterate (for i :from 1) (for digits = (digits i)) (finding i :such-that (every (lambda (n) (orderless-equal digits (digits (* n i)))) '(2 3 4 5 6))))) (defun problem-53 () There are exactly ten ways of selecting three from five , 12345 : 123 , 124 , 125 , 134 , 135 , 145 , 234 , 235 , 245 , and 345 In combinatorics , we use the notation , 5C3 = 10 . nCr = n ! / r!(n−r ) ! where r ≤ n , n ! = n×(n−1)× ... ×3×2×1 , and 0 ! = 1 . It is not until n = 23 , that a value exceeds one - million : 23C10 = 1144066 . How many , not necessarily distinct , values of nCr , for 1 ≤ n ≤ 100 , are greater than one - million ? (iterate main (for n :from 1 :to 100) (iterate (for r :from 1 :to n) (for nCr = (binomial-coefficient n r)) (in main (counting (> nCr 1000000)))))) (defun problem-54 () In the card game poker , a hand consists of five cards and are ranked , from One Pair : Two cards of the same value . Two Pairs : Two different pairs . Three of a Kind : Three cards of the same value . Full House : Three of a kind and a pair . Four of a Kind : Four cards of the same value . Straight Flush : All cards are consecutive values of same suit . Royal Flush : Ten , , Queen , King , Ace , in same suit . 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , , Queen , King , Ace . If two players have the same ranked hands then the rank made up of the ( see example 1 below ) . But if two ranks tie , for example , both players have The file , poker.txt , contains one - thousand random hands dealt to two players . Each line of the file contains ten cards ( separated by a single space ): the first five are Player 1 's cards and the last five are Player How many hands does Player 1 win ? (iterate (for line :in-file "data/054-poker.txt" :using #'read-line) (for cards = (mapcar #'euler.poker::parse-card (str:split #\space line))) (for p1 = (take 5 cards)) (for p2 = (drop 5 cards)) (counting (euler.poker::poker-hand-beats-p p1 p2)))) (defun problem-55 () If we take 47 , reverse and add , 47 + 74 = 121 , which is palindromic . 349 + 943 = 1292 , 1292 + 2921 = 4213 4213 + 3124 = 7337 That is , 349 took three iterations to arrive at a palindrome . 196 , never produce a palindrome . A number that never forms a palindrome through the reverse and add process is called a Lychrel number . Due to the we shall assume that a number is Lychrel until proven otherwise . In addition you are given that for every number below ten - thousand , it will either ( i ) become a palindrome in less than fifty iterations , or , ( ii ) no to a palindrome . In fact , 10677 is the first number to be shown to require 4668731596684224866951378664 ( 53 iterations , 28 - digits ) . Surprisingly , there are palindromic numbers that are themselves Lychrel How many Lychrel numbers are there below ten - thousand ? (labels ((lychrel (n) (+ n (reverse-integer n))) (lychrelp (n) (iterate (repeat 50) (for i :iterating #'lychrel :seed n) (never (palindromep i))))) (iterate (for i :from 0 :below 10000) (counting (lychrelp i))))) (defun problem-56 () 100 ^ 100 is almost unimaginably large : one followed by two - hundred zeros . Despite their size , the sum of the digits in each number is only 1 . Considering natural numbers of the form , a^b , where a , b < 100 , what is the (iterate (for-nested ((a :from 1 :below 100) (b :from 1 :below 100))) (maximizing (digital-sum (expt a b))))) (defun problem-57 () It is possible to show that the square root of two can be expressed as an √ 2 = 1 + 1/(2 + 1/(2 + 1/(2 + ... ) ) ) = 1.414213 ... By expanding this for the first four iterations , we get : 1 + 1/2 = 3/2 = 1.5 1 + 1/(2 + 1/2 ) = 7/5 = 1.4 1 + 1/(2 + 1/(2 + 1/2 ) ) = 17/12 = 1.41666 ... 1 + 1/(2 + 1/(2 + 1/(2 + 1/2 ) ) ) = 41/29 = 1.41379 ... The next three expansions are 99/70 , 239/169 , and 577/408 , but the eighth expansion , 1393/985 , is the first example where the number of digits in the In the first one - thousand expansions , how many fractions contain (iterate (repeat 1000) (for i :initially 1/2 :then (/ (+ 2 i))) (for expansion = (1+ i)) (counting (> (digits-length (numerator expansion)) (digits-length (denominator expansion)))))) (defun problem-58 () Starting with 1 and spiralling anticlockwise in the following way , a square spiral with side length 7 is formed . 37 36 35 34 33 32 31 38 17 16 15 14 13 30 39 18 5 4 3 12 29 40 19 6 1 2 11 28 41 20 7 8 9 10 27 42 21 22 23 24 25 26 43 44 45 46 47 48 49 diagonal , but what is more interesting is that 8 out of the 13 numbers If one complete new layer is wrapped around the spiral above , a square spiral with side length 9 will be formed . If this process is continued , along both diagonals first falls below 10 % ? (labels ((score (value) (if (primep value) 1 0)) (primes-in-layer (size) (summation (number-spiral-corners size) :key #'score))) (iterate (for size :from 3 :by 2) (for count :from 5 :by 4) (summing (primes-in-layer size) :into primes) (for ratio = (/ primes count)) (finding size :such-that (< ratio 1/10))))) (defun problem-59 () standard is ASCII ( American Standard Code for Information Interchange ) . For example , uppercase A = 65 , asterisk ( * ) = 42 , and lowercase k = 107 . then 107 XOR 42 = 65 . Your task has been made easy , as the encryption key consists of three lower that the plain text must contain common English words , decrypt the message (let* ((data (-<> "data/059-cipher.txt" read-file-into-string (substitute #\space #\, <>) read-all-from-string)) (raw-words (-<> "/usr/share/dict/words" read-file-into-string (str:split #\newline <>) (mapcar #'string-downcase <>))) (words (make-hash-set :test 'equal :initial-contents raw-words))) (labels ((stringify (codes) (map 'string #'code-char codes)) (apply-cipher (key) (iterate (for number :in data) (for k :in-looping key) (collect (logxor number k)))) (score-keyword (keyword) (-<> (apply-cipher keyword) (stringify <>) (string-downcase <>) (str:words <>) (remove-if-not (curry #'hset-contains-p words) <>) length)) (answer (keyword) (summation (apply-cipher keyword)))) (iterate (for-nested ((a :from (char-code #\a) :to (char-code #\z)) (b :from (char-code #\a) :to (char-code #\z)) (c :from (char-code #\a) :to (char-code #\z)))) (for keyword = (list a b c)) (finding (answer keyword) :maximizing (score-keyword keyword)))))) (defun problem-60 () The primes 3 , 7 , 109 , and 673 , are quite remarkable . By taking any two For example , taking 7 and 109 , both 7109 and 1097 are prime . The sum of these four primes , 792 , represents the lowest sum for a set of four primes Find the lowest sum for a set of five primes for which any two primes (labels-memoized ((concatenates-prime-p (a b) (and (primep (concatenate-integers a b)) (primep (concatenate-integers b a))))) (flet ((satisfiesp (prime primes) (every (curry #'concatenates-prime-p prime) primes))) (iterate main (with primes = (subseq (sieve 10000) 1)) (for a :in-vector primes :with-index ai) (iterate (for b :in-vector primes :with-index bi :from (1+ ai)) (when (satisfiesp b (list a)) (iterate (for c :in-vector primes :with-index ci :from (1+ bi)) (when (satisfiesp c (list a b)) (iterate (for d :in-vector primes :with-index di :from (1+ ci)) (when (satisfiesp d (list a b c)) (iterate (for e :in-vector primes :from (1+ di)) (when (satisfiesp e (list a b c d)) (in main (return-from problem-60 (+ a b c d e))))))))))))))) (defun problem-61 () Triangle , square , pentagonal , hexagonal , heptagonal , and octagonal numbers Triangle P3,n = n(n+1)/2 1 , 3 , 6 , 10 , 15 , ... Square P4,n = n² 1 , 4 , 9 , 16 , 25 , ... Pentagonal P5,n = n(3n−1)/2 1 , 5 , 12 , 22 , 35 , ... Hexagonal P6,n = n(2n−1 ) 1 , 6 , 15 , 28 , 45 , ... Heptagonal P7,n = n(5n−3)/2 1 , 7 , 18 , 34 , 55 , ... Octagonal P8,n = n(3n−2 ) 1 , 8 , 21 , 40 , 65 , ... The ordered set of three 4 - digit numbers : 8128 , 2882 , 8281 , has three 1 . The set is cyclic , in that the last two digits of each number is the first two digits of the next number ( including the last number with the first ) . 2 . Each polygonal type : triangle ( P3,127=8128 ) , square ( P4,91=8281 ) , and pentagonal ( ) , is represented by a different number in the 3 . This is the only set of 4 - digit numbers with this property . Find the sum of the only ordered set of six cyclic 4 - digit numbers for (labels ((numbers (generator) (iterate (for i :from 1) (for n = (funcall generator i)) (while (<= n 9999)) (when (>= n 1000) (collect n)))) (split (number) (truncate number 100)) (prefix (number) (when number (nth-value 0 (split number)))) (suffix (number) (when number (nth-value 1 (split number)))) (matches (prefix suffix number) (multiple-value-bind (p s) (split number) (and (or (not prefix) (= prefix p)) (or (not suffix) (= suffix s))))) (choose (numbers used prefix &optional suffix) (-<> numbers (remove-if-not (curry #'matches prefix suffix) <>) (set-difference <> used))) (search-sets (sets) (recursively ((sets sets) (path nil)) (destructuring-bind (set . remaining) sets (if remaining (iterate (for number :in (choose set path (suffix (car path)))) (recur remaining (cons number path))) between the penultimate element and first element to (when-let* ((init (first (last path))) (prev (car path)) (final (choose set path (suffix prev) (prefix init)))) (return-from problem-61 (summation (reverse (cons (first final) path)))))))))) (map-permutations #'search-sets (list (numbers #'triangle) (numbers #'square) (numbers #'pentagon) (numbers #'hexagon) (numbers #'heptagon) (numbers #'octagon))))) (defun problem-62 () The cube , 41063625 ( 345³ ) , can be permuted to produce two other cubes : 56623104 ( 384³ ) and 66430125 ( 405³ ) . In fact , 41063625 is the smallest cube which has exactly three permutations of its digits which are also cube . Find the smallest cube for which exactly five permutations of its digits canonical - repr = > ( count . first - cube ) Basic strategy from [ 1 ] but with some bug fixes . His strategy happens to We ca n't just return as soon as we hit the 5th cubic permutation , because what if this cube is actually part of a family of 6 ? Instead we need to [ 1 ] : -euler-62-cube-five-permutations/ (labels ((canonicalize (cube) (digits-to-number (sort (digits cube) #'>))) (mark (cube) (let ((entry (ensure-gethash (canonicalize cube) scores (cons 0 cube)))) (incf (car entry)) entry))) (iterate (with i = 1) (with target = 5) (with candidates = nil) (for limit :initially 10 :then (* 10 limit)) (iterate (for cube = (cube i)) (while (< cube limit)) (incf i) (for (score . first) = (mark cube)) (cond ((= score target) (push first candidates)) (thereis (apply (nullary #'min) candidates)))))) (defun problem-63 () The 5 - digit number , 16807=7 ^ 5 , is also a fifth power . Similarly , the 9 - digit number , 134217728=8 ^ 9 , is a ninth power . (flet ((score (n) (iterate (for base :from 1 :below 10) (for value = (expt base n)) (counting (= n (digits-length value))))) (find-bound () it 's 21.something , but I do n't really grok why yet (iterate (for power :from 1) (for maximum-possible-digits = (digits-length (expt 9 power))) (while (>= maximum-possible-digits power)) (finally (return power))))) (iterate (for n :from 1 :below (find-bound)) (summing (score n))))) (defun problem-67 () on the row below , the maximum total from top to bottom is 23 . 3 2 4 6 That is , 3 + 7 + 4 + 9 = 23 . Find the maximum total from top to bottom in triangle.txt , a 15 K text file containing a triangle with one - hundred rows . NOTE : This is a much more difficult version of Problem 18 . It is not possible to try every route to solve this problem , as there are 299 altogether ! If you could check one trillion ( 1012 ) routes every second it would take over twenty billion years to check them all . There is an (car (reduce (lambda (prev last) (mapcar #'+ prev (mapcar #'max last (rest last)))) (iterate (for line :in-csv-file "data/067-triangle.txt" :delimiter #\space :key #'parse-integer) (collect line)) :from-end t))) (defun problem-69 () Euler 's Totient function , ) [ sometimes called the phi function ] , is prime to n. For example , as 1 , 2 , 4 , 5 , 7 , and 8 , are all less than nine and relatively prime to nine , φ(9)=6 . It can be seen that n=6 produces a maximum n / φ(n ) for n ≤ 10 . Find the value of n ≤ 1,000,000 for which n / φ(n ) is a maximum . (iterate Euler 's Totient function is defined to be : φ(n ) = n * Πₓ(1 - 1 / x ) where x ∈ { prime factors of n } _ n _ _ = _ _ _ _ _ _ _ n _ _ _ _ _ _ _ = _ _ _ _ _ 1 _ _ _ _ _ φ(n ) n * Πₓ(1 - 1 / x ) Πₓ(1 - 1 / x ) MINIMIZE the denominator : Πₓ(1 - 1 / x ) . 1 . Have as many terms as possible in the product , because all terms are between 0 and 1 , and so decrease the total product when multiplied . 2 . Prefer smaller values of x , because this minimizes ( 1 - 1 / x ) , which same unique prime factorization will have the same value for n / φ(n ) . f(2 * 3 * 5 ) = f(2² * 3⁸ * 5 ) maximum value below 1,000,000 , but even if there were multiple answers , it seems reasonable to return the first . This means that the answer Not only is it square - free , it must be the product of the first k primes , for some number see why , consider two possible square - free denominator , thus maximizing the result . So given two sets of prime Together we can use these two notes to conclude that we simply want the (for p :in-primes t) (for n :initially 1 :then (* n p)) (for result :previous n) (while (<= n 1000000)) (finally (return result)))) (defun problem-71 () If we list the set of reduced proper fractions for d ≤ 8 in ascending order 1/8 , 1/7 , 1/6 , 1/5 , 1/4 , 2/7 , 1/3 , 3/8 , 2/5 , 3/7 , 1/2 , 4/7 , 3/5 , 5/8 , 2/3 , 5/7 , 3/4 , 4/5 , 5/6 , 6/7 , 7/8 It can be seen that 2/5 is the fraction immediately to the left of 3/7 . By listing the set of reduced proper fractions for d ≤ 1,000,000 in the left of 3/7 . (iterate We could theoretically iterate through F_1000000 til we find 3/7 , but we 'd have about 130000000000 elements to churn though . We can do it much Instead , we start by computing F₇ and finding 3/7 and whatever 's to the left of it . We can find what 's in between these two in the next (with limit = 1000000) (with target = 3/7) (with guess = (iterate (for x :in-farey-sequence (denominator target)) (for px :previous x) (finding px :such-that (= x target)))) (for next = (mediant guess target)) (if (> (denominator next) limit) (return (numerator guess)) (setf guess next)))) (defun problem-73 () If we list the set of reduced proper fractions for d ≤ 8 in ascending order 1/8 , 1/7 , 1/6 , 1/5 , 1/4 , 2/7 , 1/3 , 3/8 , 2/5 , 3/7 , 1/2 , 4/7 , 3/5 , 5/8 , 2/3 , 5/7 , 3/4 , 4/5 , 5/6 , 6/7 , 7/8 It can be seen that there are 3 fractions between 1/3 and 1/2 . How many fractions lie between 1/3 and 1/2 in the sorted set of reduced proper fractions for d ≤ 12,000 ? (iterate Just brute force this one with our fancy sequence iterator . (for x :in-farey-sequence 12000) (while (< x 1/2)) (counting (< 1/3 x)))) (defun problem-74 () The number 145 is well known for the property that the sum of the factorial of its digits is equal to 145 : 1 ! + 4 ! + 5 ! = 1 + 24 + 120 = 145 Perhaps less well known is 169 , in that it produces the longest chain of 169 → 363601 → 1454 → 169 871 → 45361 → 871 872 → 45362 → 872 69 → 363600 → 1454 → 169 → 363601 ( → 1454 ) 78 → 45360 → 871 → 45361 ( → 871 ) 540 → 145 ( → 145 ) Starting with 69 produces a chain of five non - repeating terms , but the longest non - repeating chain with a starting number below one million is sixty terms . How many chains , with a starting number below one million , contain exactly sixty non - repeating terms ? (labels ((digit-factorial (n) (summation (digits n) :key #'factorial)) (term-count (n) (iterate (for i :initially n :then (digit-factorial i)) (until (member i prev)) (collect i :into prev) (counting t)))) (iterate (for i :from 1 :below 1000000) (counting (= 60 (term-count i)))))) (defun problem-79 () three random characters from a passcode . For example , if the passcode was reply would be : 317 . The text file , keylog.txt , contains fifty successful login attempts . Given that the three characters are always asked for in order , analyse (let ((attempts (-<> "data/079-keylog.txt" read-all-from-file (mapcar #'digits <>) (mapcar (rcurry #'coerce 'vector) <>)))) assumption . If you have attempts of ( 12 21 ) then the shortest passcode would be 121 . So we 'll do things the safe way and just brute force it . (iterate (for passcode :from 1) (finding passcode :such-that (every (rcurry #'subsequencep (digits passcode)) attempts))))) (defun problem-81 () In the 5 by 5 matrix below , the minimal path sum from the top left to the red and is equal to 2427 . Find the minimal path sum , in matrix.txt , a 31 K text file containing a 80 by 80 matrix , from the top left to the bottom right by only moving right (let* ((data (convert-to-multidimensional-array (iterate (for line :in-csv-file "data/081-matrix.txt" :key #'parse-integer) (collect line)))) (rows (array-dimension data 0)) (cols (array-dimension data 1)) (last-row (1- rows)) (last-col (1- cols)) (down (vec2 0 1)) (right (vec2 1 0)) (top-left (vec2 0 0)) (bottom-right (vec2 last-col last-row)) (minimum-value (iterate (for value :in-array data) (minimizing value)))) (labels ((value-at (point) (aref data (vy point) (vx point))) (neighbors (point) (remove nil (list (when (< (vx point) last-col) (vec2+ point right)) (when (< (vy point) last-row) (vec2+ point down))))) (remaining-moves (point) (+ (- cols (vx point)) (- rows (vy point)))) (heuristic (point) (* minimum-value (remaining-moves point))) (cost (prev point) (declare (ignore prev)) (value-at point))) (summation (astar :start top-left :neighbors #'neighbors :goalp (curry #'vec2= bottom-right) :cost #'cost :heuristic #'heuristic :test #'equalp) :key #'value-at)))) (defun problem-82 () NOTE : This problem is a more challenging version of Problem 81 . The minimal path sum in the 5 by 5 matrix below , by starting in any cell in to 994 . Find the minimal path sum , in matrix.txt , a 31 K text file containing a 80 by 80 matrix , from the left column to the right column . (let* ((data (convert-to-multidimensional-array (iterate (for line :in-csv-file "data/082-matrix.txt" :key #'parse-integer) (collect line)))) (rows (array-dimension data 0)) (cols (array-dimension data 1)) (last-row (1- rows)) (last-col (1- cols)) (up (vec2 0 -1)) (down (vec2 0 1)) (right (vec2 1 0)) (minimum-value (iterate (for value :in-array data) (minimizing value)))) choose anything in the first column as a starting state : we 'll make the starting state NIL and make everything in the first column its neighbors . (labels ((value-at (point) (aref data (vy point) (vx point))) (neighbors (point) (if (null point) (mapcar (curry #'vec2 0) (range 0 rows)) (remove nil (list (when (< (vx point) last-col) (vec2+ point right)) (when (< 0 (vy point)) (vec2+ point up)) (when (< (vy point) last-row) (vec2+ point down)))))) (remaining-moves (point) (+ (- cols (vx point)) (- rows (vy point)))) (goalp (point) (and point (= last-col (vx point)))) (heuristic (point) (* minimum-value (remaining-moves point))) (cost (prev point) (declare (ignore prev)) (value-at point))) (summation (rest (astar :start nil :neighbors #'neighbors :goalp #'goalp :cost #'cost :heuristic #'heuristic :test #'equalp)) :key #'value-at)))) (defun problem-92 () 44 → 32 → 13 → 10 → 1 → 1 85 → 89 → 145 → 42 → 20 → 4 → 16 → 37 → 58 → 89 Therefore any chain that arrives at 1 or 89 will become stuck in an eventually arrive at 1 or 89 . How many starting numbers below ten million will arrive at 89 ? (labels ((square-chain-end (i) (if (or (= 1 i) (= 89 i)) i (square-chain-end (iterate (for d :in-digits-of i) (summing (square d))))))) (iterate (for i :from 1 :below 10000000) (counting (= 89 (square-chain-end i)))))) (defun problem-97 () The first known prime found to exceed one million digits was discovered in 2,098,960 digits . Subsequently other primes , of the form 2^p−1 , However , in 2004 there was found a massive non - Mersenne prime which contains 2,357,207 digits : 28433×2 ^ 7830457 + 1 . Find the last ten digits of this prime number . (-<> 2 (expt <> 7830457) (* 28433 <>) 1+ (mod <> (expt 10 10)))) (defun problem-99 () Comparing two numbers written in index form like 2 ^ 11 and 3 ^ 7 is not difficult , as any calculator would confirm that 2 ^ 11 = 2048 < 3 ^ 7 = 2187 . However , confirming that 632382 ^ 518061 > 519432 ^ 525806 would be much more difficult , as both numbers contain over three million digits . Using base_exp.txt ( right click and ' Save Link / Target As ... ' ) , a 22 K text file containing one thousand lines with a base / exponent pair on each line , NOTE : The first two lines in the file represent the numbers in the example (iterate (for line-number :from 1) (for (base exponent) :in-csv-file "data/099-exponents.txt" :key #'parse-integer) (finding line-number :maximizing (* exponent (log base))))) (defun problem-102 () Three distinct points are plotted at random on a Cartesian plane , for which -1000 ≤ x , y ≤ 1000 , such that a triangle is formed . Consider the following two triangles : A(-340,495 ) , B(-153,-910 ) , C(835,-947 ) X(-175,41 ) , ) , Z(574,-645 ) It can be verified that triangle ABC contains the origin , whereas triangle XYZ does not . Using triangles.txt ( right click and ' Save Link / Target As ... ' ) , a 27 K text file containing the co - ordinates of one thousand " random " triangles , find NOTE : The first two examples in the file represent the triangles in the (flet ((parse-file (file) (iterate (for (ax ay bx by cx cy) :in-csv-file file :key #'parse-integer) (collect (list (vec2 ax ay) (vec2 bx by) (vec2 cx cy))))) (check-triangle (a b c) ( with respect to that triangle ) are all within 0 to 1 . (multiple-value-bind (u v w) (barycentric a b c (vec2 0 0)) (and (<= 0 u 1) (<= 0 v 1) (<= 0 w 1))))) (iterate (for (a b c) :in (parse-file "data/102-triangles.txt")) (counting (check-triangle a b c))))) (defun problem-112 () Working from left - to - right if no digit is exceeded by the digit to its left Clearly there can not be any bouncy numbers below one - hundred , but just over half of the numbers below one - thousand ( 525 ) are bouncy . In fact , the least number for which the proportion of bouncy numbers first reaches 50 % is 538 . reach 21780 the proportion of bouncy numbers is equal to 90 % . 99 % . (flet ((bouncyp (integer) (iterate (for digit :in-digits-of integer) (for prev :previous digit) (unless-first-time (oring (< prev digit) :into increasing) (oring (> prev digit) :into decreasing)) (thereis (and increasing decreasing))))) (iterate (for i :from 1) (for total :from 1) (counting (bouncyp i) :into bouncy) (finding i :such-that (= (/ bouncy total) 99/100))))) (defun problem-145 () consists entirely of odd ( decimal ) digits . For instance , 36 + 63 = 99 and 904 are reversible . Leading zeroes are not allowed in either n or There are 120 reversible numbers below one - thousand . How many reversible numbers are there below one - billion ( 10 ^ 9 ) ? (flet ((reversiblep (n) (let ((reversed (reverse-integer n))) (values (unless (zerop (digit 0 n)) (every #'oddp (digits (+ n reversed)))) reversed)))) (iterate TODO : improve this one ( with limit = 1000000000 ) there are no 9 - digit reversible numbers ... (with limit = 100000000) (with done = (make-array limit :element-type 'bit :initial-element 0)) (for i :from 1 :below limit) (unless (= 1 (aref done i)) (for (values reversible j) = (reversiblep i)) (setf (aref done j) 1) (when reversible (summing (if (= i j) 1 2))))))) (defun problem-206 () (declare (optimize speed)) 1_2_3_4_5_6_7_8_9_0 , where each “ _ ” is a single digit . (flet ((targetp (i) (declare (type fixnum i)) (and (= 0 (nth-digit 0 i)) (= 9 (nth-digit 2 i)) (= 8 (nth-digit 4 i)) (= 7 (nth-digit 6 i)) (= 6 (nth-digit 8 i)) (= 5 (nth-digit 10 i)) (= 4 (nth-digit 12 i)) (= 3 (nth-digit 14 i)) (= 2 (nth-digit 16 i)) (= 1 (nth-digit 18 i))))) in 0 . This means the original number has to be divisible by 10 , so we (iterate (with min = (round-to (sqrt 1020304050607080900) 10)) (with max = (floor (sqrt 1929394959697989990))) (for i :from min :to max :by 10) (finding i :such-that (targetp (square i)))))) (defun problem-315 () Full description too long , see (labels ((digit-to-bits (n) (case n (0 #b1111110) (1 #b0101000) (2 #b1011011) (3 #b1101011) (4 #b0101101) (5 #b1100111) (6 #b1110111) (7 #b0101110) (8 #b1111111) (9 #b1101111) (t #b0000000))) (transition-sam (previous current) turns off everything lit in the previous number , and turns (let ((p (digit-to-bits previous)) (c (digit-to-bits current))) (+ (logcount p) (logcount c)))) (transition-max (previous current) only turns off the things that need to be turned off , and (let ((p (digit-to-bits previous)) (c (digit-to-bits current))) (logcount (logxor p c)))) (transition (transition-function previous-digits current-digits) (summation (mapcar-long transition-function nil previous-digits current-digits))) (run-clock (seed) (iterate (for current :in-list (mapcar (rcurry #'digits :from-end t) (digital-roots seed)) :finally nil) (for prev :previous current :initially nil) (summing (transition #'transition-sam prev current) :into sam) (summing (transition #'transition-max prev current) :into max) (finally (return (values sam max)))))) (iterate (for n :from (expt 10 7) :to (* 2 (expt 10 7))) (when (primep n) (summing (multiple-value-call #'- (run-clock n))))))) (defun problem-323 () Let y0 , y1 , y2 , ... be a sequence of random unsigned 32 bit integers ( i.e. 0 ≤ yi < 2 ^ 32 , every value equally likely ) . xi = 2 ^ 32 - 1 ( a bit - pattern of all ones ) for all i ≥ N. Give your answer rounded to 10 digits after the decimal point . (labels treat this problem as a set of 32 independent trials , and are trying to find the expected numbers of iterations required for all 32 ((empirical-test () (iterate (counting t) (until (randomp)))) (empirical-tests (runners) (iterate (repeat runners) (maximizing (empirical-test)))) (run-empirical-tests (runners) (coerce (iterate (repeat 1000000) (averaging (empirical-tests runners))) 'double-float)) Running the experiments for 32 parallel trials enough times to get 10 ( 1 * P(finishing on turn 1 ) ) + ( 2 * P(finishing on turn 2 ) ) + turn n ) , and then adding enough terms to get our ten digits of (probability-of-finishing-by (runners n) (expt (geometric-cdf 0.5d0 n) runners)) (probability-of-finishing-on (runners n) taking N 's cumulative probability and subtracting N-1 's cumulative (- (probability-of-finishing-by runners n) (probability-of-finishing-by runners (1- n)))) (expected-value (runners) (iterate (for n :from 1 :below 1000) (for prob = (probability-of-finishing-on runners n)) (summing (* n prob)))) (sanity-check (runners) (assert (= (round-decimal (run-empirical-tests runners) 1) (round-decimal (expected-value runners) 1))))) (when nil (iterate (for i :from 1 :to 6) (sanity-check i))) (round-decimal (expected-value 32) 10))) (defun problem-345 () the Matrix Sum of the matrix below equals 3315 ( = 863 + 383 + 343 + 959 7 53 183 439 863 497 383 563 79 973 287 63 343 169 583 627 343 773 959 943 767 473 103 699 303 (let ((matrix (copy-array #2a(( 7 53 183 439 863 497 383 563 79 973 287 63 343 169 583) (627 343 773 959 943 767 473 103 699 303 957 703 583 639 913) (447 283 463 29 23 487 463 993 119 883 327 493 423 159 743) (217 623 3 399 853 407 103 983 89 463 290 516 212 462 350) (960 376 682 962 300 780 486 502 912 800 250 346 172 812 350) (870 456 192 162 593 473 915 45 989 873 823 965 425 329 803) (973 965 905 919 133 673 665 235 509 613 673 815 165 992 326) (322 148 972 962 286 255 941 541 265 323 925 281 601 95 973) (445 721 11 525 473 65 511 164 138 672 18 428 154 448 848) (414 456 310 312 798 104 566 520 302 248 694 976 430 392 198) (184 829 373 181 631 101 969 613 840 740 778 458 284 760 390) (821 461 843 513 17 901 711 993 293 157 274 94 192 156 574) ( 34 124 4 878 450 476 712 914 838 669 875 299 823 329 699) (815 559 813 459 522 788 168 586 966 232 308 833 251 631 107) (813 883 451 509 615 77 281 613 459 205 380 274 302 35 805))))) The hungarian algorithm finds a minimal assignment , but we want a maximal (do-array (val matrix) (negatef val)) (iterate (for (row . col) :in (euler.hungarian:find-minimal-assignment matrix)) (summing (- (aref matrix row col)))))) (defun problem-346 () The number 7 is special , because 7 is 111 written in base 2 , and 11 written in base 6 ( i.e. 7_10 = 11_6 = 111_2 ) . In other words , 7 is a repunit in at least two bases b > 1 . can be verified that there are 8 strong repunits below 50 : { 1,7,13,15,21,31,40,43 } . Furthermore , the sum of all strong repunits below 1000 equals 15864 . Find the sum of all strong repunits below 10 ^ 12 . (iterate Let 's start with a few observations . First , 1 is a repunit in ALL bases , and 2 is n't a repunit in any base . Next , EVERY number ` n ` greater than 2 is a repunit in base ` n - 1 ` , because it will be ` 11 ` in that base . So every number already fulfills half the requirements of the problem . This means we only need to find and sum all the numbers are repunits in at least one more base , and they 'll be of the form ` 11[1]+ ` in that base . R₁ = 1 = 1 R₂ = 11 = 1 + b¹ = 111 = 1 + b¹ + b² R₄ = 1111 = 1 + b¹ + b² + b³ are repunits in more than two bases . (with limit = (expt 10 12)) (with strong-repunits = (make-hash-set :initial-contents '(1))) (for base :from 2 :to (sqrt limit)) (iterate To check a particular base we 'll start at number 111 in that base , because we 've already accounted for 1 and 11 in our previous This is why we only iterate up to √b in the outer loop : the first number we 're going to be checking is ` 111 = 1 + b¹ + b² ` , and so any (for n :first (+ 1 base (expt base 2)) :then (+ 1 (* base n))) (while (< n limit)) (hset-insert! strong-repunits n)) (finally (return (hset-reduce strong-repunits #'+))))) (defun problem-357 () Consider the divisors of 30 : 1,2,3,5,6,10,15,30 . It can be seen that for every divisor d of 30 , d+30 / d is prime . Find the sum of all positive integers n not exceeding 100 000 000 such that (labels ((check-divisor (n d) (primep (+ d (truncate n d)))) (prime-generating-integer-p (n) (declare (optimize speed) (type fixnum n) (inline divisors-up-to-square-root)) (every (curry #'check-divisor n) (divisors-up-to-square-root n)))) Every number has 1 has a factor , which means one of the tests will be to see if ) is prime . * n must be even ( except the edge case of 1 ) . * ) must be prime . Because all candidates are even , they all have 2 as a divisor ( see the formula gives us d+(n / d ) . We know that n / d will still be divisible factorization . Obviously d itself is divisible by our entire same number , so we only need to bother checking one of them . (1+ (iterate edge case : skip 2 ( candidiate 1 ) , we 'll add it at the end (for prime :in-vector (sieve (1+ 100000000)) :from 1) (for candidate = (1- prime)) (when (and (check-divisor candidate 2) (prime-generating-integer-p candidate)) (summing candidate)))))) (defun problem-387 () A or Niven number is a number that is divisible by the sum of its digits . 201 is a number because it is divisible by 3 ( the sum of its digits . ) When we truncate the last digit from 201 , we get 20 , which is a number . When we truncate the last digit from 20 , we get 2 , which is also a number . Let 's call a number that , while recursively truncating the last digit , always results in a number a right truncatable Also : 201/3=67 which is prime . Let 's call a number that , when divided by the sum of its digits , results in a prime a strong number . Now take the number 2011 which is prime . When we truncate the last digit from it we get 201 , a strong number that is also right truncatable . Let 's call such primes strong , right truncatable primes . You are given that the sum of the strong , right truncatable primes less than 10000 is 90619 . Find the sum of the strong , right truncatable primes less than 10 ^ 14 . (labels ((harshadp (number) (dividesp number (digital-sum number))) (strong-harshad-p (number) (multiple-value-bind (result remainder) (truncate number (digital-sum number)) (and (zerop remainder) (primep result)))) (right-truncatable-harshad-p (number) (iterate (for i :first number :then (truncate-number-right i 1)) (until (zerop i)) (always (harshadp i)))) (strong-right-truncatable-harshad-p (number) A " strong , right - truncatable number " is a number that is both a strong number and a right - truncatable number . Note that after the first truncation the rest no longer (and (strong-harshad-p number) (right-truncatable-harshad-p number))) (strong-right-truncatable-harshad-prime-p (number) A " strong , right - truncatable prime " is not itself a number ! Prime numbers can never be numbers chop off the right digit and get strong , truncatable (and (primep number) (strong-right-truncatable-harshad-p (truncate-number-right number 1)))) (harshad-total (limit) Instead of trying to check every number below 10 ^ 14 for primality , we can recursively build right - truncatable and make sure the number is a number at each step , (recursively ((n 0)) (cond ((>= n limit) 0) ((or (zerop n) (harshadp n)) (iterate (for digit :from (if (zerop n) 1 0) :to 9) (summing (recur (append-digit digit n))))) ((strong-right-truncatable-harshad-prime-p n) n) (t 0))))) (harshad-total (expt 10 14)))) (test p10 (is (= 142913828922 (problem-10)))) (test p11 (is (= 70600674 (problem-11)))) (test p12 (is (= 76576500 (problem-12)))) (test p13 (is (= 5537376230 (problem-13)))) (test p14 (is (= 837799 (problem-14)))) (test p15 (is (= 137846528820 (problem-15)))) (test p16 (is (= 1366 (problem-16)))) (test p17 (is (= 21124 (problem-17)))) (test p18 (is (= 1074 (problem-18)))) (test p19 (is (= 171 (problem-19)))) (test p20 (is (= 648 (problem-20)))) (test p21 (is (= 31626 (problem-21)))) (test p22 (is (= 871198282 (problem-22)))) (test p23 (is (= 4179871 (problem-23)))) (test p24 (is (= 2783915460 (problem-24)))) (test p25 (is (= 4782 (problem-25)))) (test p26 (is (= 983 (problem-26)))) (test p27 (is (= -59231 (problem-27)))) (test p28 (is (= 669171001 (problem-28)))) (test p29 (is (= 9183 (problem-29)))) (test p30 (is (= 443839 (problem-30)))) (test p31 (is (= 73682 (problem-31)))) (test p32 (is (= 45228 (problem-32)))) (test p33 (is (= 100 (problem-33)))) (test p34 (is (= 40730 (problem-34)))) (test p35 (is (= 55 (problem-35)))) (test p36 (is (= 872187 (problem-36)))) (test p37 (is (= 748317 (problem-37)))) (test p38 (is (= 932718654 (problem-38)))) (test p39 (is (= 840 (problem-39)))) (test p40 (is (= 210 (problem-40)))) (test p41 (is (= 7652413 (problem-41)))) (test p42 (is (= 162 (problem-42)))) (test p43 (is (= 16695334890 (problem-43)))) (test p44 (is (= 5482660 (problem-44)))) (test p45 (is (= 1533776805 (problem-45)))) (test p46 (is (= 5777 (problem-46)))) (test p47 (is (= 134043 (problem-47)))) (test p48 (is (= 9110846700 (problem-48)))) (test p49 (is (= 296962999629 (problem-49)))) (test p50 (is (= 997651 (problem-50)))) (test p51 (is (= 121313 (problem-51)))) (test p52 (is (= 142857 (problem-52)))) (test p53 (is (= 4075 (problem-53)))) (test p54 (is (= 376 (problem-54)))) (test p55 (is (= 249 (problem-55)))) (test p56 (is (= 972 (problem-56)))) (test p57 (is (= 153 (problem-57)))) (test p58 (is (= 26241 (problem-58)))) (test p59 (is (= 107359 (problem-59)))) (test p60 (is (= 26033 (problem-60)))) (test p61 (is (= 28684 (problem-61)))) (test p62 (is (= 127035954683 (problem-62)))) (test p63 (is (= 49 (problem-63)))) (test p67 (is (= 7273 (problem-67)))) (test p69 (is (= 510510 (problem-69)))) (test p71 (is (= 428570 (problem-71)))) (test p73 (is (= 7295372 (problem-73)))) (test p74 (is (= 402 (problem-74)))) (test p79 (is (= 73162890 (problem-79)))) (test p81 (is (= 427337 (problem-81)))) (test p82 (is (= 260324 (problem-82)))) (test p92 (is (= 8581146 (problem-92)))) (test p97 (is (= 8739992577 (problem-97)))) (test p99 (is (= 709 (problem-99)))) (test p102 (is (= 228 (problem-102)))) (test p145 (is (= 608720 (problem-145)))) (test p206 (is (= 1389019170 (problem-206)))) (test p315 (is (= 13625242 (problem-315)))) (test p323 (is (= 6.3551758451d0 (problem-323)))) (test p345 (is (= 13938 (problem-345)))) (test p346 (is (= 336108797689259276 (problem-346)))) (test p357 (is (= 1739023853137 (problem-357)))) (test p387 (is (= 696067597313468 (problem-387)))) (defun run-tests () (1am:run))
a2e2c05ab28aaea95788853f0a2612b3925ab8275db72eb5c54f6a0b7ed20d08
raimohanska/snap-mongo-rest
Mongo.hs
module Util.Mongo where import Control.Monad import Control.Applicative import Data.Bson.Mapping import Database.MongoDB import Control.Monad.IO.Class mongoPost :: Applicative m => MonadIO m => Bson a => Database -> Collection -> a -> m String mongoPost db collection x = do val <- doMongo db $ insert collection $ toBson x case val of ObjId (oid) -> return $ show oid _ -> fail $ "unexpected id" mongoFindOne :: MonadIO m => Bson a => Database -> Query -> m (Maybe a) mongoFindOne db query = do doc <- doMongo db $ findOne query return (doc >>= (fromBson >=> Just)) doMongo :: MonadIO m => Database -> Action m a -> m a doMongo db action = do pipe <- liftIO $ runIOE $ connect (host "127.0.0.1") result <- access pipe master db action liftIO $ close pipe case result of Right val -> return val Left failure -> fail $ show failure
null
https://raw.githubusercontent.com/raimohanska/snap-mongo-rest/9659e799e0c7d8cb808361b01e661b272e9e8025/src/Util/Mongo.hs
haskell
module Util.Mongo where import Control.Monad import Control.Applicative import Data.Bson.Mapping import Database.MongoDB import Control.Monad.IO.Class mongoPost :: Applicative m => MonadIO m => Bson a => Database -> Collection -> a -> m String mongoPost db collection x = do val <- doMongo db $ insert collection $ toBson x case val of ObjId (oid) -> return $ show oid _ -> fail $ "unexpected id" mongoFindOne :: MonadIO m => Bson a => Database -> Query -> m (Maybe a) mongoFindOne db query = do doc <- doMongo db $ findOne query return (doc >>= (fromBson >=> Just)) doMongo :: MonadIO m => Database -> Action m a -> m a doMongo db action = do pipe <- liftIO $ runIOE $ connect (host "127.0.0.1") result <- access pipe master db action liftIO $ close pipe case result of Right val -> return val Left failure -> fail $ show failure
66866730cec3d673cbf0eac5cfdcc60b7ed8f7ccf9e0b3a19a39a4cbfc166c09
zhugecaomao/AutoLISP
dycy-标注序号.lsp
用于标注序号的程序 ;; 希望能够对大家的绘图工作有所帮助 ;;用于标注序号的LISP程序 ;;序号可以自动累计标注 必须在图形中设置6图层用于标注 (defun C:DYCY();;;(/ r p1 p2 p3 p4 x y a x1 y1 n nn) 文字设置 " 汉字HZ字型是否存在 " 字高是否为定值 (/= (getvar "TEXTSTYLE") "standard");当前字型是否为"hz" ) (command "style" "standard" "gbeitc,gbcbig" (* mm 10) 1 0 "n" "n");设置字型" ) ) (defun tc_sz() 6图层是否存在 当前图层是否为6图层 ) LCA - COMMENT : The LAYER command has new options . 设置"dim图层 " 设置线型为连续线型 (command "layer" "s" "6" "c" "white" "" "") ) 判断条件不成立设置图层 (command "layer" "s" "6" "c" "white" "" "") (command "linetype" "s" "continuous" "") ) ) ) 主程序开始 (setq olderr *error* ;;;保存初始设置 *error* yyerr oldcmd (getvar "cmdecho") oldos (getvar "osmode") ) (setvar "osmode" 0);;;取消捉 (setq nn 1) (if (= mm nil) (progn (setq mm (getreal "\n 输入绘图比例1:mm<1:1>")) (if (= mm nil)(setq mm 1)) ) ) (wz_sz) (tc_sz) ( setq mmm ( * 10 mm ) ) (setvar "ORTHOMODE" 0) (setq p1 1) (while p1 (setq p1 (getpoint "选定标注零件插入点 <停止标注>:")) (if p1 ;;* (progn ( setq p1 ( getpoint " 指定件号点 : " ) ) (setq p2 (getpoint p1 "指定标注点:")) (if (= no nil) (setq no (getint "起始序号<1>")) ) (if (= no nil) (setq no 1)) (setvar "ORTHOMODE" 1) (setq p4 (getpoint p2 "指定标注方向点:")) (setq xx (- (car p4) (car p2))) (setq yy (- (cadr p4) (cadr p2))) (setq r (* 8 mm)) (setq n (getint "\n零件数量N=?<1>")) (if (= n nil) (setq n 1)) ( setq n ( - n 1 ) ) ; ; * * * * * * * * (setq x (-(car p2)(car p1))) (setq y (-(cadr p2)(cadr p1))) (setq a (atan (/(abs y)(abs x)))) (setq y1 (* (sin a) r)) (setq x1 (* (cos a) r)) (cond ((and (>= x 0)(>= y 0)) (setq p3 (list (+(car p2) x1)(+ (cadr p2) y1))) ) ((and (< x 0)(> y 0)) (setq p3 (list (-(car p2) x1)(+ (cadr p2) y1))) ) ((and (< x 0)(< y 0)) (setq p3 (list (-(car p2) x1)(- (cadr p2) y1))) ) ((and (> x 0)(< y 0)) (setq p3 (list (+(car p2) x1)(- (cadr p2) y1))) ) ) (command "color" "7") (command "donut" 0 0.8 p1 "") (command "line" p1 p2 "") (if (or (<= n 1) (and (> x 0)(< y 0)) (and (> x 0)(= yy 0)) (and (< x 0)(< y 0)(= xx 0))) (progn (command "circle" p3 (* 8 mm) "") ;;; (if (and (< x 0)(> n 0)) ( ( + no n 1 ) ) ( setq p3 ( polar p3 pi ( * n 2 r ) ) ) (command "text" "j" "m" p3 "0" no);********** (setq no (+ 1 no)) ) ) ;;;(if (<= n 0) (command "text" "j" "m" p3 "0" no));********** ;;; (setq no (+ 1 no)) (setq x (-(car p4)(car p2))) (setq y (-(cadr p4)(cadr p2))) (if (and (= x 0) (> y 0)) (progn (setq x1 0) (setq y1 (* 2 r)) ) ) (if (and (= x 0) (< y 0)) (progn (setq x1 0) (setq y1 (* 2 (- 0 r))) ) ) (if (and (= y 0) (> x 0)) (progn (setq y1 0) (setq x1 (* 2 r)) ) ) (if (and (= y 0) (< x 0)) (progn (setq y1 0) (setq x1 (* 2 (- 0 r))) ) ) (if (and (< x 0)(> n 0)) (setq p3 (polar p3 pi (* 2 n r))) ) (if (and (> y 0)(> n 0)) (setq p3 (polar p3 (* pi 0.5) (* 2 n r))) ) (if (or (<= n 1) (> x 0) (and (> x 0)(= yy 0)) (and (< x 0)(< y 0)(= xx 0))) (setq n (- n 1))) (if (or (and (< y 0) (= xx 0)) (and (< y 0) (= xx 0))) (setq n (- n 1)));;88888888888 (setq nn0 1) (while (<= nn0 n) (cond ((and (< x 0)(> n 1)) (progn (setq p3 (list (- (car p3) x1)(+ (cadr p3) y1))) (command "circle" p3 (* 8 mm) "") (command "text" "j" "m" p3 "0" no ) (setq no (+ 1 no)) (setq nn0 (+ nn0 1)) ) ) ((and (> y 0) (> n 1)) (progn (setq p3 (list (+ (car p3) x1)(- (cadr p3) y1))) (command "circle" p3 (* 8 mm) "") (command "text" "j" "m" p3 "0" no ) (setq no (+ 1 no)) (setq nn0 (+ nn0 1)) ) ) ((OR (> x 0) (< y 0)) (progn (setq p3 (list (+ (car p3) x1)(+ (cadr p3) y1))) (command "circle" p3 (* 8 mm) "") (command "text" "j" "m" p3 "0" no ) (setq no (+ 1 no)) (setq nn0 (+ nn0 1)) ) ) ) ) (setvar "ORTHOMODE" 0) ) ) ) (command "redraw") (setq *error* olderr) ;;;恢复原设置 (SETVAR "CMDECHO" OLDCMD) (setvar "osmode" oldos) (princ) )
null
https://raw.githubusercontent.com/zhugecaomao/AutoLISP/3e97f911068124f3ea8a1cf6f1d8be9f8227c64b/dycy-%E6%A0%87%E6%B3%A8%E5%BA%8F%E5%8F%B7.lsp
lisp
希望能够对大家的绘图工作有所帮助 用于标注序号的LISP程序 序号可以自动累计标注 (/ r p1 p2 p3 p4 x y a x1 y1 n nn) 当前字型是否为"hz" 设置字型" 保存初始设置 取消捉 * ; * * * * * * * * (if (and (< x 0)(> n 0)) ********** (if (<= n 0) (command "text" "j" "m" p3 "0" no));********** (setq no (+ 1 no)) 88888888888 恢复原设置
用于标注序号的程序 必须在图形中设置6图层用于标注 文字设置 " 汉字HZ字型是否存在 " 字高是否为定值 ) ) ) (defun tc_sz() 6图层是否存在 当前图层是否为6图层 ) LCA - COMMENT : The LAYER command has new options . 设置"dim图层 " 设置线型为连续线型 (command "layer" "s" "6" "c" "white" "" "") ) 判断条件不成立设置图层 (command "layer" "s" "6" "c" "white" "" "") (command "linetype" "s" "continuous" "") ) ) ) 主程序开始 *error* yyerr oldcmd (getvar "cmdecho") oldos (getvar "osmode") ) (setq nn 1) (if (= mm nil) (progn (setq mm (getreal "\n 输入绘图比例1:mm<1:1>")) (if (= mm nil)(setq mm 1)) ) ) (wz_sz) (tc_sz) ( setq mmm ( * 10 mm ) ) (setvar "ORTHOMODE" 0) (setq p1 1) (while p1 (setq p1 (getpoint "选定标注零件插入点 <停止标注>:")) (progn ( setq p1 ( getpoint " 指定件号点 : " ) ) (setq p2 (getpoint p1 "指定标注点:")) (if (= no nil) (setq no (getint "起始序号<1>")) ) (if (= no nil) (setq no 1)) (setvar "ORTHOMODE" 1) (setq p4 (getpoint p2 "指定标注方向点:")) (setq xx (- (car p4) (car p2))) (setq yy (- (cadr p4) (cadr p2))) (setq r (* 8 mm)) (setq n (getint "\n零件数量N=?<1>")) (if (= n nil) (setq n 1)) (setq x (-(car p2)(car p1))) (setq y (-(cadr p2)(cadr p1))) (setq a (atan (/(abs y)(abs x)))) (setq y1 (* (sin a) r)) (setq x1 (* (cos a) r)) (cond ((and (>= x 0)(>= y 0)) (setq p3 (list (+(car p2) x1)(+ (cadr p2) y1))) ) ((and (< x 0)(> y 0)) (setq p3 (list (-(car p2) x1)(+ (cadr p2) y1))) ) ((and (< x 0)(< y 0)) (setq p3 (list (-(car p2) x1)(- (cadr p2) y1))) ) ((and (> x 0)(< y 0)) (setq p3 (list (+(car p2) x1)(- (cadr p2) y1))) ) ) (command "color" "7") (command "donut" 0 0.8 p1 "") (command "line" p1 p2 "") (if (or (<= n 1) (and (> x 0)(< y 0)) (and (> x 0)(= yy 0)) (and (< x 0)(< y 0)(= xx 0))) (progn (command "circle" p3 (* 8 mm) "") ( ( + no n 1 ) ) ( setq p3 ( polar p3 pi ( * n 2 r ) ) ) (setq no (+ 1 no)) ) ) (setq x (-(car p4)(car p2))) (setq y (-(cadr p4)(cadr p2))) (if (and (= x 0) (> y 0)) (progn (setq x1 0) (setq y1 (* 2 r)) ) ) (if (and (= x 0) (< y 0)) (progn (setq x1 0) (setq y1 (* 2 (- 0 r))) ) ) (if (and (= y 0) (> x 0)) (progn (setq y1 0) (setq x1 (* 2 r)) ) ) (if (and (= y 0) (< x 0)) (progn (setq y1 0) (setq x1 (* 2 (- 0 r))) ) ) (if (and (< x 0)(> n 0)) (setq p3 (polar p3 pi (* 2 n r))) ) (if (and (> y 0)(> n 0)) (setq p3 (polar p3 (* pi 0.5) (* 2 n r))) ) (if (or (<= n 1) (> x 0) (and (> x 0)(= yy 0)) (and (< x 0)(< y 0)(= xx 0))) (setq n (- n 1))) (setq nn0 1) (while (<= nn0 n) (cond ((and (< x 0)(> n 1)) (progn (setq p3 (list (- (car p3) x1)(+ (cadr p3) y1))) (command "circle" p3 (* 8 mm) "") (command "text" "j" "m" p3 "0" no ) (setq no (+ 1 no)) (setq nn0 (+ nn0 1)) ) ) ((and (> y 0) (> n 1)) (progn (setq p3 (list (+ (car p3) x1)(- (cadr p3) y1))) (command "circle" p3 (* 8 mm) "") (command "text" "j" "m" p3 "0" no ) (setq no (+ 1 no)) (setq nn0 (+ nn0 1)) ) ) ((OR (> x 0) (< y 0)) (progn (setq p3 (list (+ (car p3) x1)(+ (cadr p3) y1))) (command "circle" p3 (* 8 mm) "") (command "text" "j" "m" p3 "0" no ) (setq no (+ 1 no)) (setq nn0 (+ nn0 1)) ) ) ) ) (setvar "ORTHOMODE" 0) ) ) ) (command "redraw") (SETVAR "CMDECHO" OLDCMD) (setvar "osmode" oldos) (princ) )
fcdeb0dc5f2213a4e1f31795ae2172398d2defa2db1df012bd44b9179e6d16b6
Nibre/BlamScript-Research
08b_deltacontrol_cinematics.lisp
CINEMATICS FOR LEVEL 08B , " DELTA CONTROL " = = = = = = = = = = = = = = = = = = = = = = = = = = = ; ===================================================================== ;* ;| Between the desire ;| And the spasm ;| Between the potency ;| And the existence ;| Between the essence ;| And the descent ;| Falls the Shadow... ;| ;| ...This is the way the world ends ;| Not with a bang but a whimper. ;*; GLOBALS & STUBS = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = (global short sound_offset 15) (global short prediction_offset 45) (script stub void 08_intra1_04_predict_stub (print "predict 04")) (script stub void 08_intra2_01_predict_stub (print "predict 01")) (script stub void 08_intra2_02_predict_stub (print "predict 02")) (script stub void 08_intra3_01_predict_stub (print "predict 01")) (script stub void 08_intra3_02_predict_stub (print "predict 02")) (script stub void 08_intra3_03_predict_stub (print "predict 03")) (script stub void 08_intra3_04_predict_stub (print "predict 04")) (script stub void 08_intra3_05_predict_stub (print "predict 05")) (script stub void 08_intra3_06_predict_stub (print "predict 06")) (script stub void x09_01_predict_stub (print "predict 01")) (script stub void x09_02_predict_stub (print "predict 02")) (script stub void x09_03_predict_stub (print "predict 03")) (script stub void x09_04_predict_stub (print "predict 04")) (script stub void x09_05_predict_stub (print "predict 05")) (script stub void x09_06_predict_stub (print "predict 06")) (script stub void x09_07_predict_stub (print "predict 07")) (script stub void x09_08_predict_stub (print "predict 08")) (script stub void x10_01_predict_stub (print "predict 01")) (script stub void x10_02_predict_stub (print "predict 02")) ; C08_INTRA1 SCENE 04 ------------------------------------------------- ; SOUND --------------------------------------------------------------- (script dormant c08_intra1_score_04 (sleep 0) (sound_impulse_start sound\cinematics\08_deltacliffs\c08_intra1\music\c08_intra1_04_mus none 1) (print "c08_intra1 score 04 start") ) (script dormant c08_intra1_foley_04 (sleep 0) (sound_impulse_start sound\cinematics\08_deltacliffs\c08_intra1\foley\c08_intra1_04_fol none 1) (print "c08_intra1 foley 04 start") ) (script dormant c08_2050_der (sleep 60) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_2050_der dervish_02 1) (cinematic_subtitle c08_2050_der 1) ) (script dormant c08_2060_soc (sleep 92) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_2060_soc commander 1) (cinematic_subtitle c08_2060_soc 6) ) (script dormant c08_2070_grv (sleep 273) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_2070_grv none 1) (cinematic_subtitle c08_2070_grv 5) (cinematic_lightmap_shadow_disable) ) (script dormant c08_2080_der (sleep 425) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_2080_der dervish_02 1) (cinematic_subtitle c08_2080_der 2) ) (script dormant c08_2090_soc (sleep 473) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_2090_soc commander 1) (cinematic_subtitle c08_2090_soc 1) ) (script dormant c08_2100_soc (sleep 512) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_2100_soc commander 1) (cinematic_subtitle c08_2100_soc 2) ) ; EFFECTS & LIGHTING -------------------------------------------------- (script dormant c04_intra1_fov_04 (sleep 511) (print "fov change: 80 -> 60 over 0 ticks") (camera_set_field_of_view 60 0) ) (script dormant c04_intra1_dof_04 (sleep 427) (cinematic_screen_effect_start 1) (cinematic_screen_effect_set_depth_of_field 1.17 .5 .5 0 0 0 0) (print "rack focus") (sleep 84) (cinematic_screen_effect_set_depth_of_field .5 .5 .5 0 0 0 0) (print "rack focus") (sleep 100) (cinematic_screen_effect_set_depth_of_field .5 .5 0 0 0 .5 .5) (print "rack focus") ) (script dormant cinematic_lighting_intra1_04 (cinematic_lighting_set_primary_light 40 134 0.321569 0.321569 0.290196) (cinematic_lighting_set_secondary_light 8 274 0.301961 0.290196 0.45098) (cinematic_lighting_set_ambient_light 0.121569 0.121569 0.0705882) (object_uses_cinematic_lighting dervish_02 1) (object_uses_cinematic_lighting commander 1) (object_uses_cinematic_lighting wraith_01 1) ) ; PREDICTION ---------------------------------------------------------- (script static void c08_intra1_04_problem_actors (print "problem actors") (object_create_anew dervish_02) (object_create_anew commander) (object_create_anew wraith_01) (cinematic_clone_players_weapon dervish_02 "right_hand_elite" "") (object_cinematic_lod dervish_02 true) (object_cinematic_lod commander true) (object_cinematic_lod wraith_01 true) ) ; --------------------------------------------------------------------- (script static void c08_intra1_04_setup (wake c08_intra1_score_04) (wake c08_intra1_foley_04) (wake c08_2050_der) (wake c08_2060_soc) (wake c08_2070_grv) (wake c08_2080_der) (wake c08_2090_soc) (wake c08_2100_soc) (wake c04_intra1_fov_04) (wake c04_intra1_dof_04) (wake cinematic_lighting_intra1_04) ) (script static void c08_intra1_04_cleanup (object_destroy dervish_02) (object_destroy commander) (object_destroy wraith_01) ) (script static void c08_intra1 (texture_cache_flush) (geometry_cache_flush) (sound_class_set_gain vehicle 0 0) (fade_out 0 0 0 0) (camera_control on) (cinematic_start) (set cinematic_letterbox_style 1) (camera_set_field_of_view 60 0) (cinematic_lightmap_shadow_enable) (c08_intra1_04_problem_actors) ; PREDICTION ->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> (08_intra1_04_predict_stub) (sound_impulse_predict sound\cinematics\08_deltacliffs\c08_intra1\music\c08_intra1_04_mus) (sound_impulse_predict sound\cinematics\08_deltacliffs\c08_intra1\foley\c08_intra1_04_fol) (sleep prediction_offset) (c08_intra1_04_setup) (camera_set_animation_relative objects\characters\cinematic_camera\08_intra1\08_intra1 "08_intra1_04" none "anchor_flag_intra1") (custom_animation_relative dervish_02 objects\characters\dervish\08_intra1\08_intra1 "dervish_04" false anchor_intra1) (custom_animation_relative commander objects\characters\elite\08_intra1\08_intra1 "commander_04" false anchor_intra1) (custom_animation_relative wraith_01 objects\vehicles\wraith\08_intra1\08_intra1 "wraith_04" false anchor_intra1) (print "cache block") (sleep 1) (cache_block_for_one_frame) (fade_in 0 0 0 30) (sleep (- (camera_time) 15)) (fade_out 1 1 1 15) (sleep 15) (c08_intra1_04_cleanup) (cinematic_screen_effect_stop) (sleep 30) (sound_class_set_gain vehicle 1 1) ) ; C08_INTRA2 SCENE 01 ------------------------------------------------- ; SOUND --------------------------------------------------------------- (script dormant c08_intra2_foley_01 (sleep 0) (sound_impulse_start sound\cinematics\08_deltacliffs\c08_intra2\foley\c08_intra2_01_fol none 1) (print "c08_intra2 foley 01 start") ) (script dormant c08_3010_jon (sleep 100) (sound_impulse_start_effect sound\dialog\levels\08_controlroom\cinematic\c08_3010_jon johnson_02 1 radio_covy_in) (cinematic_subtitle c08_3010_jon 3) ) (script dormant c08_3020_jon (sleep 203) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_3020_jon johnson_02 1) (cinematic_subtitle c08_3020_jon 3) ) (script dormant c08_3030_jon (sleep 316) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_3030_jon johnson_02 1) (cinematic_subtitle c08_3030_jon 2) ) (script dormant c08_3040_der (sleep 359) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_3040_der dervish_02 1) (cinematic_subtitle c08_3040_der 3) ) ; EFFECTS & LIGHTING -------------------------------------------------- (script dormant intra2_texture_cam_01 (object_create_anew texture_camera) (texture_camera_set_object_marker texture_camera marker 35) (scenery_animation_start_relative texture_camera objects\cinematics\texture_camera\08_intra2\08_intra2 "texture_camera_01" anchor_intra2) ) (script dormant cinematic_lighting_intra2 (cinematic_lighting_set_primary_light 33 0 0.258824 0.278431 0.34902) (cinematic_lighting_set_secondary_light -37 228 0.109804 0.419608 0.611765) (cinematic_lighting_set_ambient_light 0.121569 0.121569 0.0705882) (object_uses_cinematic_lighting dervish_02 1) (object_uses_cinematic_lighting johnson_02 1) (object_uses_cinematic_lighting scarab_01 1) ) ; PROBLEM ACTORS ------------------------------------------------------ (script static void c08_intra2_problem_actors (print "problem actors") (object_create_anew dervish_02) (object_cinematic_lod dervish_02 true) (cinematic_clone_players_weapon dervish_02 "right_hand_elite" "") ) ; --------------------------------------------------------------------- (script dormant scarab_shake (sleep 45) (print "shake") (player_effect_set_max_rotation 0 1 1) (player_effect_start .25 2) (sleep 240) (player_effect_stop 2) ) (script static void c08_intra2_01_setup (object_destroy scarab) (object_create_anew johnson_02) (object_create_anew scarab_01) (object_create_anew scarab_screen) (objects_attach scarab_01 "holo_scarab_full" scarab_screen "") (object_cinematic_lod johnson_02 true) (object_cinematic_lod scarab_01 true) (unit_set_emotional_state johnson_02 angry .25 0) (wake c08_intra2_foley_01) (wake c08_3010_jon) (wake c08_3020_jon) (wake c08_3030_jon) (wake c08_3040_der) ( wake ) (wake scarab_shake) (wake intra2_texture_cam_01) (wake cinematic_lighting_intra2) ) (script static void c08_intra2_scene_01 (fade_out 1 1 1 0) (camera_control on) (cinematic_start) (set cinematic_letterbox_style 1) (camera_set_field_of_view 60 0) (cinematic_lightmap_shadow_enable) (c08_intra2_problem_actors) ; PREDICTION ->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> (08_intra2_01_predict_stub) (sound_impulse_predict sound\cinematics\08_deltacliffs\c08_intra2\foley\c08_intra2_01_fol) (sleep prediction_offset) ; safety white (sleep 45) (c08_intra2_01_setup) (camera_set_animation_relative objects\characters\cinematic_camera\08_intra2\08_intra2 "08_intra2_01" none "anchor_flag_intra2") (custom_animation_relative dervish_02 objects\characters\dervish\08_intra2\08_intra2 "dervish_01" false anchor_intra2) (custom_animation_relative johnson_02 objects\characters\marine\08_intra2\08_intra2 "johnson_01" false anchor_intra2) (scenery_animation_start_relative scarab_01 scenarios\objects\covenant\military\scarab\08_intra2\08_intra2 "scarab_01" anchor_intra2) (fade_in 1 1 1 15) ; PREDICTION ->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> (sleep (- (camera_time) prediction_offset)) (08_intra2_02_predict_stub) (sleep (- (camera_time) sound_offset)) (sound_impulse_predict sound\cinematics\08_deltacliffs\c08_intra2\foley\c08_intra2_02_fol) (sleep (camera_time)) ) ; C08_INTRA2 SCENE 02 ------------------------------------------------- ; SOUND --------------------------------------------------------------- (script dormant c08_intra2_foley_02 (sleep 0) (sound_impulse_start sound\cinematics\08_deltacliffs\c08_intra2\foley\c08_intra2_02_fol none 1) (print "c08_intra1 foley 04 start") ) (script dormant c08_3050_jon (sleep 70) (sound_impulse_start_effect sound\dialog\levels\08_controlroom\cinematic\c08_3050_jon johnson_02 1 radio_covy_loop) (cinematic_subtitle c08_3050_jon 2) ) (script dormant c08_3061_jon (sleep 156) (sound_impulse_start_effect sound\dialog\levels\08_controlroom\cinematic\c08_3061_jon johnson_02 1 radio_covy_loop) (cinematic_subtitle c08_3061_jon 2) ) (script dormant c08_3070_jon (sleep 231) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_3070_jon johnson_02 1) (cinematic_subtitle c08_3070_jon 1) (unit_set_emotional_state johnson_02 angry .75 45) ) ; EFFECTS & LIGHTING -------------------------------------------------- (script dormant intra2_dof (sleep 68) (cinematic_screen_effect_start true) (cinematic_screen_effect_set_depth_of_field 1 .5 .5 0.001 0 0 0.001) (print "rack focus") (sleep 151) (cinematic_screen_effect_stop) (print "rack focus stop") ) ; --------------------------------------------------------------------- (script dormant scarab_shake2 (sleep 137) (print "shake") (player_effect_set_max_rotation 0 1 1) (player_effect_start .75 .15) (sleep 5) (player_effect_stop .5) ) (script static void c08_intra2_02_setup (wake c08_intra2_foley_02) (wake c08_3050_jon) (wake c08_3061_jon) (wake c08_3070_jon) (wake intra2_dof) (wake scarab_shake2) ) (script static void c08_intra2_02_cleanup (object_destroy dervish_02) (object_destroy johnson_02) (object_destroy scarab_01) (object_destroy scarab_screen) (object_create_anew scarab) ) (script static void c08_intra2_scene_02 (c08_intra2_02_setup) (camera_set_animation_relative objects\characters\cinematic_camera\08_intra2\08_intra2 "08_intra2_02" none "anchor_flag_intra2") (custom_animation_relative dervish_02 objects\characters\dervish\08_intra2\08_intra2 "dervish_02" false anchor_intra2) (custom_animation_relative johnson_02 objects\characters\marine\08_intra2\08_intra2 "johnson_02" false anchor_intra2) (scenery_animation_start_relative scarab_01 scenarios\objects\covenant\military\scarab\08_intra2\08_intra2 "scarab_02" anchor_intra2) (sleep (- (camera_time) 15)) (fade_out 1 1 1 15) (sleep 15) (c08_intra2_02_cleanup) (sound_class_set_gain amb 0 15) (sleep 15) ) ; C08_INTRA2 MASTER SCRIPT ============================================ ; ===================================================================== (script static void c08_intra2 (texture_cache_flush) (geometry_cache_flush) (switch_bsp_by_name deltacontrolroom_bsp0) (sleep 1) (c08_intra2_scene_01) (c08_intra2_scene_02) ) ; C08_INTRA3 SCENE 01 ------------------------------------------------- ; SOUND --------------------------------------------------------------- (script dormant c08_intra3_foley_01 (sleep 0) (sound_impulse_start sound\cinematics\08_deltacliffs\c08_intra3\foley\c08_intra3_01_fol none 1) (print "c08_intra3 foley 01 start") ) (script dormant c08_4010_tar (sleep 0) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4010_tar tartarus 1) (cinematic_subtitle c08_4010_tar 4) ) (script dormant c08_4020_tar (sleep 167) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4020_tar tartarus 1) (cinematic_subtitle c08_4020_tar 3) ) (script dormant c08_4030_gsp (sleep 251) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4030_gsp monitor 1) (cinematic_subtitle c08_4030_gsp 3) ) (script dormant c08_4040_tar (sleep 344) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4040_tar tartarus 1) (cinematic_subtitle c08_4040_tar 4) ) (script dormant c08_4050_mir (sleep 486) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4050_mir miranda 1) (cinematic_subtitle c08_4050_mir 1) ) (script dormant c08_4060_tar (sleep 510) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4060_tar tartarus 1) (cinematic_subtitle c08_4060_tar 3) ) LIGHTING & EFFECTS -------------------------------------------------- (script dormant c08_intra3_fov_01 (sleep 246) (camera_set_field_of_view 30 0) (print "fov change: 60 -> 30 over 0 ticks") (sleep 105) (camera_set_field_of_view 60 13) (print "fov change: 30 -> 60 over 13 ticks") ) (script dormant cinematic_lighting_intra3_01 (cinematic_lighting_set_primary_light 63 80 0.180392 0.168627 0.129412) (cinematic_lighting_set_secondary_light -51 188 0.101961 0.2 0.301961) (cinematic_lighting_set_ambient_light 0.121569 0.121569 0.0705882) (rasterizer_bloom_override 1) (rasterizer_bloom_override_threshold .3) (rasterizer_bloom_override_brightness .5) (object_uses_cinematic_lighting miranda 1) (object_uses_cinematic_lighting tartarus 1) (object_uses_cinematic_lighting brute_01 1) (object_uses_cinematic_lighting brute_02 1) (object_uses_cinematic_lighting brute_03 1) (object_uses_cinematic_lighting brute_04 1) (object_uses_cinematic_lighting monitor 1) (object_uses_cinematic_lighting index 1) ) ; PROBLEM ACTORS ------------------------------------------------------ (script static void c08_intra3_problem_actors_01 (print "problem actors") (object_create_anew miranda) (object_create_anew tartarus) (object_create_anew brute_01) (object_create_anew brute_02) (object_create_anew brute_03) (object_create_anew brute_04) (object_create_anew monitor) (object_cinematic_lod miranda true) (object_cinematic_lod tartarus true) (object_cinematic_lod brute_01 true) (object_cinematic_lod brute_02 true) (object_cinematic_lod brute_03 true) (object_cinematic_lod brute_04 true) (object_cinematic_lod monitor true) ) ; --------------------------------------------------------------------- (script dormant c08_intra2_miranda_emotion_01 (unit_set_emotional_state miranda angry .25 0) (sleep 180) (unit_set_emotional_state miranda angry .75 30) ) (script dormant c08_intra2_miranda_emotion_02 (sleep 488) (unit_set_emotional_state miranda pain .75 30) (sleep 81) (unit_set_emotional_state miranda angry .25 60) ) (script static void c08_intra3_01_setup ; (object_create_anew hammer) (object_create_anew index) (object_create_anew repository) ; (object_cinematic_lod hammer true) (object_cinematic_lod index true) (object_cinematic_lod repository true) (wake c08_intra3_foley_01) (wake c08_4010_tar) (wake c08_4020_tar) (wake c08_4030_gsp) (wake c08_4040_tar) (wake c08_4050_mir) (wake c08_4060_tar) (wake c08_intra2_miranda_emotion_01) (wake c08_intra2_miranda_emotion_02) ( wake ) (wake c08_intra3_fov_01) (wake cinematic_lighting_intra3_01) ) (script static void c08_intra3_scene_01 (fade_out 1 1 1 0) (camera_control on) (cinematic_start) (set cinematic_letterbox_style 1) (camera_set_field_of_view 60 0) (c08_intra3_problem_actors_01) ; PREDICTION ->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> (08_intra3_01_predict_stub) (sound_impulse_predict sound\cinematics\08_deltacliffs\c08_intra3\foley\c08_intra3_01_fol) (sleep prediction_offset) (c08_intra3_01_setup) (camera_set_animation_relative objects\characters\cinematic_camera\08_intra3\08_intra3 "08_intra3_01" none "anchor_flag_intra3") (custom_animation_relative miranda objects\characters\miranda\08_intra3\08_intra3 "miranda_01" false anchor_intra3) (custom_animation_relative monitor objects\characters\monitor\08_intra3\08_intra3 "monitor_01" false anchor_intra3) (custom_animation_relative tartarus objects\characters\brute\08_intra3\08_intra3 "tartarus_01" false anchor_intra3) (custom_animation_relative brute_01 objects\characters\brute\08_intra3\08_intra3 "brute01_01" false anchor_intra3) (custom_animation_relative brute_02 objects\characters\brute\08_intra3\08_intra3 "brute02_01" false anchor_intra3) (custom_animation_relative brute_03 objects\characters\brute\08_intra3\08_intra3 "brute03_01" false anchor_intra3) (custom_animation_relative brute_04 objects\characters\brute\08_intra3\08_intra3 "brute04_01" false anchor_intra3) ( scenery_animation_start_relative hammer objects\weapons\melee\gravity_hammer\08_intra3\08_intra3 " " anchor_intra3 ) (scenery_animation_start_relative index scenarios\objects\forerunner\industrial\index\index_full\08_intra3\08_intra3 "index_01" anchor_intra3) (fade_in 1 1 1 15) ; PREDICTION ->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> (sleep (- (camera_time) prediction_offset)) (08_intra3_02_predict_stub) (sleep (- (camera_time) sound_offset)) (sound_impulse_predict sound\cinematics\08_deltacliffs\c08_intra3\music\c08_intra3_02_mus) (sound_impulse_predict sound\cinematics\08_deltacliffs\c08_intra3\foley\c08_intra3_02_fol) (sleep (camera_time)) ) ; C08_INTRA3 SCENE 02 ------------------------------------------------- ; SOUND --------------------------------------------------------------- (script dormant c08_intra3_score_02 (sleep 0) (sound_impulse_start sound\cinematics\08_deltacliffs\c08_intra3\music\c08_intra3_02_mus none 1) (print "c08_intra3 score 02 start") ) (script dormant c08_intra3_foley_02 (sleep 0) (sound_impulse_start sound\cinematics\08_deltacliffs\c08_intra3\foley\c08_intra3_02_fol none 1) (print "c08_intra3 foley 02 start") ) (script dormant c08_4070_der (sleep 36) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4070_der dervish 1) (cinematic_subtitle c08_4070_der 1) ) (script dormant c08_4080_tar (sleep 77) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4080_tar tartarus 1) (cinematic_subtitle c08_4080_tar 3) ) (script dormant c08_4100_der (sleep 157) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4100_der dervish 1) (cinematic_subtitle c08_4100_der 2) ) (script dormant c08_4110_tar (sleep 212) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4110_tar tartarus 1) (cinematic_subtitle c08_4110_tar 3) ) (script dormant c08_4120_der (sleep 312) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4120_der dervish 1) (cinematic_subtitle c08_4120_der 5) ) (script dormant c08_4140_tar (sleep 516) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4140_tar tartarus 1) (cinematic_subtitle c08_4140_tar 4) ) (script dormant c08_4150_der (sleep 628) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4150_der dervish 1) (cinematic_subtitle c08_4150_der 1) ) (script dormant c08_4160_der (sleep 681) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4160_der dervish 1) (cinematic_subtitle c08_4160_der 3) ) ; --------------------------------------------------------------------- (script dormant unhide_dervish (time_code_reset) (sleep 10) (print "unhide dervish") (object_hide dervish false) ) (script static void c08_intra3_02_setup (object_create_anew dervish) (object_cinematic_lod dervish true) (object_hide dervish true) (cinematic_clone_players_weapon dervish "right_hand_elite" "") (wake c08_intra3_score_02) (wake c08_intra3_foley_02) (wake c08_4070_der) (wake c08_4080_tar) (wake c08_4100_der) (wake c08_4110_tar) (wake c08_4120_der) (wake c08_4140_tar) (wake c08_4150_der) (wake c08_4160_der) (wake unhide_dervish) ( wake ) ) (script static void c08_intra3_scene_02 (c08_intra3_02_setup) (camera_set_animation_relative objects\characters\cinematic_camera\08_intra3\08_intra3 "08_intra3_02" none "anchor_flag_intra3") (custom_animation_relative miranda objects\characters\miranda\08_intra3\08_intra3 "miranda_02" false anchor_intra3) (custom_animation_relative monitor objects\characters\monitor\08_intra3\08_intra3 "monitor_02" false anchor_intra3) (custom_animation_relative dervish objects\characters\dervish\08_intra3\08_intra3 "dervish_02" false anchor_intra3) (custom_animation_relative tartarus objects\characters\brute\08_intra3\08_intra3 "tartarus_02" false anchor_intra3) (custom_animation_relative brute_01 objects\characters\brute\08_intra3\08_intra3 "brute01_02" false anchor_intra3) (custom_animation_relative brute_02 objects\characters\brute\08_intra3\08_intra3 "brute02_02" false anchor_intra3) (custom_animation_relative brute_03 objects\characters\brute\08_intra3\08_intra3 "brute03_02" false anchor_intra3) (custom_animation_relative brute_04 objects\characters\brute\08_intra3\08_intra3 "brute04_02" false anchor_intra3) (scenery_animation_start_relative index scenarios\objects\forerunner\industrial\index\index_full\08_intra3\08_intra3 "index_02" anchor_intra3) ; PREDICTION ->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> (sleep (- (camera_time) prediction_offset)) (08_intra3_03_predict_stub) (sleep (- (camera_time) sound_offset)) (sound_impulse_predict sound\cinematics\08_deltacliffs\c08_intra3\foley\c08_intra3_03_fol) (sleep (camera_time)) ) ; C08_INTRA3 SCENE 03 ------------------------------------------------- ; SOUND --------------------------------------------------------------- (script dormant c08_intra3_foley_03 (sleep 0) (sound_impulse_start sound\cinematics\08_deltacliffs\c08_intra3\foley\c08_intra3_03_fol none 1) (print "c08_intra3 foley 03 start") ) (script dormant c08_4170_gsp (sleep 0) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4170_gsp monitor 1) (cinematic_subtitle c08_4170_gsp 2) ) (script dormant c08_4180_tar (sleep 41) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4180_tar tartarus 1) (cinematic_subtitle c08_4180_tar 2) ) (script dormant c08_4190_tar (sleep 84) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4190_tar tartarus 1) (cinematic_subtitle c08_4190_tar 2) ) (script dormant c08_4200_jon (sleep 137) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4200_jon johnson 1) (cinematic_subtitle c08_4200_jon 1) (unit_set_emotional_state johnson angry .5 0) (print "johnson - angry .5 0") ) (script dormant c08_4201_jon (sleep 202) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4201_jon johnson 1) (cinematic_subtitle c08_4201_jon 2) ) (script dormant c08_4220_jon (sleep 308) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4220_jon johnson 1) (cinematic_subtitle c08_4220_jon 3) (unit_set_emotional_state johnson angry 1 15) (print "johnson - angry 1 15") ) (script dormant c08_4230_tar (sleep 430) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4230_tar tartarus 1) (cinematic_subtitle c08_4230_tar 1) ) (script dormant c08_4240_jon (sleep 474) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4240_jon johnson 1) (cinematic_subtitle c08_4240_jon 2) ) (script dormant c08_4250_der (sleep 548) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4250_der dervish 1) (cinematic_subtitle c08_4250_der 2) ) ; EFFECTS & LIGHTING -------------------------------------------------- (script dormant c08_intra3_fov_03 (sleep 184) (camera_set_field_of_view 5 21) (print "fov change: 60 -> 5 over 21 ticks") (sleep 69) (camera_set_field_of_view 60 0) (print "fov change: 5 -> 60 over 0 ticks") ) (script dormant cinematic_lighting_intra3_03 (object_uses_cinematic_lighting johnson 1) (object_uses_cinematic_lighting cov_sniper 1) ) ; --------------------------------------------------------------------- (script static void c08_intra3_03_setup (object_create_anew johnson) (object_create_anew cov_sniper) (object_cinematic_lod johnson true) (object_cinematic_lod cov_sniper true) (objects_attach johnson "right_hand" cov_sniper "") (wake c08_intra3_foley_03) (wake c08_4170_gsp) (wake c08_4180_tar) (wake c08_4190_tar) (wake c08_4200_jon) (wake c08_4201_jon) (wake c08_4220_jon) (wake c08_4230_tar) (wake c08_4240_jon) (wake c08_4250_der) ( wake ) (wake c08_intra3_fov_03) (wake cinematic_lighting_intra3_03) ) (script static void c08_intra3_scene_03 (c08_intra3_03_setup) (camera_set_animation_relative objects\characters\cinematic_camera\08_intra3\08_intra3 "08_intra3_03" none "anchor_flag_intra3") (custom_animation_relative miranda objects\characters\miranda\08_intra3\08_intra3 "miranda_03" false anchor_intra3) (custom_animation_relative johnson objects\characters\marine\08_intra3\08_intra3 "johnson_03" false anchor_intra3) (custom_animation_relative monitor objects\characters\monitor\08_intra3\08_intra3 "monitor_03" false anchor_intra3) (custom_animation_relative dervish objects\characters\dervish\08_intra3\08_intra3 "dervish_03" false anchor_intra3) (custom_animation_relative tartarus objects\characters\brute\08_intra3\08_intra3 "tartarus_03" false anchor_intra3) (custom_animation_relative brute_01 objects\characters\brute\08_intra3\08_intra3 "brute01_03" false anchor_intra3) (custom_animation_relative brute_02 objects\characters\brute\08_intra3\08_intra3 "brute02_03" false anchor_intra3) (custom_animation_relative brute_03 objects\characters\brute\08_intra3\08_intra3 "brute03_03" false anchor_intra3) (custom_animation_relative brute_04 objects\characters\brute\08_intra3\08_intra3 "brute04_03" false anchor_intra3) (scenery_animation_start_relative index scenarios\objects\forerunner\industrial\index\index_full\08_intra3\08_intra3 "index_03" anchor_intra3) ; PREDICTION ->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> (sleep (- (camera_time) prediction_offset)) (08_intra3_04_predict_stub) (sleep (- (camera_time) sound_offset)) (sound_impulse_predict sound\cinematics\08_deltacliffs\c08_intra3\foley\c08_intra3_04_fol) (sleep (camera_time)) ) ; C08_INTRA3 SCENE 04 ------------------------------------------------- ; SOUND --------------------------------------------------------------- (script dormant c08_intra3_foley_04 (sleep 0) (sound_impulse_start sound\cinematics\08_deltacliffs\c08_intra3\foley\c08_intra3_04_fol none 1) (print "c08_intra3 foley 04 start") ) (script dormant c08_4260_gsp (sleep 0) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4260_gsp monitor 1) (cinematic_subtitle c08_4260_gsp 6) (unit_set_emotional_state miranda shocked .25 0) (print "miranda - shocked .25 0") ) (script dormant c08_4270_der (sleep 189) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4270_der dervish 1) (cinematic_subtitle c08_4270_der 4) ) (script dormant c08_4280_gsp (sleep 297) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4280_gsp monitor 1) (cinematic_subtitle c08_4280_gsp 11) ) (script dormant c08_4290_gsp (sleep 640) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4290_gsp monitor 1) (cinematic_subtitle c08_4290_gsp 2) ) (script dormant c08_4300_der (sleep 746) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4300_der dervish 1) (cinematic_subtitle c08_4300_der 4) ) ; --------------------------------------------------------------------- (script static void c08_intra3_04_setup (wake c08_intra3_foley_04) (wake c08_4260_gsp) (wake c08_4270_der) (wake c08_4280_gsp) (wake c08_4290_gsp) (wake c08_4300_der) ( wake ) ) (script static void c08_intra3_scene_04 (c08_intra3_04_setup) (camera_set_animation_relative objects\characters\cinematic_camera\08_intra3\08_intra3 "08_intra3_04" none "anchor_flag_intra3") (custom_animation_relative miranda objects\characters\miranda\08_intra3\08_intra3 "miranda_04" false anchor_intra3) (custom_animation_relative johnson objects\characters\marine\08_intra3\08_intra3 "johnson_04" false anchor_intra3) (custom_animation_relative monitor objects\characters\monitor\08_intra3\08_intra3 "monitor_04" false anchor_intra3) (custom_animation_relative dervish objects\characters\dervish\08_intra3\08_intra3 "dervish_04" false anchor_intra3) (custom_animation_relative tartarus objects\characters\brute\08_intra3\08_intra3 "tartarus_04" false anchor_intra3) (scenery_animation_start_relative index scenarios\objects\forerunner\industrial\index\index_full\08_intra3\08_intra3 "index_04" anchor_intra3) ; PREDICTION ->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> (sleep (- (camera_time) prediction_offset)) (08_intra3_05_predict_stub) (sleep (- (camera_time) sound_offset)) (sound_impulse_predict sound\cinematics\08_deltacliffs\c08_intra3\foley\c08_intra3_05_fol) (sleep (camera_time)) ) ; C08_INTRA3 SCENE 05 ------------------------------------------------- ; SOUND --------------------------------------------------------------- (script dormant c08_intra3_foley_05 (sleep 0) (sound_impulse_start sound\cinematics\08_deltacliffs\c08_intra3\foley\c08_intra3_05_fol none 1) (print "c08_intra3 foley 05 start") ) (script dormant c08_4310_jon (sleep 74) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4310_jon johnson 1) (cinematic_subtitle c08_4310_jon 1) ) (script dormant c08_4320_tar (sleep 106) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4320_tar tartarus 1) (cinematic_subtitle c08_4320_tar 1) (unit_set_emotional_state miranda pain .5 0) (print "miranda - pain .5 0") (sleep 45) (unit_set_emotional_state miranda scared .5 15) (print "miranda - scared .5 15") ) (script dormant c08_4330_tar (sleep 144) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4330_tar tartarus 1) (cinematic_subtitle c08_4330_tar 2) ) (script dormant c08_4340_tar (sleep 220) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4340_tar tartarus 1) (cinematic_subtitle c08_4340_tar 4) (object_set_function_variable tartarus "invincibility" 1 60) (print "tartarus activates shield") ) LIGHTING & EFFECTS -------------------------------------------------- (script dormant cinematic_lighting_intra3_05 (object_uses_cinematic_lighting hammer 1) ) ; --------------------------------------------------------------------- (script dormant index_insertion (sleep 165) (print "slot the icon") (device_set_position repository 1) (effect_new_on_object_marker effects\objects\cinematics\index\index_insertion index "") (sleep 15) (object_destroy index) ) (script static void c08_intra3_05_setup (object_create_anew hammer) (object_cinematic_lod hammer true) (wake c08_intra3_foley_05) (wake c08_4310_jon) (wake c08_4320_tar) (wake c08_4330_tar) (wake c08_4340_tar) (wake index_insertion) ( wake ) (wake cinematic_lighting_intra3_05) ) (script dormant c08_intra3_05_cleanup (object_destroy miranda) (object_destroy johnson) (object_destroy monitor) (object_destroy dervish) (object_destroy tartarus) (object_destroy brute_01) (object_destroy brute_02) (object_destroy brute_03) (object_destroy brute_04) (object_destroy repository) (object_destroy index) (object_destroy hammer) (object_destroy cov_sniper) ) (script static void c08_intra3_scene_05 (c08_intra3_05_setup) (camera_set_animation_relative objects\characters\cinematic_camera\08_intra3\08_intra3 "08_intra3_05" none "anchor_flag_intra3") (custom_animation_relative miranda objects\characters\miranda\08_intra3\08_intra3 "miranda_05" false anchor_intra3) (custom_animation_relative johnson objects\characters\marine\08_intra3\08_intra3 "johnson_05" false anchor_intra3) (custom_animation_relative monitor objects\characters\monitor\08_intra3\08_intra3 "monitor_05" false anchor_intra3) (custom_animation_relative dervish objects\characters\dervish\08_intra3\08_intra3 "dervish_05" false anchor_intra3) (custom_animation_relative tartarus objects\characters\brute\08_intra3\08_intra3 "tartarus_05" false anchor_intra3) (custom_animation_relative brute_01 objects\characters\brute\08_intra3\08_intra3 "brute01_05" false anchor_intra3) (custom_animation_relative brute_02 objects\characters\brute\08_intra3\08_intra3 "brute02_05" false anchor_intra3) (custom_animation_relative brute_03 objects\characters\brute\08_intra3\08_intra3 "brute03_05" false anchor_intra3) (custom_animation_relative brute_04 objects\characters\brute\08_intra3\08_intra3 "brute04_05" false anchor_intra3) (scenery_animation_start_relative hammer objects\weapons\melee\gravity_hammer\08_intra3\08_intra3 "hammer_05" anchor_intra3) (scenery_animation_start_relative index scenarios\objects\forerunner\industrial\index\index_full\08_intra3\08_intra3 "index_05" anchor_intra3) ; PREDICTION ->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> (sleep (- (camera_time) prediction_offset)) (08_intra3_06_predict_stub) (sleep (- (camera_time) sound_offset)) (sound_impulse_predict sound\cinematics\08_deltacliffs\c08_intra3\music\c08_intra3_06_mus) (sound_impulse_predict sound\cinematics\08_deltacliffs\c08_intra3\foley\c08_intra3_06_fol) (sleep (camera_time)) (wake c08_intra3_05_cleanup) ) ; C08_INTRA3 SCENE 06 ------------------------------------------------- (script dormant create_lift (print "create lift") (object_create_anew c08_intra3_lift) (object_set_function_variable c08_intra3_lift "effect" 0 0) (sleep 10) (object_set_function_variable c08_intra3_lift "effect" 1 60) ) (script static void c08_intra3_scene_06 (sound_impulse_start sound\cinematics\08_deltacliffs\c08_intra3\music\c08_intra3_06_mus none 1) (sound_impulse_start sound\cinematics\08_deltacliffs\c08_intra3\foley\c08_intra3_06_fol none 1) (device_set_position e13_boss_platform 1) (print "shake") (player_effect_set_max_rotation 0 1 1) (player_effect_start .25 3) (camera_set platform_01a 0) (camera_set platform_01b 420) (sleep 300) (wake create_lift) (sleep 30) (camera_set platform_02 0) (cinematic_screen_effect_start 1) (cinematic_screen_effect_set_depth_of_field 5 0 0 0 2 2 0) (sleep 30) (cinematic_screen_effect_set_depth_of_field 5 0 2 .5 2 0 .5) (sleep 45) (player_effect_stop 1.5) (sleep 15) (print "fade to white") (fade_out 1 1 1 15) (sleep 15) (cinematic_screen_effect_stop) (object_destroy c08_intra3_lift) (sound_class_set_gain amb 0 15) (sleep 30) ) ; C08_INTRA3 MASTER SCRIPT ============================================ ; ===================================================================== (script static void c08_intra3 (texture_cache_flush) (geometry_cache_flush) (switch_bsp_by_name deltacontrolroom_bsp3) (sleep 1) (c08_intra3_scene_01) (c08_intra3_scene_02) (c08_intra3_scene_03) (c08_intra3_scene_04) (c08_intra3_scene_05) (c08_intra3_scene_06) (rasterizer_bloom_override 0) ) X09 SCENE 01 -------------------------------------------------------- ; SOUND --------------------------------------------------------------- (script dormant x09_foley_1 (sleep 0) (sound_impulse_start sound\cinematics\08_deltacliffs\x09\foley\x09_01_fol none 1) (print "x09 foley 01 start") ) (script dormant x09_01_stop_sounds (sleep 383) (print "sound looping stop") (sound_looping_stop scenarios\solo\08b_deltacontrol\08b_music\08b_11) (sound_looping_stop scenarios\solo\08b_deltacontrol\08b_music\08b_12) (sound_looping_stop scenarios\solo\08b_deltacontrol\08b_music\08b_13) ) ; EFFECTS & LIGHTING -------------------------------------------------- (script dormant cinematic_lighting_x09_01 (cinematic_lighting_set_primary_light -4 206 0.454902 0.435294 0.352941) (cinematic_lighting_set_secondary_light -69 234 0.152941 0.152941 0.227451) (cinematic_lighting_set_ambient_light 0.0862745 0.0862745 0.0862745) (rasterizer_bloom_override 1) (rasterizer_bloom_override_threshold .4) (rasterizer_bloom_override_brightness .5) (object_uses_cinematic_lighting miranda 1) (object_uses_cinematic_lighting rotors_x09 1) ) (script dormant x09_fov_01 (time_code_reset) (sleep 289) (camera_set_field_of_view 35 0) (print "fov change: 60 -> 35 over 0 ticks") ) ; PROBLEM ACTORS ------------------------------------------------------ (script static void x09_problem_actors_01 (print "problem actors") (object_create_anew miranda) (object_create_anew rotors_x09) (object_cinematic_lod miranda true) (object_cinematic_lod rotors_x09 true) ) (script static void x09_problem_actors_02 (print "problem actors") (object_create_anew index_x09) (object_cinematic_lod index_x09 true) ) ; --------------------------------------------------------------------- (script dormant x09_miranda_emotion_01 (unit_set_emotional_state miranda angry .25 0) (sleep 186) (unit_set_emotional_state miranda shocked .5 30) (sleep 71) (unit_set_emotional_state miranda pain .5 30) ) (script static void x09_01_setup (object_destroy e13_rotors) (wake x09_miranda_emotion_01) (wake x09_01_stop_sounds) (wake x09_foley_1) (wake x09_fov_01) (wake cinematic_lighting_x09_01) ) ; --------------------------------------------------------------------- (script static void x09_scene_01 (fade_out 1 1 1 0) (camera_control on) (cinematic_start) (cinematic_outro_start) (set cinematic_letterbox_style 1) (camera_set_field_of_view 60 0) (cinematic_lightmap_shadow_enable) (x09_problem_actors_01) ; PREDICTION ->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> (x09_01_predict_stub) (sound_impulse_predict sound\cinematics\08_deltacliffs\x09\foley\x09_01_fol) (sleep prediction_offset) (sleep 30) (x09_01_setup) (camera_set_animation_relative objects\characters\cinematic_camera\x09\x09 "x09_01" none "anchor_flag_x09_01") (custom_animation_relative miranda objects\characters\miranda\x09\x09 "miranda_01" false anchor_x09_01) (scenery_animation_start_relative rotors_x09 scenarios\objects\solo\deltacontrolroom\control_rotors\x09\x09 "control_rotors_01" anchor_x09_01) (fade_in 1 1 1 15) ; PREDICTION ->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> (sleep (- (camera_time) prediction_offset)) (x09_02_predict_stub) (x09_problem_actors_02) (sleep (- (camera_time) sound_offset)) (sound_impulse_predict sound\cinematics\08_deltacliffs\x09\music\x09_02_mus) (sound_impulse_predict sound\cinematics\08_deltacliffs\x09\foley\x09_02_fol) (sleep (camera_time)) (object_destroy rotors_x09) ) X09 SCENE 02 -------------------------------------------------------- ; SOUND --------------------------------------------------------------- (script dormant x09_score_2 (sleep 92) (sound_impulse_start sound\cinematics\08_deltacliffs\x09\music\x09_02_mus none 1) (print "x09 score 01 start") ) (script dormant x09_foley_2 (sleep 0) (sound_impulse_start sound\cinematics\08_deltacliffs\x09\foley\x09_02_fol none 1) (print "x09 foley 02 start") ) (script dormant cinematic_lighting_x09_02 (cinematic_lighting_set_primary_light -18 166 0.454902 0.435294 0.352941) (cinematic_lighting_set_secondary_light -10 78 0.152941 0.152941 0.227451) (cinematic_lighting_set_ambient_light 0.0862745 0.0862745 0.0862745) (object_uses_cinematic_lighting index_x09 1) ) ; EFFECTS & LIGHTING -------------------------------------------------- (script dormant x09_dof_01 (cinematic_screen_effect_start 1) (cinematic_screen_effect_set_depth_of_field .5 1 1 0 0 0 0) (print "rack focus") (sleep 45) (cinematic_screen_effect_set_depth_of_field .5 1 0 .25 0 1 .25) (print "rack focus") ) ; --------------------------------------------------------------------- (script dormant lift_deactivate (sleep 93) (print "lift deactivate") (object_set_function_variable x09_lift effect 0 90) (sound_class_set_gain device 0 30) ) (script dormant x09_miranda_emotion_02 (unit_set_emotional_state miranda angry .25 0) (sleep 137) (unit_set_emotional_state miranda scared .5 90) ) (script static void x09_02_setup (wake x09_score_2) (wake x09_foley_2) (wake lift_deactivate) (wake x09_miranda_emotion_02) ; (wake x09_dof_01) (wake cinematic_lighting_x09_02) ) (script static void x09_scene_02 (camera_set_field_of_view 60 0) (x09_02_setup) (camera_set_animation_relative objects\characters\cinematic_camera\x09\x09 "x09_02" none "anchor_flag_x09_01") (custom_animation_relative miranda objects\characters\miranda\x09\x09 "miranda_02" false anchor_x09_01) (scenery_animation_start_relative index_x09 scenarios\objects\forerunner\industrial\index\index_full\x09\x09 "index_02" anchor_x09_01) ; PREDICTION ->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> (sleep (- (camera_time) prediction_offset)) (x09_03_predict_stub) (sleep (- (camera_time) sound_offset)) (sound_impulse_predict sound\cinematics\08_deltacliffs\x09\foley\x09_03_fol) (sleep (- (camera_time) 15)) (fade_out 1 1 1 15) (sleep 15) (cinematic_screen_effect_stop) ) X09 SCENE 03 -------------------------------------------------------- ; SOUND --------------------------------------------------------------- (script dormant x09_foley_3 (sleep 0) (sound_impulse_start sound\cinematics\08_deltacliffs\x09\foley\x09_03_fol none 1) (print "x09 foley 03 start") ) ; PROBLEM ACTORS ------------------------------------------------------ (script static void x09_problem_actors_04 (print "predict: problem actors") (object_create_anew halo) (object_create_anew matte_halo) (object_cinematic_lod halo true) (object_cinematic_lod matte_halo true) ) ; --------------------------------------------------------------------- (script static void x09_03_setup (object_create_anew x09_halo_bang) (wake x09_foley_3) ) (script static void x09_scene_03 (sleep 15) (x09_03_setup) (camera_set_animation_relative objects\characters\cinematic_camera\x09\x09 "x09_03" none "anchor_flag_x09_03") (sleep 10) (fade_in 1 1 1 15) ; PREDICTION ->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> (sleep (- (camera_time) prediction_offset)) (x09_04_predict_stub) (x09_problem_actors_04) (cinematic_screen_effect_start true) (sleep (- (camera_time) sound_offset)) (sound_impulse_predict sound\cinematics\08_deltacliffs\x09\foley\x09_04_fol) (sleep (- (camera_time) 5)) (fade_out 1 1 1 5) (sleep 5) ) X09 SCENE 04 -------------------------------------------------------- (script dormant x09_foley_4 (sleep 0) (sound_impulse_start sound\cinematics\08_deltacliffs\x09\foley\x09_04_fol none 1) (print "x09 foley 04 start") ) (script dormant cinematic_lighting_x09_04 (cinematic_lighting_set_primary_light 34 146 0.51 0.79 0.99) (cinematic_lighting_set_secondary_light 6 118 0.18 0.22 0.41) (cinematic_lighting_set_ambient_light 0.05 0.05 0.05) (rasterizer_bloom_override_threshold .75) (rasterizer_bloom_override_brightness .5) (object_uses_cinematic_lighting halo 1) ) ; --------------------------------------------------------------------- (script static void x09_04_setup ; (object_create_anew halo) (object_create_anew matte_substance) (object_create_anew matte_high_charity) ; (object_cinematic_lod halo true) (object_cinematic_lod matte_substance true) (object_cinematic_lod matte_high_charity true) (object_create_anew x09_halo_whimper) (wake x09_foley_4) (wake cinematic_lighting_x09_04) ) (script static void x09_scene_04_cleanup (object_destroy halo) (object_destroy_containing matte) ) (script static void x09_scene_04 (x09_04_setup) (camera_set_animation_relative objects\characters\cinematic_camera\x09\x09 "x09_04" none "anchor_flag_x09_02") (scenery_animation_start_relative halo scenarios\objects\forerunner\industrial\halo\x09\x09 "halo_04" anchor_x09_02) (scenery_animation_start_relative matte_halo objects\cinematics\matte_paintings\delta_halo_quarter\x09\x09 "delta_halo_quarter_04" anchor_x09_02) (scenery_animation_start_relative matte_substance objects\cinematics\matte_paintings\substance_space\x09\x09 "substance_space_04" anchor_x09_02) (scenery_animation_start_relative matte_high_charity objects\cinematics\matte_paintings\high_charity_exterior\x09\x09 "high_charity_exterior_04" anchor_x09_02) (sleep 10) (fade_in 1 1 1 5) ; PREDICTION ->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> (sleep (- (camera_time) prediction_offset)) (x09_05_predict_stub) (cinematic_screen_effect_start true) (sleep (- (camera_time) sound_offset)) (sound_impulse_predict sound\cinematics\08_deltacliffs\x09\foley\x09_05_fol) (sleep (- (camera_time) 90)) (fade_out 0 0 0 90) (sleep 90) (x09_scene_04_cleanup) ) X09 SCENE 05 -------------------------------------------------------- ; SOUND --------------------------------------------------------------- (script dormant x09_foley_5 (sleep 0) (sound_impulse_start sound\cinematics\08_deltacliffs\x09\foley\x09_05_fol none 1) (print "x09 foley 05 start") ) (script dormant x09_0010_mir (sleep 188) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\x09_0010_mir miranda 1) (cinematic_subtitle x09_0010_mir 1) ) (script dormant x09_0020_gsp (sleep 214) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\x09_0020_gsp monitor 1) (cinematic_subtitle x09_0020_gsp 1) ) (script dormant x09_0030_mir (sleep 251) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\x09_0030_mir miranda 1) (cinematic_subtitle x09_0030_mir 1) ) (script dormant x09_0040_gsp (sleep 280) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\x09_0040_gsp monitor 1) (cinematic_subtitle x09_0040_gsp 3) ) (script dormant x09_0050_mir (sleep 370) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\x09_0050_mir miranda 1) (cinematic_subtitle x09_0050_mir 2) ) (script dormant x09_0060_gsp (sleep 419) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\x09_0060_gsp monitor 1) (cinematic_subtitle x09_0060_gsp 2) ) (script dormant x09_0070_mir (sleep 469) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\x09_0070_mir miranda 1) (cinematic_subtitle x09_0070_mir 1) ) ; EFFECTS & LIGHTING -------------------------------------------------- (script dormant cinematic_lighting_x09_05 (cinematic_lighting_set_primary_light -18 220 0.286275 0.270588 0.219608) (cinematic_lighting_set_secondary_light 13 176 0.152941 0.152941 0.227451) (cinematic_lighting_set_ambient_light 0.0862745 0.0862745 0.0862745) (rasterizer_bloom_override_threshold .4) (rasterizer_bloom_override_brightness .5) (object_uses_cinematic_lighting miranda 1) (object_uses_cinematic_lighting johnson 1) (object_uses_cinematic_lighting monitor 1) (object_uses_cinematic_lighting index_x09 1) ) ; --------------------------------------------------------------------- (script dormant beacon_shuffle (sleep 140) (print "beacon 01 -> beacon 02") (object_destroy beacon_01) (object_create_anew beacon_02) ) (script dormant x09_miranda_emotion_05 (sleep 467) (unit_set_emotional_state miranda angry .5 30) ) (script static void x09_05_setup (object_destroy e13_rotors) (object_destroy x09_lift) (object_create_anew johnson) (object_create_anew monitor) (object_create_anew beacon_01) (object_cinematic_lod johnson true) (object_cinematic_lod monitor true) (unit_set_emotional_state miranda inquisitive 1 0) (wake x09_miranda_emotion_05) (wake x09_foley_5) (wake x09_0010_mir) (wake x09_0020_gsp) (wake x09_0030_mir) (wake x09_0040_gsp) (wake x09_0050_mir) (wake x09_0060_gsp) (wake x09_0070_mir) (wake beacon_shuffle) (wake cinematic_lighting_x09_05) (interpolator_start x09_fog 1 1) ) (script static void x09_scene_05 (x09_05_setup) (camera_set_animation_relative objects\characters\cinematic_camera\x09\x09 "x09_05" none "anchor_flag_x09_01") (custom_animation_relative miranda objects\characters\miranda\x09\x09 "miranda_05" false anchor_x09_01) (custom_animation_relative johnson objects\characters\marine\x09\x09 "johnson_05" false anchor_x09_01) (custom_animation_relative monitor objects\characters\monitor\x09\x09 "monitor_05" false anchor_x09_01) (scenery_animation_start_relative index_x09 scenarios\objects\forerunner\industrial\index\index_full\x09\x09 "index_05" anchor_x09_01) (sleep 15) (fade_in 0 0 0 90) ; PREDICTION ->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> (sleep (- (camera_time) prediction_offset)) (x09_06_predict_stub) (sleep (- (camera_time) sound_offset)) (sound_impulse_predict sound\cinematics\08_deltacliffs\x09\foley\x09_06_fol) (sleep (camera_time)) ) X09 SCENE 06 -------------------------------------------------------- ; SOUND --------------------------------------------------------------- (script dormant x09_foley_6 (sleep 0) (sound_impulse_start sound\cinematics\08_deltacliffs\x09\foley\x09_06_fol none 1) (print "x09 foley 06 start") ) (script dormant x09_0080_gsp (sleep 0) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\x09_0080_gsp monitor 1) (cinematic_subtitle x09_0080_gsp 10) ) (script dormant x09_0090_mir (sleep 310) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\x09_0090_mir miranda 1) (cinematic_subtitle x09_0090_mir 2) ; (unit_set_emotional_state miranda repulsed .25 0) ; (print "miranda - repulsed .25 0") ) (script dormant x09_0100_gsp (sleep 386) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\x09_0100_gsp monitor 1) (cinematic_subtitle x09_0100_gsp 1) ) (script dormant x09_0110_jon (sleep 430) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\x09_0110_jon johnson 1) (cinematic_subtitle x09_0110_jon 2) ) (script dormant x09_0120_mir (sleep 494) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\x09_0120_mir miranda 1) (cinematic_subtitle x09_0120_mir 4) (sleep 30) ( unit_set_emotional_state miranda pain .25 15 ) ( print " miranda - pain .25 15 " ) ) (script dormant x09_0130_gsp (sleep 675) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\x09_0130_gsp monitor 1) (cinematic_subtitle x09_0130_gsp 2) ) (script dormant x09_0140_der (sleep 742) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\x09_0140_der dervish 1) (cinematic_subtitle x09_0140_der 3) ) ; EFFECTS & LIGHTING -------------------------------------------------- (script dormant cinematic_lighting_x09_06 (cinematic_lighting_set_primary_light -18 220 0.286275 0.270588 0.219608) (cinematic_lighting_set_secondary_light 13 176 0.152941 0.152941 0.227451) (cinematic_lighting_set_ambient_light 0.0862745 0.0862745 0.0862745) (object_uses_cinematic_lighting dervish 1) ) ; --------------------------------------------------------------------- (script dormant x09_miranda_emotion_06a (sleep 310) (unit_set_emotional_state miranda scared .5 60) ) (script dormant x09_miranda_emotion_06b (sleep 525) (unit_set_emotional_state miranda pain .25 90) ) (script dormant x09_miranda_emotion_06c (sleep 776) (unit_set_emotional_state miranda shocked .25 30) ) (script dormant x09_johnson_emotion_06a (sleep 440) (unit_set_emotional_state johnson angry .75 60) (sleep 54) (unit_set_emotional_state johnson shocked .25 30) ) (script dormant x09_johnson_emotion_06b (sleep 784) (unit_set_emotional_state johnson shocked .25 30) ) (script static void x09_06_setup (object_destroy beacon_02) (object_create_anew beacon_03) (device_set_position beacon_03 1) (object_create_anew dervish) (object_cinematic_lod dervish true) (unit_set_emotional_state miranda angry .25 0) (unit_set_emotional_state johnson angry .25 0) (wake x09_miranda_emotion_06a) (wake x09_miranda_emotion_06b) (wake x09_miranda_emotion_06c) (wake x09_johnson_emotion_06a) (wake x09_johnson_emotion_06b) (wake x09_foley_6) (wake x09_0080_gsp) (wake x09_0090_mir) (wake x09_0100_gsp) (wake x09_0110_jon) (wake x09_0120_mir) (wake x09_0130_gsp) (wake x09_0140_der) ) (script static void x09_scene_06_cleanup (object_destroy dervish) (object_destroy miranda) (object_destroy johnson) (object_destroy monitor) (object_destroy index_x09) ) (script static void x09_scene_06 (x09_06_setup) (camera_set_animation_relative objects\characters\cinematic_camera\x09\x09 "x09_06" none "anchor_flag_x09_01") (custom_animation_relative dervish objects\characters\dervish\x09\x09 "dervish_06" false anchor_x09_01) (custom_animation_relative miranda objects\characters\miranda\x09\x09 "miranda_06" false anchor_x09_01) (custom_animation_relative johnson objects\characters\marine\x09\x09 "johnson_06" false anchor_x09_01) (custom_animation_relative monitor objects\characters\monitor\x09\x09 "monitor_06" false anchor_x09_01) (scenery_animation_start_relative index_x09 scenarios\objects\forerunner\industrial\index\index_full\x09\x09 "index_06" anchor_x09_01) ; PREDICTION ->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> (sleep (- (camera_time) prediction_offset)) (x09_07_predict_stub) (sleep (- (camera_time) sound_offset)) (sound_impulse_predict sound\cinematics\08_deltacliffs\x09\foley\x09_07_fol) (sleep (- (camera_time) 5)) (fade_out 0 0 0 5) (sleep 5) (x09_scene_06_cleanup) ) X09 SCENE 07 -------------------------------------------------------- ; SOUND --------------------------------------------------------------- (script dormant x09_foley_7 (sleep 0) (sound_impulse_start sound\cinematics\08_deltacliffs\x09\foley\x09_07_fol none 1) (print "x09 foley 07 start") ) (script dormant x09_0150_to1 (sleep 100) (sound_impulse_start_effect sound\dialog\levels\08_controlroom\cinematic\x09_0150_to1 none 1 radio_default_in) (cinematic_subtitle x09_0150_to1 3) ) ; EFFECTS & LIGHTING -------------------------------------------------- (script dormant cinematic_lighting_x09_07 (cinematic_lighting_set_primary_light 16 -32 .8 .6 .4) (cinematic_lighting_set_secondary_light 20 180 .3 .3 .5) (cinematic_lighting_set_ambient_light .2 .2 .2) (object_uses_cinematic_lighting forerunner_ship 1) ) ; PROBLEM ACTORS ------------------------------------------------------ (script static void x09_problem_actors_08 (print "problem actors") (object_create_anew chief) (object_create_anew x09_alcove) (object_create_anew bloom_quad) (object_cinematic_lod chief true) (object_cinematic_lod x09_alcove true) ) ; --------------------------------------------------------------------- (script static void x09_07_setup (object_create_anew slipspace) (object_create_anew_containing earth_battle) (object_create_anew forerunner_ship) (object_create_anew matte_earth) (object_create_anew matte_moon) (object_cinematic_lod forerunner_ship true) (object_cinematic_lod matte_earth true) (object_cinematic_lod matte_moon true) (wake x09_foley_7) (wake x09_0150_to1) (wake cinematic_lighting_x09_07) ) (script static void x09_scene_07_cleanup (object_destroy slipspace) (object_destroy_containing earth_battle) (object_destroy forerunner_ship) (object_destroy_containing matte) ) (script static void x09_scene_07 (sleep 60) (x09_07_setup) (camera_set_animation_relative objects\characters\cinematic_camera\x09\x09 "x09_07" none "anchor_flag_x09_02") (scenery_animation_start_relative forerunner_ship objects\cinematics\forerunner\forerunner_ship\x09\x09 "forerunner_ship_07" anchor_x09_02) (scenery_animation_start_relative cairo scenarios\objects\solo\spacestation\ss_prop\x09\x09 "ss_prop_07" anchor_x09_02) (scenery_animation_start_relative matte_earth objects\cinematics\matte_paintings\earth_space\x09\x09 "earth_space_07" anchor_x09_02) (scenery_animation_start_relative matte_moon objects\cinematics\matte_paintings\moon\x09\x09 "moon_07" anchor_x09_02) (fade_in 0 0 0 5) ; PREDICTION ->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> (sleep (- (camera_time) prediction_offset)) (x09_08_predict_stub) (x09_problem_actors_08) (sleep (- (camera_time) sound_offset)) (sound_impulse_predict sound\cinematics\08_deltacliffs\x09\music\x09_08_mus) (sound_impulse_predict sound\cinematics\08_deltacliffs\x09\foley\x09_03_fol) (sleep (- (camera_time) 5)) (fade_out 1 1 1 5) (sleep 5) (x09_scene_07_cleanup) ) X09 SCENE 08 -------------------------------------------------------- ; SOUND --------------------------------------------------------------- (script dormant x09_score_8 (sleep 338) (sound_impulse_start sound\cinematics\08_deltacliffs\x09\music\x09_08_mus none 1) (print "x09 score 08 start") ) (script dormant x09_foley_8 (sleep 0) (sound_impulse_start sound\cinematics\08_deltacliffs\x09\foley\x09_08_fol none 1) (print "x09 foley 08 start") ) (script dormant x09_0160_lhd (sleep 0) (sound_impulse_start_effect sound\dialog\levels\08_controlroom\cinematic\x09_0160_lhd none 1 radio_default_loop) (cinematic_subtitle x09_0160_lhd 2) ) (script dormant x09_0180_mas (sleep 69) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\x09_0180_mas chief 1) (cinematic_subtitle x09_0180_mas 2) ) (script dormant x09_0190_mas (sleep 132) (sound_impulse_start_effect sound\dialog\levels\08_controlroom\cinematic\x09_0190_mas none 1 radio_default_out) (cinematic_subtitle x09_0190_mas 2) ) (script dormant x09_0200_lhd (sleep 183) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\x09_0200_lhd hood 1) (cinematic_subtitle x09_0200_lhd 1) ) (script dormant x09_0210_lhd (sleep 232) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\x09_0210_lhd hood 1) (cinematic_subtitle x09_0210_lhd 3) ) (script dormant x09_0220_mas (sleep 342) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\x09_0220_mas chief 1) (cinematic_subtitle x09_0220_mas 3) ) ; EFFECTS & LIGHTING -------------------------------------------------- (script dormant cinematic_light_x09_chief_01 (print "light chief 01") (cinematic_lighting_set_primary_light -20 278 0.388235 0.427451 0.494118) (cinematic_lighting_set_secondary_light 42 224 0.0431373 0.0431373 0.0666667) (cinematic_lighting_set_ambient_light 0 0 0) (rasterizer_bloom_override_threshold .3) (rasterizer_bloom_override_brightness .5) (object_uses_cinematic_lighting chief 1) (object_uses_cinematic_lighting hood 1) (object_uses_cinematic_lighting cairo_bridge 1) (object_uses_cinematic_lighting x09_alcove 1) ) (script dormant cinematic_light_x09_hood_01 (sleep 124) (print "light hood 01") (cinematic_lighting_set_primary_light 0 94 0.47451 0.443137 0.333333) (cinematic_lighting_set_secondary_light 0 320 0.184314 0.176471 0.266667) (cinematic_lighting_set_ambient_light 0 0 0) (rasterizer_bloom_override_threshold .75) (rasterizer_bloom_override_brightness .5) ) (script dormant final_explosion (time_code_reset) (sleep 135) (object_create_anew_containing blast_base) (effect_new_on_object_marker effects\cinematics\01_outro\covenant_tiny_explosion blast_base "marker") (sleep 110) (effect_new_on_object_marker effects\cinematics\01_outro\covenant_tiny_explosion blast_base2 "marker") ) (script dormant cinematic_light_x09_chief_02 (sleep 277) (print "light chief 02") (cinematic_lighting_set_primary_light -20 278 0.388235 0.427451 0.494118) (cinematic_lighting_set_secondary_light 42 224 0.0431373 0.0431373 0.0666667) (cinematic_lighting_set_ambient_light 0 0 0) (rasterizer_bloom_override_threshold .3) (rasterizer_bloom_override_brightness .5) ) ; --------------------------------------------------------------------- (script dormant x09_hood_emotion_08 (sleep 43) (unit_set_emotional_state hood shocked .5 30) (sleep 45) (unit_set_emotional_state hood happy .25 90) ) (script dormant shake_chief (print "shake") (player_effect_set_max_rotation 0 1 1) (player_effect_start .75 0) (sleep 15) (player_effect_stop 3) ) (script static void x09_08_setup (object_create_anew hood) (object_create_anew cairo_bridge) (object_cinematic_lod hood true) (object_cinematic_lod cairo_bridge true) (object_create_anew_containing cairo_effect) (unit_set_emotional_state hood angry .5 0) (wake x09_hood_emotion_08) (wake x09_score_8) (wake x09_foley_8) (wake x09_0160_lhd) (wake x09_0180_mas) (wake x09_0190_mas) (wake x09_0200_lhd) (wake x09_0210_lhd) (wake x09_0220_mas) (wake shake_chief) (wake final_explosion) (wake cinematic_light_x09_chief_01) (wake cinematic_light_x09_hood_01) (wake cinematic_light_x09_chief_02) ) (script static void x09_scene_08_cleanup (object_destroy chief) (object_destroy hood) (object_destroy cairo_bridge) (object_destroy x09_alcove) (object_destroy bloom_quad) (object_destroy_containing blast_base) ) (script static void x09_scene_08 (x09_08_setup) (camera_set_animation_relative objects\characters\cinematic_camera\x09\x09 "x09_08" none "anchor_flag_x09_02") (custom_animation_relative chief objects\characters\masterchief\x09\x09 "chief_08" false anchor_x09_02) (custom_animation_relative hood objects\characters\lord_hood\x09\x09 "hood_08" false anchor_x09_02) (scenery_animation_start_relative cairo_bridge objects\cinematics\human\cairo_bridge\x09\x09 "cairo_bridge_08" anchor_x09_02) (scenery_animation_start_relative x09_alcove objects\cinematics\forerunner\forerunner_ship_alcove\x09\x09 "alcove_08" anchor_x09_02) (scenery_animation_start_relative bloom_quad scenarios\objects\special\bloom_quad\x09\x09 "bloom_quad_08" anchor_x09_02) ; safety white (sleep 10) (fade_in 1 1 1 5) (sleep (- (camera_time) 5)) (fade_out 0 0 0 5) (sleep 5) (sleep 401) (x09_scene_08_cleanup) (rasterizer_bloom_override 0) ) X10 SCENE 01 -------------------------------------------------------- ; SOUND --------------------------------------------------------------- (script dormant x10_score_1 (sleep 0) (sound_impulse_start sound\cinematics\08_deltacliffs\x10\music\x10_01_mus none 1) (print "x10 score 01 start") ) (script dormant x10_foley_1 (sleep 0) (sound_impulse_start sound\cinematics\08_deltacliffs\x10\foley\x10_01_fol none 1) (print "x10 foley 01 start") ) (script dormant x10_0010_grv (sleep 496) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\x10_0010_grv none 1) (cinematic_subtitle x10_0010_grv 6) ) ; EFFECTS & LIGHTING -------------------------------------------------- (script dormant cinematic_lighting_x10_01 (cinematic_lighting_set_primary_light 51 28 0.380392 0.384314 0.341176) (cinematic_lighting_set_secondary_light -53 202 0.0588235 0.356863 0.356863) (cinematic_lighting_set_ambient_light 0.0901961 0.117647 0.0823529) (rasterizer_bloom_override 1) (rasterizer_bloom_override_threshold .3) (rasterizer_bloom_override_brightness .5) (object_uses_cinematic_lighting tentacle_01 1) (object_uses_cinematic_lighting tentacle_02 1) (object_uses_cinematic_lighting tentacle_03 1) (object_uses_cinematic_lighting tentacle_04 1) ) ; PREDICTION ---------------------------------------------------------- (script static void x10_problem_actors_01 (print "problem actors") (object_create_anew spore_01) (object_create_anew spore_02) (object_create_anew spore_03) (object_cinematic_lod spore_01 true) (object_cinematic_lod spore_02 true) (object_cinematic_lod spore_03 true) ) ; --------------------------------------------------------------------- (script static void x10_scene_01_setup (object_create_anew x09_chamber_door) (object_create_anew tentacle_01) (object_create_anew tentacle_02) (object_create_anew tentacle_03) (object_create_anew tentacle_04) (object_cinematic_lod x09_chamber_door true) (object_cinematic_lod tentacle_01 true) (object_cinematic_lod tentacle_02 true) (object_cinematic_lod tentacle_03 true) (object_cinematic_lod tentacle_04 true) (object_cinematic_visibility tentacle_01 true) (object_cinematic_visibility tentacle_02 true) (object_cinematic_visibility tentacle_03 true) (object_cinematic_visibility tentacle_04 true) (wake x10_score_1) (wake x10_foley_1) (wake x10_0010_grv) (wake cinematic_lighting_x10_01) ) (script static void x10_scene_01_cleanup (object_destroy x09_chamber_door) (object_destroy_containing spore) ) (script static void x10_scene_01 (fade_out 0 0 0 0) (camera_control on) (cinematic_start) (cinematic_outro_start) (set cinematic_letterbox_style 1) (camera_set_field_of_view 60 0) (weather_start 0) (weather_change_intensity 0 1) (x10_problem_actors_01) ; PREDICTION ->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> (x10_01_predict_stub) (sound_impulse_predict sound\cinematics\08_deltacliffs\x10\music\x10_01_mus) (sound_impulse_predict sound\cinematics\08_deltacliffs\x10\foley\x10_01_fol) (sleep prediction_offset) (x10_scene_01_setup) (camera_set_animation_relative objects\characters\cinematic_camera\x10\x10 "x10_01" none "anchor_flag_x10") (scenery_animation_start_relative x09_chamber_door scenarios\objects\solo\highcharity\high_door_grand\x10\x10 "high_door_grand_01" anchor_x10) (scenery_animation_start_relative spore_01 objects\cinematics\flood\flood_spore\x10\x10 "spore01_01" anchor_x10) (scenery_animation_start_relative spore_02 objects\cinematics\flood\flood_spore\x10\x10 "spore02_01" anchor_x10) (scenery_animation_start_relative spore_03 objects\cinematics\flood\flood_spore\x10\x10 "spore03_01" anchor_x10) (scenery_animation_start_relative tentacle_01 objects\characters\gravemind\tentacle_capture\x10\x10 "tentacle01_01" anchor_x10) (scenery_animation_start_relative tentacle_02 objects\characters\gravemind\tentacle_capture\x10\x10 "tentacle02_01" anchor_x10) (scenery_animation_start_relative tentacle_03 objects\characters\gravemind\tentacle_capture\x10\x10 "tentacle03_01" anchor_x10) (fade_in 0 0 0 60) ; PREDICTION ->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> (sleep (- (camera_time) prediction_offset)) (x10_02_predict_stub) (cinematic_screen_effect_start true) (sleep (- (camera_time) 1)) (cinematic_screen_effect_set_crossfade 2) (sleep 1) (x10_scene_01_cleanup) ) X10 SCENE 02 -------------------------------------------------------- ; SOUND --------------------------------------------------------------- (script dormant x10_score_2 (sleep 553) (sound_looping_start sound\cinematics\08_deltacliffs\x10\music\x10_02_mus none 1) (print "x10 score 02 start") ) (script dormant x10_0020_grv (sleep 0) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\x10_0020_grv none 1) (cinematic_subtitle x10_0020_grv 8) ) (script dormant x10_0030_grv (sleep 260) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\x10_0030_grv none 1) (cinematic_subtitle x10_0030_grv 5) ) (script dormant x10_0040_cor (sleep 496) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\x10_0040_cor cortana 1) (cinematic_subtitle x10_0040_cor 1) ) (script dormant x10_0041_cor (sleep 520) (unit_set_emotional_state cortana pain .25 60) (print "cortana - pain .25 60") (sleep 30) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\x10_0041_cor cortana 1) (cinematic_subtitle x10_0041_cor 1) ) ; EFFECTS & LIGHTING -------------------------------------------------- (script dormant cinematic_lighting_x10_02 (cinematic_lighting_set_primary_light 51 28 0.380392 0.384314 0.341176) (cinematic_lighting_set_secondary_light -53 202 0.0588235 0.356863 0.356863) (cinematic_lighting_set_ambient_light 0.0901961 0.117647 0.0823529) (object_uses_cinematic_lighting cortana 1) ) ; --------------------------------------------------------------------- (script dormant effect_cortana_appear (sleep 410) (print "cortana appears") (effect_new_on_object_marker effects\objects\characters\cortana\cortana_on_off_65 cortana_stand "marker") ) (script static void x10_scene_02_setup (object_create_anew cortana) (object_cinematic_lod cortana true) (object_create_anew cortana_stand) (unit_set_emotional_state cortana repulsed .5 0) (print "cortana - repulsed .5 0") (wake x10_score_2) (wake x10_0020_grv) (wake x10_0030_grv) (wake x10_0040_cor) (wake x10_0041_cor) (wake effect_cortana_appear) (wake cinematic_lighting_x10_02) (cinematic_set_near_clip_distance .05) (print "setting near clip distance to .05") ) (script static void x10_scene_02_cleanup (object_destroy_containing cortana) (object_destroy_containing tentacle) ) (script static void x10_scene_02 (time_code_reset) (x10_scene_02_setup) (camera_set_animation_relative objects\characters\cinematic_camera\x10\x10 "x10_02" none "anchor_flag_x10") (custom_animation_relative cortana objects\characters\cortana\x10\x10 "cortana_02" false anchor_x10) (scenery_animation_start_relative tentacle_01 objects\characters\gravemind\tentacle_capture\x10\x10 "tentacle01_02" anchor_x10) (scenery_animation_start_relative tentacle_02 objects\characters\gravemind\tentacle_capture\x10\x10 "tentacle02_02" anchor_x10) (scenery_animation_start_relative tentacle_03 objects\characters\gravemind\tentacle_capture\x10\x10 "tentacle03_02" anchor_x10) (scenery_animation_start_relative tentacle_04 objects\characters\gravemind\tentacle_capture\x10\x10 "tentacle04_02" anchor_x10) (sleep (- (camera_time) 5)) (fade_out 0 0 0 5) (sleep 5) (cinematic_set_near_clip_distance .06) (print "setting near clip distance to .06") (sleep 328) ) (script static void x10 ; (texture_cache_flush) ; (geometry_cache_flush) (switch_bsp_by_name high_0) (sleep 1) (x10_scene_01) (x10_scene_02) ) ; X09 MASTER SCRIPT =================================================== ; ===================================================================== (script static void x09 (texture_cache_flush) (geometry_cache_flush) (switch_bsp_by_name deltacontrolroom_bsp4) (sleep 1) (sound_class_set_gain amb 0 15) (x09_scene_01) (x09_scene_02) (switch_bsp_by_name deltacontrolroom_bsp0) (sleep 1) (x09_scene_03) (x09_scene_04) (switch_bsp_by_name deltacontrolroom_bsp4) (sleep 1) (x09_scene_05) (x09_scene_06) (switch_bsp_by_name deltacontrolroom_bsp0) (sleep 1) (x09_scene_07) (x09_scene_08) (sleep 30) (print "30 ticks of black for marty") (cinematic_show_letterbox 0) (play_credits) ; (sleep (bink_time)) (sleep_until (bink_done) 1) ; safety black (sleep 30) (x10) (sleep 30) (print "30 ticks of black for marty") (game_won) )
null
https://raw.githubusercontent.com/Nibre/BlamScript-Research/dd17538dcbdc78f391effb341846fbaf9a1f8643/h2v/08b_deltacontrol/08b_deltacontrol_cinematics.lisp
lisp
===================================================================== * | Between the desire | And the spasm | Between the potency | And the existence | Between the essence | And the descent | Falls the Shadow... | | ...This is the way the world ends | Not with a bang but a whimper. *; C08_INTRA1 SCENE 04 ------------------------------------------------- SOUND --------------------------------------------------------------- EFFECTS & LIGHTING -------------------------------------------------- PREDICTION ---------------------------------------------------------- --------------------------------------------------------------------- PREDICTION ->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> C08_INTRA2 SCENE 01 ------------------------------------------------- SOUND --------------------------------------------------------------- EFFECTS & LIGHTING -------------------------------------------------- PROBLEM ACTORS ------------------------------------------------------ --------------------------------------------------------------------- PREDICTION ->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> safety white PREDICTION ->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> C08_INTRA2 SCENE 02 ------------------------------------------------- SOUND --------------------------------------------------------------- EFFECTS & LIGHTING -------------------------------------------------- --------------------------------------------------------------------- C08_INTRA2 MASTER SCRIPT ============================================ ===================================================================== C08_INTRA3 SCENE 01 ------------------------------------------------- SOUND --------------------------------------------------------------- PROBLEM ACTORS ------------------------------------------------------ --------------------------------------------------------------------- (object_create_anew hammer) (object_cinematic_lod hammer true) PREDICTION ->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> PREDICTION ->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> C08_INTRA3 SCENE 02 ------------------------------------------------- SOUND --------------------------------------------------------------- --------------------------------------------------------------------- PREDICTION ->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> C08_INTRA3 SCENE 03 ------------------------------------------------- SOUND --------------------------------------------------------------- EFFECTS & LIGHTING -------------------------------------------------- --------------------------------------------------------------------- PREDICTION ->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> C08_INTRA3 SCENE 04 ------------------------------------------------- SOUND --------------------------------------------------------------- --------------------------------------------------------------------- PREDICTION ->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> C08_INTRA3 SCENE 05 ------------------------------------------------- SOUND --------------------------------------------------------------- --------------------------------------------------------------------- PREDICTION ->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> C08_INTRA3 SCENE 06 ------------------------------------------------- C08_INTRA3 MASTER SCRIPT ============================================ ===================================================================== SOUND --------------------------------------------------------------- EFFECTS & LIGHTING -------------------------------------------------- PROBLEM ACTORS ------------------------------------------------------ --------------------------------------------------------------------- --------------------------------------------------------------------- PREDICTION ->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> PREDICTION ->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> SOUND --------------------------------------------------------------- EFFECTS & LIGHTING -------------------------------------------------- --------------------------------------------------------------------- (wake x09_dof_01) PREDICTION ->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> SOUND --------------------------------------------------------------- PROBLEM ACTORS ------------------------------------------------------ --------------------------------------------------------------------- PREDICTION ->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> --------------------------------------------------------------------- (object_create_anew halo) (object_cinematic_lod halo true) PREDICTION ->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> SOUND --------------------------------------------------------------- EFFECTS & LIGHTING -------------------------------------------------- --------------------------------------------------------------------- PREDICTION ->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> SOUND --------------------------------------------------------------- (unit_set_emotional_state miranda repulsed .25 0) (print "miranda - repulsed .25 0") EFFECTS & LIGHTING -------------------------------------------------- --------------------------------------------------------------------- PREDICTION ->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> SOUND --------------------------------------------------------------- EFFECTS & LIGHTING -------------------------------------------------- PROBLEM ACTORS ------------------------------------------------------ --------------------------------------------------------------------- PREDICTION ->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> SOUND --------------------------------------------------------------- EFFECTS & LIGHTING -------------------------------------------------- --------------------------------------------------------------------- safety white SOUND --------------------------------------------------------------- EFFECTS & LIGHTING -------------------------------------------------- PREDICTION ---------------------------------------------------------- --------------------------------------------------------------------- PREDICTION ->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> PREDICTION ->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> SOUND --------------------------------------------------------------- EFFECTS & LIGHTING -------------------------------------------------- --------------------------------------------------------------------- (texture_cache_flush) (geometry_cache_flush) X09 MASTER SCRIPT =================================================== ===================================================================== (sleep (bink_time)) safety black
CINEMATICS FOR LEVEL 08B , " DELTA CONTROL " = = = = = = = = = = = = = = = = = = = = = = = = = = = GLOBALS & STUBS = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = (global short sound_offset 15) (global short prediction_offset 45) (script stub void 08_intra1_04_predict_stub (print "predict 04")) (script stub void 08_intra2_01_predict_stub (print "predict 01")) (script stub void 08_intra2_02_predict_stub (print "predict 02")) (script stub void 08_intra3_01_predict_stub (print "predict 01")) (script stub void 08_intra3_02_predict_stub (print "predict 02")) (script stub void 08_intra3_03_predict_stub (print "predict 03")) (script stub void 08_intra3_04_predict_stub (print "predict 04")) (script stub void 08_intra3_05_predict_stub (print "predict 05")) (script stub void 08_intra3_06_predict_stub (print "predict 06")) (script stub void x09_01_predict_stub (print "predict 01")) (script stub void x09_02_predict_stub (print "predict 02")) (script stub void x09_03_predict_stub (print "predict 03")) (script stub void x09_04_predict_stub (print "predict 04")) (script stub void x09_05_predict_stub (print "predict 05")) (script stub void x09_06_predict_stub (print "predict 06")) (script stub void x09_07_predict_stub (print "predict 07")) (script stub void x09_08_predict_stub (print "predict 08")) (script stub void x10_01_predict_stub (print "predict 01")) (script stub void x10_02_predict_stub (print "predict 02")) (script dormant c08_intra1_score_04 (sleep 0) (sound_impulse_start sound\cinematics\08_deltacliffs\c08_intra1\music\c08_intra1_04_mus none 1) (print "c08_intra1 score 04 start") ) (script dormant c08_intra1_foley_04 (sleep 0) (sound_impulse_start sound\cinematics\08_deltacliffs\c08_intra1\foley\c08_intra1_04_fol none 1) (print "c08_intra1 foley 04 start") ) (script dormant c08_2050_der (sleep 60) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_2050_der dervish_02 1) (cinematic_subtitle c08_2050_der 1) ) (script dormant c08_2060_soc (sleep 92) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_2060_soc commander 1) (cinematic_subtitle c08_2060_soc 6) ) (script dormant c08_2070_grv (sleep 273) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_2070_grv none 1) (cinematic_subtitle c08_2070_grv 5) (cinematic_lightmap_shadow_disable) ) (script dormant c08_2080_der (sleep 425) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_2080_der dervish_02 1) (cinematic_subtitle c08_2080_der 2) ) (script dormant c08_2090_soc (sleep 473) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_2090_soc commander 1) (cinematic_subtitle c08_2090_soc 1) ) (script dormant c08_2100_soc (sleep 512) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_2100_soc commander 1) (cinematic_subtitle c08_2100_soc 2) ) (script dormant c04_intra1_fov_04 (sleep 511) (print "fov change: 80 -> 60 over 0 ticks") (camera_set_field_of_view 60 0) ) (script dormant c04_intra1_dof_04 (sleep 427) (cinematic_screen_effect_start 1) (cinematic_screen_effect_set_depth_of_field 1.17 .5 .5 0 0 0 0) (print "rack focus") (sleep 84) (cinematic_screen_effect_set_depth_of_field .5 .5 .5 0 0 0 0) (print "rack focus") (sleep 100) (cinematic_screen_effect_set_depth_of_field .5 .5 0 0 0 .5 .5) (print "rack focus") ) (script dormant cinematic_lighting_intra1_04 (cinematic_lighting_set_primary_light 40 134 0.321569 0.321569 0.290196) (cinematic_lighting_set_secondary_light 8 274 0.301961 0.290196 0.45098) (cinematic_lighting_set_ambient_light 0.121569 0.121569 0.0705882) (object_uses_cinematic_lighting dervish_02 1) (object_uses_cinematic_lighting commander 1) (object_uses_cinematic_lighting wraith_01 1) ) (script static void c08_intra1_04_problem_actors (print "problem actors") (object_create_anew dervish_02) (object_create_anew commander) (object_create_anew wraith_01) (cinematic_clone_players_weapon dervish_02 "right_hand_elite" "") (object_cinematic_lod dervish_02 true) (object_cinematic_lod commander true) (object_cinematic_lod wraith_01 true) ) (script static void c08_intra1_04_setup (wake c08_intra1_score_04) (wake c08_intra1_foley_04) (wake c08_2050_der) (wake c08_2060_soc) (wake c08_2070_grv) (wake c08_2080_der) (wake c08_2090_soc) (wake c08_2100_soc) (wake c04_intra1_fov_04) (wake c04_intra1_dof_04) (wake cinematic_lighting_intra1_04) ) (script static void c08_intra1_04_cleanup (object_destroy dervish_02) (object_destroy commander) (object_destroy wraith_01) ) (script static void c08_intra1 (texture_cache_flush) (geometry_cache_flush) (sound_class_set_gain vehicle 0 0) (fade_out 0 0 0 0) (camera_control on) (cinematic_start) (set cinematic_letterbox_style 1) (camera_set_field_of_view 60 0) (cinematic_lightmap_shadow_enable) (c08_intra1_04_problem_actors) (08_intra1_04_predict_stub) (sound_impulse_predict sound\cinematics\08_deltacliffs\c08_intra1\music\c08_intra1_04_mus) (sound_impulse_predict sound\cinematics\08_deltacliffs\c08_intra1\foley\c08_intra1_04_fol) (sleep prediction_offset) (c08_intra1_04_setup) (camera_set_animation_relative objects\characters\cinematic_camera\08_intra1\08_intra1 "08_intra1_04" none "anchor_flag_intra1") (custom_animation_relative dervish_02 objects\characters\dervish\08_intra1\08_intra1 "dervish_04" false anchor_intra1) (custom_animation_relative commander objects\characters\elite\08_intra1\08_intra1 "commander_04" false anchor_intra1) (custom_animation_relative wraith_01 objects\vehicles\wraith\08_intra1\08_intra1 "wraith_04" false anchor_intra1) (print "cache block") (sleep 1) (cache_block_for_one_frame) (fade_in 0 0 0 30) (sleep (- (camera_time) 15)) (fade_out 1 1 1 15) (sleep 15) (c08_intra1_04_cleanup) (cinematic_screen_effect_stop) (sleep 30) (sound_class_set_gain vehicle 1 1) ) (script dormant c08_intra2_foley_01 (sleep 0) (sound_impulse_start sound\cinematics\08_deltacliffs\c08_intra2\foley\c08_intra2_01_fol none 1) (print "c08_intra2 foley 01 start") ) (script dormant c08_3010_jon (sleep 100) (sound_impulse_start_effect sound\dialog\levels\08_controlroom\cinematic\c08_3010_jon johnson_02 1 radio_covy_in) (cinematic_subtitle c08_3010_jon 3) ) (script dormant c08_3020_jon (sleep 203) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_3020_jon johnson_02 1) (cinematic_subtitle c08_3020_jon 3) ) (script dormant c08_3030_jon (sleep 316) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_3030_jon johnson_02 1) (cinematic_subtitle c08_3030_jon 2) ) (script dormant c08_3040_der (sleep 359) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_3040_der dervish_02 1) (cinematic_subtitle c08_3040_der 3) ) (script dormant intra2_texture_cam_01 (object_create_anew texture_camera) (texture_camera_set_object_marker texture_camera marker 35) (scenery_animation_start_relative texture_camera objects\cinematics\texture_camera\08_intra2\08_intra2 "texture_camera_01" anchor_intra2) ) (script dormant cinematic_lighting_intra2 (cinematic_lighting_set_primary_light 33 0 0.258824 0.278431 0.34902) (cinematic_lighting_set_secondary_light -37 228 0.109804 0.419608 0.611765) (cinematic_lighting_set_ambient_light 0.121569 0.121569 0.0705882) (object_uses_cinematic_lighting dervish_02 1) (object_uses_cinematic_lighting johnson_02 1) (object_uses_cinematic_lighting scarab_01 1) ) (script static void c08_intra2_problem_actors (print "problem actors") (object_create_anew dervish_02) (object_cinematic_lod dervish_02 true) (cinematic_clone_players_weapon dervish_02 "right_hand_elite" "") ) (script dormant scarab_shake (sleep 45) (print "shake") (player_effect_set_max_rotation 0 1 1) (player_effect_start .25 2) (sleep 240) (player_effect_stop 2) ) (script static void c08_intra2_01_setup (object_destroy scarab) (object_create_anew johnson_02) (object_create_anew scarab_01) (object_create_anew scarab_screen) (objects_attach scarab_01 "holo_scarab_full" scarab_screen "") (object_cinematic_lod johnson_02 true) (object_cinematic_lod scarab_01 true) (unit_set_emotional_state johnson_02 angry .25 0) (wake c08_intra2_foley_01) (wake c08_3010_jon) (wake c08_3020_jon) (wake c08_3030_jon) (wake c08_3040_der) ( wake ) (wake scarab_shake) (wake intra2_texture_cam_01) (wake cinematic_lighting_intra2) ) (script static void c08_intra2_scene_01 (fade_out 1 1 1 0) (camera_control on) (cinematic_start) (set cinematic_letterbox_style 1) (camera_set_field_of_view 60 0) (cinematic_lightmap_shadow_enable) (c08_intra2_problem_actors) (08_intra2_01_predict_stub) (sound_impulse_predict sound\cinematics\08_deltacliffs\c08_intra2\foley\c08_intra2_01_fol) (sleep prediction_offset) (sleep 45) (c08_intra2_01_setup) (camera_set_animation_relative objects\characters\cinematic_camera\08_intra2\08_intra2 "08_intra2_01" none "anchor_flag_intra2") (custom_animation_relative dervish_02 objects\characters\dervish\08_intra2\08_intra2 "dervish_01" false anchor_intra2) (custom_animation_relative johnson_02 objects\characters\marine\08_intra2\08_intra2 "johnson_01" false anchor_intra2) (scenery_animation_start_relative scarab_01 scenarios\objects\covenant\military\scarab\08_intra2\08_intra2 "scarab_01" anchor_intra2) (fade_in 1 1 1 15) (sleep (- (camera_time) prediction_offset)) (08_intra2_02_predict_stub) (sleep (- (camera_time) sound_offset)) (sound_impulse_predict sound\cinematics\08_deltacliffs\c08_intra2\foley\c08_intra2_02_fol) (sleep (camera_time)) ) (script dormant c08_intra2_foley_02 (sleep 0) (sound_impulse_start sound\cinematics\08_deltacliffs\c08_intra2\foley\c08_intra2_02_fol none 1) (print "c08_intra1 foley 04 start") ) (script dormant c08_3050_jon (sleep 70) (sound_impulse_start_effect sound\dialog\levels\08_controlroom\cinematic\c08_3050_jon johnson_02 1 radio_covy_loop) (cinematic_subtitle c08_3050_jon 2) ) (script dormant c08_3061_jon (sleep 156) (sound_impulse_start_effect sound\dialog\levels\08_controlroom\cinematic\c08_3061_jon johnson_02 1 radio_covy_loop) (cinematic_subtitle c08_3061_jon 2) ) (script dormant c08_3070_jon (sleep 231) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_3070_jon johnson_02 1) (cinematic_subtitle c08_3070_jon 1) (unit_set_emotional_state johnson_02 angry .75 45) ) (script dormant intra2_dof (sleep 68) (cinematic_screen_effect_start true) (cinematic_screen_effect_set_depth_of_field 1 .5 .5 0.001 0 0 0.001) (print "rack focus") (sleep 151) (cinematic_screen_effect_stop) (print "rack focus stop") ) (script dormant scarab_shake2 (sleep 137) (print "shake") (player_effect_set_max_rotation 0 1 1) (player_effect_start .75 .15) (sleep 5) (player_effect_stop .5) ) (script static void c08_intra2_02_setup (wake c08_intra2_foley_02) (wake c08_3050_jon) (wake c08_3061_jon) (wake c08_3070_jon) (wake intra2_dof) (wake scarab_shake2) ) (script static void c08_intra2_02_cleanup (object_destroy dervish_02) (object_destroy johnson_02) (object_destroy scarab_01) (object_destroy scarab_screen) (object_create_anew scarab) ) (script static void c08_intra2_scene_02 (c08_intra2_02_setup) (camera_set_animation_relative objects\characters\cinematic_camera\08_intra2\08_intra2 "08_intra2_02" none "anchor_flag_intra2") (custom_animation_relative dervish_02 objects\characters\dervish\08_intra2\08_intra2 "dervish_02" false anchor_intra2) (custom_animation_relative johnson_02 objects\characters\marine\08_intra2\08_intra2 "johnson_02" false anchor_intra2) (scenery_animation_start_relative scarab_01 scenarios\objects\covenant\military\scarab\08_intra2\08_intra2 "scarab_02" anchor_intra2) (sleep (- (camera_time) 15)) (fade_out 1 1 1 15) (sleep 15) (c08_intra2_02_cleanup) (sound_class_set_gain amb 0 15) (sleep 15) ) (script static void c08_intra2 (texture_cache_flush) (geometry_cache_flush) (switch_bsp_by_name deltacontrolroom_bsp0) (sleep 1) (c08_intra2_scene_01) (c08_intra2_scene_02) ) (script dormant c08_intra3_foley_01 (sleep 0) (sound_impulse_start sound\cinematics\08_deltacliffs\c08_intra3\foley\c08_intra3_01_fol none 1) (print "c08_intra3 foley 01 start") ) (script dormant c08_4010_tar (sleep 0) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4010_tar tartarus 1) (cinematic_subtitle c08_4010_tar 4) ) (script dormant c08_4020_tar (sleep 167) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4020_tar tartarus 1) (cinematic_subtitle c08_4020_tar 3) ) (script dormant c08_4030_gsp (sleep 251) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4030_gsp monitor 1) (cinematic_subtitle c08_4030_gsp 3) ) (script dormant c08_4040_tar (sleep 344) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4040_tar tartarus 1) (cinematic_subtitle c08_4040_tar 4) ) (script dormant c08_4050_mir (sleep 486) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4050_mir miranda 1) (cinematic_subtitle c08_4050_mir 1) ) (script dormant c08_4060_tar (sleep 510) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4060_tar tartarus 1) (cinematic_subtitle c08_4060_tar 3) ) LIGHTING & EFFECTS -------------------------------------------------- (script dormant c08_intra3_fov_01 (sleep 246) (camera_set_field_of_view 30 0) (print "fov change: 60 -> 30 over 0 ticks") (sleep 105) (camera_set_field_of_view 60 13) (print "fov change: 30 -> 60 over 13 ticks") ) (script dormant cinematic_lighting_intra3_01 (cinematic_lighting_set_primary_light 63 80 0.180392 0.168627 0.129412) (cinematic_lighting_set_secondary_light -51 188 0.101961 0.2 0.301961) (cinematic_lighting_set_ambient_light 0.121569 0.121569 0.0705882) (rasterizer_bloom_override 1) (rasterizer_bloom_override_threshold .3) (rasterizer_bloom_override_brightness .5) (object_uses_cinematic_lighting miranda 1) (object_uses_cinematic_lighting tartarus 1) (object_uses_cinematic_lighting brute_01 1) (object_uses_cinematic_lighting brute_02 1) (object_uses_cinematic_lighting brute_03 1) (object_uses_cinematic_lighting brute_04 1) (object_uses_cinematic_lighting monitor 1) (object_uses_cinematic_lighting index 1) ) (script static void c08_intra3_problem_actors_01 (print "problem actors") (object_create_anew miranda) (object_create_anew tartarus) (object_create_anew brute_01) (object_create_anew brute_02) (object_create_anew brute_03) (object_create_anew brute_04) (object_create_anew monitor) (object_cinematic_lod miranda true) (object_cinematic_lod tartarus true) (object_cinematic_lod brute_01 true) (object_cinematic_lod brute_02 true) (object_cinematic_lod brute_03 true) (object_cinematic_lod brute_04 true) (object_cinematic_lod monitor true) ) (script dormant c08_intra2_miranda_emotion_01 (unit_set_emotional_state miranda angry .25 0) (sleep 180) (unit_set_emotional_state miranda angry .75 30) ) (script dormant c08_intra2_miranda_emotion_02 (sleep 488) (unit_set_emotional_state miranda pain .75 30) (sleep 81) (unit_set_emotional_state miranda angry .25 60) ) (script static void c08_intra3_01_setup (object_create_anew index) (object_create_anew repository) (object_cinematic_lod index true) (object_cinematic_lod repository true) (wake c08_intra3_foley_01) (wake c08_4010_tar) (wake c08_4020_tar) (wake c08_4030_gsp) (wake c08_4040_tar) (wake c08_4050_mir) (wake c08_4060_tar) (wake c08_intra2_miranda_emotion_01) (wake c08_intra2_miranda_emotion_02) ( wake ) (wake c08_intra3_fov_01) (wake cinematic_lighting_intra3_01) ) (script static void c08_intra3_scene_01 (fade_out 1 1 1 0) (camera_control on) (cinematic_start) (set cinematic_letterbox_style 1) (camera_set_field_of_view 60 0) (c08_intra3_problem_actors_01) (08_intra3_01_predict_stub) (sound_impulse_predict sound\cinematics\08_deltacliffs\c08_intra3\foley\c08_intra3_01_fol) (sleep prediction_offset) (c08_intra3_01_setup) (camera_set_animation_relative objects\characters\cinematic_camera\08_intra3\08_intra3 "08_intra3_01" none "anchor_flag_intra3") (custom_animation_relative miranda objects\characters\miranda\08_intra3\08_intra3 "miranda_01" false anchor_intra3) (custom_animation_relative monitor objects\characters\monitor\08_intra3\08_intra3 "monitor_01" false anchor_intra3) (custom_animation_relative tartarus objects\characters\brute\08_intra3\08_intra3 "tartarus_01" false anchor_intra3) (custom_animation_relative brute_01 objects\characters\brute\08_intra3\08_intra3 "brute01_01" false anchor_intra3) (custom_animation_relative brute_02 objects\characters\brute\08_intra3\08_intra3 "brute02_01" false anchor_intra3) (custom_animation_relative brute_03 objects\characters\brute\08_intra3\08_intra3 "brute03_01" false anchor_intra3) (custom_animation_relative brute_04 objects\characters\brute\08_intra3\08_intra3 "brute04_01" false anchor_intra3) ( scenery_animation_start_relative hammer objects\weapons\melee\gravity_hammer\08_intra3\08_intra3 " " anchor_intra3 ) (scenery_animation_start_relative index scenarios\objects\forerunner\industrial\index\index_full\08_intra3\08_intra3 "index_01" anchor_intra3) (fade_in 1 1 1 15) (sleep (- (camera_time) prediction_offset)) (08_intra3_02_predict_stub) (sleep (- (camera_time) sound_offset)) (sound_impulse_predict sound\cinematics\08_deltacliffs\c08_intra3\music\c08_intra3_02_mus) (sound_impulse_predict sound\cinematics\08_deltacliffs\c08_intra3\foley\c08_intra3_02_fol) (sleep (camera_time)) ) (script dormant c08_intra3_score_02 (sleep 0) (sound_impulse_start sound\cinematics\08_deltacliffs\c08_intra3\music\c08_intra3_02_mus none 1) (print "c08_intra3 score 02 start") ) (script dormant c08_intra3_foley_02 (sleep 0) (sound_impulse_start sound\cinematics\08_deltacliffs\c08_intra3\foley\c08_intra3_02_fol none 1) (print "c08_intra3 foley 02 start") ) (script dormant c08_4070_der (sleep 36) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4070_der dervish 1) (cinematic_subtitle c08_4070_der 1) ) (script dormant c08_4080_tar (sleep 77) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4080_tar tartarus 1) (cinematic_subtitle c08_4080_tar 3) ) (script dormant c08_4100_der (sleep 157) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4100_der dervish 1) (cinematic_subtitle c08_4100_der 2) ) (script dormant c08_4110_tar (sleep 212) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4110_tar tartarus 1) (cinematic_subtitle c08_4110_tar 3) ) (script dormant c08_4120_der (sleep 312) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4120_der dervish 1) (cinematic_subtitle c08_4120_der 5) ) (script dormant c08_4140_tar (sleep 516) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4140_tar tartarus 1) (cinematic_subtitle c08_4140_tar 4) ) (script dormant c08_4150_der (sleep 628) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4150_der dervish 1) (cinematic_subtitle c08_4150_der 1) ) (script dormant c08_4160_der (sleep 681) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4160_der dervish 1) (cinematic_subtitle c08_4160_der 3) ) (script dormant unhide_dervish (time_code_reset) (sleep 10) (print "unhide dervish") (object_hide dervish false) ) (script static void c08_intra3_02_setup (object_create_anew dervish) (object_cinematic_lod dervish true) (object_hide dervish true) (cinematic_clone_players_weapon dervish "right_hand_elite" "") (wake c08_intra3_score_02) (wake c08_intra3_foley_02) (wake c08_4070_der) (wake c08_4080_tar) (wake c08_4100_der) (wake c08_4110_tar) (wake c08_4120_der) (wake c08_4140_tar) (wake c08_4150_der) (wake c08_4160_der) (wake unhide_dervish) ( wake ) ) (script static void c08_intra3_scene_02 (c08_intra3_02_setup) (camera_set_animation_relative objects\characters\cinematic_camera\08_intra3\08_intra3 "08_intra3_02" none "anchor_flag_intra3") (custom_animation_relative miranda objects\characters\miranda\08_intra3\08_intra3 "miranda_02" false anchor_intra3) (custom_animation_relative monitor objects\characters\monitor\08_intra3\08_intra3 "monitor_02" false anchor_intra3) (custom_animation_relative dervish objects\characters\dervish\08_intra3\08_intra3 "dervish_02" false anchor_intra3) (custom_animation_relative tartarus objects\characters\brute\08_intra3\08_intra3 "tartarus_02" false anchor_intra3) (custom_animation_relative brute_01 objects\characters\brute\08_intra3\08_intra3 "brute01_02" false anchor_intra3) (custom_animation_relative brute_02 objects\characters\brute\08_intra3\08_intra3 "brute02_02" false anchor_intra3) (custom_animation_relative brute_03 objects\characters\brute\08_intra3\08_intra3 "brute03_02" false anchor_intra3) (custom_animation_relative brute_04 objects\characters\brute\08_intra3\08_intra3 "brute04_02" false anchor_intra3) (scenery_animation_start_relative index scenarios\objects\forerunner\industrial\index\index_full\08_intra3\08_intra3 "index_02" anchor_intra3) (sleep (- (camera_time) prediction_offset)) (08_intra3_03_predict_stub) (sleep (- (camera_time) sound_offset)) (sound_impulse_predict sound\cinematics\08_deltacliffs\c08_intra3\foley\c08_intra3_03_fol) (sleep (camera_time)) ) (script dormant c08_intra3_foley_03 (sleep 0) (sound_impulse_start sound\cinematics\08_deltacliffs\c08_intra3\foley\c08_intra3_03_fol none 1) (print "c08_intra3 foley 03 start") ) (script dormant c08_4170_gsp (sleep 0) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4170_gsp monitor 1) (cinematic_subtitle c08_4170_gsp 2) ) (script dormant c08_4180_tar (sleep 41) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4180_tar tartarus 1) (cinematic_subtitle c08_4180_tar 2) ) (script dormant c08_4190_tar (sleep 84) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4190_tar tartarus 1) (cinematic_subtitle c08_4190_tar 2) ) (script dormant c08_4200_jon (sleep 137) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4200_jon johnson 1) (cinematic_subtitle c08_4200_jon 1) (unit_set_emotional_state johnson angry .5 0) (print "johnson - angry .5 0") ) (script dormant c08_4201_jon (sleep 202) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4201_jon johnson 1) (cinematic_subtitle c08_4201_jon 2) ) (script dormant c08_4220_jon (sleep 308) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4220_jon johnson 1) (cinematic_subtitle c08_4220_jon 3) (unit_set_emotional_state johnson angry 1 15) (print "johnson - angry 1 15") ) (script dormant c08_4230_tar (sleep 430) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4230_tar tartarus 1) (cinematic_subtitle c08_4230_tar 1) ) (script dormant c08_4240_jon (sleep 474) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4240_jon johnson 1) (cinematic_subtitle c08_4240_jon 2) ) (script dormant c08_4250_der (sleep 548) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4250_der dervish 1) (cinematic_subtitle c08_4250_der 2) ) (script dormant c08_intra3_fov_03 (sleep 184) (camera_set_field_of_view 5 21) (print "fov change: 60 -> 5 over 21 ticks") (sleep 69) (camera_set_field_of_view 60 0) (print "fov change: 5 -> 60 over 0 ticks") ) (script dormant cinematic_lighting_intra3_03 (object_uses_cinematic_lighting johnson 1) (object_uses_cinematic_lighting cov_sniper 1) ) (script static void c08_intra3_03_setup (object_create_anew johnson) (object_create_anew cov_sniper) (object_cinematic_lod johnson true) (object_cinematic_lod cov_sniper true) (objects_attach johnson "right_hand" cov_sniper "") (wake c08_intra3_foley_03) (wake c08_4170_gsp) (wake c08_4180_tar) (wake c08_4190_tar) (wake c08_4200_jon) (wake c08_4201_jon) (wake c08_4220_jon) (wake c08_4230_tar) (wake c08_4240_jon) (wake c08_4250_der) ( wake ) (wake c08_intra3_fov_03) (wake cinematic_lighting_intra3_03) ) (script static void c08_intra3_scene_03 (c08_intra3_03_setup) (camera_set_animation_relative objects\characters\cinematic_camera\08_intra3\08_intra3 "08_intra3_03" none "anchor_flag_intra3") (custom_animation_relative miranda objects\characters\miranda\08_intra3\08_intra3 "miranda_03" false anchor_intra3) (custom_animation_relative johnson objects\characters\marine\08_intra3\08_intra3 "johnson_03" false anchor_intra3) (custom_animation_relative monitor objects\characters\monitor\08_intra3\08_intra3 "monitor_03" false anchor_intra3) (custom_animation_relative dervish objects\characters\dervish\08_intra3\08_intra3 "dervish_03" false anchor_intra3) (custom_animation_relative tartarus objects\characters\brute\08_intra3\08_intra3 "tartarus_03" false anchor_intra3) (custom_animation_relative brute_01 objects\characters\brute\08_intra3\08_intra3 "brute01_03" false anchor_intra3) (custom_animation_relative brute_02 objects\characters\brute\08_intra3\08_intra3 "brute02_03" false anchor_intra3) (custom_animation_relative brute_03 objects\characters\brute\08_intra3\08_intra3 "brute03_03" false anchor_intra3) (custom_animation_relative brute_04 objects\characters\brute\08_intra3\08_intra3 "brute04_03" false anchor_intra3) (scenery_animation_start_relative index scenarios\objects\forerunner\industrial\index\index_full\08_intra3\08_intra3 "index_03" anchor_intra3) (sleep (- (camera_time) prediction_offset)) (08_intra3_04_predict_stub) (sleep (- (camera_time) sound_offset)) (sound_impulse_predict sound\cinematics\08_deltacliffs\c08_intra3\foley\c08_intra3_04_fol) (sleep (camera_time)) ) (script dormant c08_intra3_foley_04 (sleep 0) (sound_impulse_start sound\cinematics\08_deltacliffs\c08_intra3\foley\c08_intra3_04_fol none 1) (print "c08_intra3 foley 04 start") ) (script dormant c08_4260_gsp (sleep 0) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4260_gsp monitor 1) (cinematic_subtitle c08_4260_gsp 6) (unit_set_emotional_state miranda shocked .25 0) (print "miranda - shocked .25 0") ) (script dormant c08_4270_der (sleep 189) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4270_der dervish 1) (cinematic_subtitle c08_4270_der 4) ) (script dormant c08_4280_gsp (sleep 297) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4280_gsp monitor 1) (cinematic_subtitle c08_4280_gsp 11) ) (script dormant c08_4290_gsp (sleep 640) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4290_gsp monitor 1) (cinematic_subtitle c08_4290_gsp 2) ) (script dormant c08_4300_der (sleep 746) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4300_der dervish 1) (cinematic_subtitle c08_4300_der 4) ) (script static void c08_intra3_04_setup (wake c08_intra3_foley_04) (wake c08_4260_gsp) (wake c08_4270_der) (wake c08_4280_gsp) (wake c08_4290_gsp) (wake c08_4300_der) ( wake ) ) (script static void c08_intra3_scene_04 (c08_intra3_04_setup) (camera_set_animation_relative objects\characters\cinematic_camera\08_intra3\08_intra3 "08_intra3_04" none "anchor_flag_intra3") (custom_animation_relative miranda objects\characters\miranda\08_intra3\08_intra3 "miranda_04" false anchor_intra3) (custom_animation_relative johnson objects\characters\marine\08_intra3\08_intra3 "johnson_04" false anchor_intra3) (custom_animation_relative monitor objects\characters\monitor\08_intra3\08_intra3 "monitor_04" false anchor_intra3) (custom_animation_relative dervish objects\characters\dervish\08_intra3\08_intra3 "dervish_04" false anchor_intra3) (custom_animation_relative tartarus objects\characters\brute\08_intra3\08_intra3 "tartarus_04" false anchor_intra3) (scenery_animation_start_relative index scenarios\objects\forerunner\industrial\index\index_full\08_intra3\08_intra3 "index_04" anchor_intra3) (sleep (- (camera_time) prediction_offset)) (08_intra3_05_predict_stub) (sleep (- (camera_time) sound_offset)) (sound_impulse_predict sound\cinematics\08_deltacliffs\c08_intra3\foley\c08_intra3_05_fol) (sleep (camera_time)) ) (script dormant c08_intra3_foley_05 (sleep 0) (sound_impulse_start sound\cinematics\08_deltacliffs\c08_intra3\foley\c08_intra3_05_fol none 1) (print "c08_intra3 foley 05 start") ) (script dormant c08_4310_jon (sleep 74) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4310_jon johnson 1) (cinematic_subtitle c08_4310_jon 1) ) (script dormant c08_4320_tar (sleep 106) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4320_tar tartarus 1) (cinematic_subtitle c08_4320_tar 1) (unit_set_emotional_state miranda pain .5 0) (print "miranda - pain .5 0") (sleep 45) (unit_set_emotional_state miranda scared .5 15) (print "miranda - scared .5 15") ) (script dormant c08_4330_tar (sleep 144) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4330_tar tartarus 1) (cinematic_subtitle c08_4330_tar 2) ) (script dormant c08_4340_tar (sleep 220) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\c08_4340_tar tartarus 1) (cinematic_subtitle c08_4340_tar 4) (object_set_function_variable tartarus "invincibility" 1 60) (print "tartarus activates shield") ) LIGHTING & EFFECTS -------------------------------------------------- (script dormant cinematic_lighting_intra3_05 (object_uses_cinematic_lighting hammer 1) ) (script dormant index_insertion (sleep 165) (print "slot the icon") (device_set_position repository 1) (effect_new_on_object_marker effects\objects\cinematics\index\index_insertion index "") (sleep 15) (object_destroy index) ) (script static void c08_intra3_05_setup (object_create_anew hammer) (object_cinematic_lod hammer true) (wake c08_intra3_foley_05) (wake c08_4310_jon) (wake c08_4320_tar) (wake c08_4330_tar) (wake c08_4340_tar) (wake index_insertion) ( wake ) (wake cinematic_lighting_intra3_05) ) (script dormant c08_intra3_05_cleanup (object_destroy miranda) (object_destroy johnson) (object_destroy monitor) (object_destroy dervish) (object_destroy tartarus) (object_destroy brute_01) (object_destroy brute_02) (object_destroy brute_03) (object_destroy brute_04) (object_destroy repository) (object_destroy index) (object_destroy hammer) (object_destroy cov_sniper) ) (script static void c08_intra3_scene_05 (c08_intra3_05_setup) (camera_set_animation_relative objects\characters\cinematic_camera\08_intra3\08_intra3 "08_intra3_05" none "anchor_flag_intra3") (custom_animation_relative miranda objects\characters\miranda\08_intra3\08_intra3 "miranda_05" false anchor_intra3) (custom_animation_relative johnson objects\characters\marine\08_intra3\08_intra3 "johnson_05" false anchor_intra3) (custom_animation_relative monitor objects\characters\monitor\08_intra3\08_intra3 "monitor_05" false anchor_intra3) (custom_animation_relative dervish objects\characters\dervish\08_intra3\08_intra3 "dervish_05" false anchor_intra3) (custom_animation_relative tartarus objects\characters\brute\08_intra3\08_intra3 "tartarus_05" false anchor_intra3) (custom_animation_relative brute_01 objects\characters\brute\08_intra3\08_intra3 "brute01_05" false anchor_intra3) (custom_animation_relative brute_02 objects\characters\brute\08_intra3\08_intra3 "brute02_05" false anchor_intra3) (custom_animation_relative brute_03 objects\characters\brute\08_intra3\08_intra3 "brute03_05" false anchor_intra3) (custom_animation_relative brute_04 objects\characters\brute\08_intra3\08_intra3 "brute04_05" false anchor_intra3) (scenery_animation_start_relative hammer objects\weapons\melee\gravity_hammer\08_intra3\08_intra3 "hammer_05" anchor_intra3) (scenery_animation_start_relative index scenarios\objects\forerunner\industrial\index\index_full\08_intra3\08_intra3 "index_05" anchor_intra3) (sleep (- (camera_time) prediction_offset)) (08_intra3_06_predict_stub) (sleep (- (camera_time) sound_offset)) (sound_impulse_predict sound\cinematics\08_deltacliffs\c08_intra3\music\c08_intra3_06_mus) (sound_impulse_predict sound\cinematics\08_deltacliffs\c08_intra3\foley\c08_intra3_06_fol) (sleep (camera_time)) (wake c08_intra3_05_cleanup) ) (script dormant create_lift (print "create lift") (object_create_anew c08_intra3_lift) (object_set_function_variable c08_intra3_lift "effect" 0 0) (sleep 10) (object_set_function_variable c08_intra3_lift "effect" 1 60) ) (script static void c08_intra3_scene_06 (sound_impulse_start sound\cinematics\08_deltacliffs\c08_intra3\music\c08_intra3_06_mus none 1) (sound_impulse_start sound\cinematics\08_deltacliffs\c08_intra3\foley\c08_intra3_06_fol none 1) (device_set_position e13_boss_platform 1) (print "shake") (player_effect_set_max_rotation 0 1 1) (player_effect_start .25 3) (camera_set platform_01a 0) (camera_set platform_01b 420) (sleep 300) (wake create_lift) (sleep 30) (camera_set platform_02 0) (cinematic_screen_effect_start 1) (cinematic_screen_effect_set_depth_of_field 5 0 0 0 2 2 0) (sleep 30) (cinematic_screen_effect_set_depth_of_field 5 0 2 .5 2 0 .5) (sleep 45) (player_effect_stop 1.5) (sleep 15) (print "fade to white") (fade_out 1 1 1 15) (sleep 15) (cinematic_screen_effect_stop) (object_destroy c08_intra3_lift) (sound_class_set_gain amb 0 15) (sleep 30) ) (script static void c08_intra3 (texture_cache_flush) (geometry_cache_flush) (switch_bsp_by_name deltacontrolroom_bsp3) (sleep 1) (c08_intra3_scene_01) (c08_intra3_scene_02) (c08_intra3_scene_03) (c08_intra3_scene_04) (c08_intra3_scene_05) (c08_intra3_scene_06) (rasterizer_bloom_override 0) ) X09 SCENE 01 -------------------------------------------------------- (script dormant x09_foley_1 (sleep 0) (sound_impulse_start sound\cinematics\08_deltacliffs\x09\foley\x09_01_fol none 1) (print "x09 foley 01 start") ) (script dormant x09_01_stop_sounds (sleep 383) (print "sound looping stop") (sound_looping_stop scenarios\solo\08b_deltacontrol\08b_music\08b_11) (sound_looping_stop scenarios\solo\08b_deltacontrol\08b_music\08b_12) (sound_looping_stop scenarios\solo\08b_deltacontrol\08b_music\08b_13) ) (script dormant cinematic_lighting_x09_01 (cinematic_lighting_set_primary_light -4 206 0.454902 0.435294 0.352941) (cinematic_lighting_set_secondary_light -69 234 0.152941 0.152941 0.227451) (cinematic_lighting_set_ambient_light 0.0862745 0.0862745 0.0862745) (rasterizer_bloom_override 1) (rasterizer_bloom_override_threshold .4) (rasterizer_bloom_override_brightness .5) (object_uses_cinematic_lighting miranda 1) (object_uses_cinematic_lighting rotors_x09 1) ) (script dormant x09_fov_01 (time_code_reset) (sleep 289) (camera_set_field_of_view 35 0) (print "fov change: 60 -> 35 over 0 ticks") ) (script static void x09_problem_actors_01 (print "problem actors") (object_create_anew miranda) (object_create_anew rotors_x09) (object_cinematic_lod miranda true) (object_cinematic_lod rotors_x09 true) ) (script static void x09_problem_actors_02 (print "problem actors") (object_create_anew index_x09) (object_cinematic_lod index_x09 true) ) (script dormant x09_miranda_emotion_01 (unit_set_emotional_state miranda angry .25 0) (sleep 186) (unit_set_emotional_state miranda shocked .5 30) (sleep 71) (unit_set_emotional_state miranda pain .5 30) ) (script static void x09_01_setup (object_destroy e13_rotors) (wake x09_miranda_emotion_01) (wake x09_01_stop_sounds) (wake x09_foley_1) (wake x09_fov_01) (wake cinematic_lighting_x09_01) ) (script static void x09_scene_01 (fade_out 1 1 1 0) (camera_control on) (cinematic_start) (cinematic_outro_start) (set cinematic_letterbox_style 1) (camera_set_field_of_view 60 0) (cinematic_lightmap_shadow_enable) (x09_problem_actors_01) (x09_01_predict_stub) (sound_impulse_predict sound\cinematics\08_deltacliffs\x09\foley\x09_01_fol) (sleep prediction_offset) (sleep 30) (x09_01_setup) (camera_set_animation_relative objects\characters\cinematic_camera\x09\x09 "x09_01" none "anchor_flag_x09_01") (custom_animation_relative miranda objects\characters\miranda\x09\x09 "miranda_01" false anchor_x09_01) (scenery_animation_start_relative rotors_x09 scenarios\objects\solo\deltacontrolroom\control_rotors\x09\x09 "control_rotors_01" anchor_x09_01) (fade_in 1 1 1 15) (sleep (- (camera_time) prediction_offset)) (x09_02_predict_stub) (x09_problem_actors_02) (sleep (- (camera_time) sound_offset)) (sound_impulse_predict sound\cinematics\08_deltacliffs\x09\music\x09_02_mus) (sound_impulse_predict sound\cinematics\08_deltacliffs\x09\foley\x09_02_fol) (sleep (camera_time)) (object_destroy rotors_x09) ) X09 SCENE 02 -------------------------------------------------------- (script dormant x09_score_2 (sleep 92) (sound_impulse_start sound\cinematics\08_deltacliffs\x09\music\x09_02_mus none 1) (print "x09 score 01 start") ) (script dormant x09_foley_2 (sleep 0) (sound_impulse_start sound\cinematics\08_deltacliffs\x09\foley\x09_02_fol none 1) (print "x09 foley 02 start") ) (script dormant cinematic_lighting_x09_02 (cinematic_lighting_set_primary_light -18 166 0.454902 0.435294 0.352941) (cinematic_lighting_set_secondary_light -10 78 0.152941 0.152941 0.227451) (cinematic_lighting_set_ambient_light 0.0862745 0.0862745 0.0862745) (object_uses_cinematic_lighting index_x09 1) ) (script dormant x09_dof_01 (cinematic_screen_effect_start 1) (cinematic_screen_effect_set_depth_of_field .5 1 1 0 0 0 0) (print "rack focus") (sleep 45) (cinematic_screen_effect_set_depth_of_field .5 1 0 .25 0 1 .25) (print "rack focus") ) (script dormant lift_deactivate (sleep 93) (print "lift deactivate") (object_set_function_variable x09_lift effect 0 90) (sound_class_set_gain device 0 30) ) (script dormant x09_miranda_emotion_02 (unit_set_emotional_state miranda angry .25 0) (sleep 137) (unit_set_emotional_state miranda scared .5 90) ) (script static void x09_02_setup (wake x09_score_2) (wake x09_foley_2) (wake lift_deactivate) (wake x09_miranda_emotion_02) (wake cinematic_lighting_x09_02) ) (script static void x09_scene_02 (camera_set_field_of_view 60 0) (x09_02_setup) (camera_set_animation_relative objects\characters\cinematic_camera\x09\x09 "x09_02" none "anchor_flag_x09_01") (custom_animation_relative miranda objects\characters\miranda\x09\x09 "miranda_02" false anchor_x09_01) (scenery_animation_start_relative index_x09 scenarios\objects\forerunner\industrial\index\index_full\x09\x09 "index_02" anchor_x09_01) (sleep (- (camera_time) prediction_offset)) (x09_03_predict_stub) (sleep (- (camera_time) sound_offset)) (sound_impulse_predict sound\cinematics\08_deltacliffs\x09\foley\x09_03_fol) (sleep (- (camera_time) 15)) (fade_out 1 1 1 15) (sleep 15) (cinematic_screen_effect_stop) ) X09 SCENE 03 -------------------------------------------------------- (script dormant x09_foley_3 (sleep 0) (sound_impulse_start sound\cinematics\08_deltacliffs\x09\foley\x09_03_fol none 1) (print "x09 foley 03 start") ) (script static void x09_problem_actors_04 (print "predict: problem actors") (object_create_anew halo) (object_create_anew matte_halo) (object_cinematic_lod halo true) (object_cinematic_lod matte_halo true) ) (script static void x09_03_setup (object_create_anew x09_halo_bang) (wake x09_foley_3) ) (script static void x09_scene_03 (sleep 15) (x09_03_setup) (camera_set_animation_relative objects\characters\cinematic_camera\x09\x09 "x09_03" none "anchor_flag_x09_03") (sleep 10) (fade_in 1 1 1 15) (sleep (- (camera_time) prediction_offset)) (x09_04_predict_stub) (x09_problem_actors_04) (cinematic_screen_effect_start true) (sleep (- (camera_time) sound_offset)) (sound_impulse_predict sound\cinematics\08_deltacliffs\x09\foley\x09_04_fol) (sleep (- (camera_time) 5)) (fade_out 1 1 1 5) (sleep 5) ) X09 SCENE 04 -------------------------------------------------------- (script dormant x09_foley_4 (sleep 0) (sound_impulse_start sound\cinematics\08_deltacliffs\x09\foley\x09_04_fol none 1) (print "x09 foley 04 start") ) (script dormant cinematic_lighting_x09_04 (cinematic_lighting_set_primary_light 34 146 0.51 0.79 0.99) (cinematic_lighting_set_secondary_light 6 118 0.18 0.22 0.41) (cinematic_lighting_set_ambient_light 0.05 0.05 0.05) (rasterizer_bloom_override_threshold .75) (rasterizer_bloom_override_brightness .5) (object_uses_cinematic_lighting halo 1) ) (script static void x09_04_setup (object_create_anew matte_substance) (object_create_anew matte_high_charity) (object_cinematic_lod matte_substance true) (object_cinematic_lod matte_high_charity true) (object_create_anew x09_halo_whimper) (wake x09_foley_4) (wake cinematic_lighting_x09_04) ) (script static void x09_scene_04_cleanup (object_destroy halo) (object_destroy_containing matte) ) (script static void x09_scene_04 (x09_04_setup) (camera_set_animation_relative objects\characters\cinematic_camera\x09\x09 "x09_04" none "anchor_flag_x09_02") (scenery_animation_start_relative halo scenarios\objects\forerunner\industrial\halo\x09\x09 "halo_04" anchor_x09_02) (scenery_animation_start_relative matte_halo objects\cinematics\matte_paintings\delta_halo_quarter\x09\x09 "delta_halo_quarter_04" anchor_x09_02) (scenery_animation_start_relative matte_substance objects\cinematics\matte_paintings\substance_space\x09\x09 "substance_space_04" anchor_x09_02) (scenery_animation_start_relative matte_high_charity objects\cinematics\matte_paintings\high_charity_exterior\x09\x09 "high_charity_exterior_04" anchor_x09_02) (sleep 10) (fade_in 1 1 1 5) (sleep (- (camera_time) prediction_offset)) (x09_05_predict_stub) (cinematic_screen_effect_start true) (sleep (- (camera_time) sound_offset)) (sound_impulse_predict sound\cinematics\08_deltacliffs\x09\foley\x09_05_fol) (sleep (- (camera_time) 90)) (fade_out 0 0 0 90) (sleep 90) (x09_scene_04_cleanup) ) X09 SCENE 05 -------------------------------------------------------- (script dormant x09_foley_5 (sleep 0) (sound_impulse_start sound\cinematics\08_deltacliffs\x09\foley\x09_05_fol none 1) (print "x09 foley 05 start") ) (script dormant x09_0010_mir (sleep 188) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\x09_0010_mir miranda 1) (cinematic_subtitle x09_0010_mir 1) ) (script dormant x09_0020_gsp (sleep 214) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\x09_0020_gsp monitor 1) (cinematic_subtitle x09_0020_gsp 1) ) (script dormant x09_0030_mir (sleep 251) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\x09_0030_mir miranda 1) (cinematic_subtitle x09_0030_mir 1) ) (script dormant x09_0040_gsp (sleep 280) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\x09_0040_gsp monitor 1) (cinematic_subtitle x09_0040_gsp 3) ) (script dormant x09_0050_mir (sleep 370) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\x09_0050_mir miranda 1) (cinematic_subtitle x09_0050_mir 2) ) (script dormant x09_0060_gsp (sleep 419) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\x09_0060_gsp monitor 1) (cinematic_subtitle x09_0060_gsp 2) ) (script dormant x09_0070_mir (sleep 469) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\x09_0070_mir miranda 1) (cinematic_subtitle x09_0070_mir 1) ) (script dormant cinematic_lighting_x09_05 (cinematic_lighting_set_primary_light -18 220 0.286275 0.270588 0.219608) (cinematic_lighting_set_secondary_light 13 176 0.152941 0.152941 0.227451) (cinematic_lighting_set_ambient_light 0.0862745 0.0862745 0.0862745) (rasterizer_bloom_override_threshold .4) (rasterizer_bloom_override_brightness .5) (object_uses_cinematic_lighting miranda 1) (object_uses_cinematic_lighting johnson 1) (object_uses_cinematic_lighting monitor 1) (object_uses_cinematic_lighting index_x09 1) ) (script dormant beacon_shuffle (sleep 140) (print "beacon 01 -> beacon 02") (object_destroy beacon_01) (object_create_anew beacon_02) ) (script dormant x09_miranda_emotion_05 (sleep 467) (unit_set_emotional_state miranda angry .5 30) ) (script static void x09_05_setup (object_destroy e13_rotors) (object_destroy x09_lift) (object_create_anew johnson) (object_create_anew monitor) (object_create_anew beacon_01) (object_cinematic_lod johnson true) (object_cinematic_lod monitor true) (unit_set_emotional_state miranda inquisitive 1 0) (wake x09_miranda_emotion_05) (wake x09_foley_5) (wake x09_0010_mir) (wake x09_0020_gsp) (wake x09_0030_mir) (wake x09_0040_gsp) (wake x09_0050_mir) (wake x09_0060_gsp) (wake x09_0070_mir) (wake beacon_shuffle) (wake cinematic_lighting_x09_05) (interpolator_start x09_fog 1 1) ) (script static void x09_scene_05 (x09_05_setup) (camera_set_animation_relative objects\characters\cinematic_camera\x09\x09 "x09_05" none "anchor_flag_x09_01") (custom_animation_relative miranda objects\characters\miranda\x09\x09 "miranda_05" false anchor_x09_01) (custom_animation_relative johnson objects\characters\marine\x09\x09 "johnson_05" false anchor_x09_01) (custom_animation_relative monitor objects\characters\monitor\x09\x09 "monitor_05" false anchor_x09_01) (scenery_animation_start_relative index_x09 scenarios\objects\forerunner\industrial\index\index_full\x09\x09 "index_05" anchor_x09_01) (sleep 15) (fade_in 0 0 0 90) (sleep (- (camera_time) prediction_offset)) (x09_06_predict_stub) (sleep (- (camera_time) sound_offset)) (sound_impulse_predict sound\cinematics\08_deltacliffs\x09\foley\x09_06_fol) (sleep (camera_time)) ) X09 SCENE 06 -------------------------------------------------------- (script dormant x09_foley_6 (sleep 0) (sound_impulse_start sound\cinematics\08_deltacliffs\x09\foley\x09_06_fol none 1) (print "x09 foley 06 start") ) (script dormant x09_0080_gsp (sleep 0) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\x09_0080_gsp monitor 1) (cinematic_subtitle x09_0080_gsp 10) ) (script dormant x09_0090_mir (sleep 310) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\x09_0090_mir miranda 1) (cinematic_subtitle x09_0090_mir 2) ) (script dormant x09_0100_gsp (sleep 386) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\x09_0100_gsp monitor 1) (cinematic_subtitle x09_0100_gsp 1) ) (script dormant x09_0110_jon (sleep 430) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\x09_0110_jon johnson 1) (cinematic_subtitle x09_0110_jon 2) ) (script dormant x09_0120_mir (sleep 494) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\x09_0120_mir miranda 1) (cinematic_subtitle x09_0120_mir 4) (sleep 30) ( unit_set_emotional_state miranda pain .25 15 ) ( print " miranda - pain .25 15 " ) ) (script dormant x09_0130_gsp (sleep 675) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\x09_0130_gsp monitor 1) (cinematic_subtitle x09_0130_gsp 2) ) (script dormant x09_0140_der (sleep 742) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\x09_0140_der dervish 1) (cinematic_subtitle x09_0140_der 3) ) (script dormant cinematic_lighting_x09_06 (cinematic_lighting_set_primary_light -18 220 0.286275 0.270588 0.219608) (cinematic_lighting_set_secondary_light 13 176 0.152941 0.152941 0.227451) (cinematic_lighting_set_ambient_light 0.0862745 0.0862745 0.0862745) (object_uses_cinematic_lighting dervish 1) ) (script dormant x09_miranda_emotion_06a (sleep 310) (unit_set_emotional_state miranda scared .5 60) ) (script dormant x09_miranda_emotion_06b (sleep 525) (unit_set_emotional_state miranda pain .25 90) ) (script dormant x09_miranda_emotion_06c (sleep 776) (unit_set_emotional_state miranda shocked .25 30) ) (script dormant x09_johnson_emotion_06a (sleep 440) (unit_set_emotional_state johnson angry .75 60) (sleep 54) (unit_set_emotional_state johnson shocked .25 30) ) (script dormant x09_johnson_emotion_06b (sleep 784) (unit_set_emotional_state johnson shocked .25 30) ) (script static void x09_06_setup (object_destroy beacon_02) (object_create_anew beacon_03) (device_set_position beacon_03 1) (object_create_anew dervish) (object_cinematic_lod dervish true) (unit_set_emotional_state miranda angry .25 0) (unit_set_emotional_state johnson angry .25 0) (wake x09_miranda_emotion_06a) (wake x09_miranda_emotion_06b) (wake x09_miranda_emotion_06c) (wake x09_johnson_emotion_06a) (wake x09_johnson_emotion_06b) (wake x09_foley_6) (wake x09_0080_gsp) (wake x09_0090_mir) (wake x09_0100_gsp) (wake x09_0110_jon) (wake x09_0120_mir) (wake x09_0130_gsp) (wake x09_0140_der) ) (script static void x09_scene_06_cleanup (object_destroy dervish) (object_destroy miranda) (object_destroy johnson) (object_destroy monitor) (object_destroy index_x09) ) (script static void x09_scene_06 (x09_06_setup) (camera_set_animation_relative objects\characters\cinematic_camera\x09\x09 "x09_06" none "anchor_flag_x09_01") (custom_animation_relative dervish objects\characters\dervish\x09\x09 "dervish_06" false anchor_x09_01) (custom_animation_relative miranda objects\characters\miranda\x09\x09 "miranda_06" false anchor_x09_01) (custom_animation_relative johnson objects\characters\marine\x09\x09 "johnson_06" false anchor_x09_01) (custom_animation_relative monitor objects\characters\monitor\x09\x09 "monitor_06" false anchor_x09_01) (scenery_animation_start_relative index_x09 scenarios\objects\forerunner\industrial\index\index_full\x09\x09 "index_06" anchor_x09_01) (sleep (- (camera_time) prediction_offset)) (x09_07_predict_stub) (sleep (- (camera_time) sound_offset)) (sound_impulse_predict sound\cinematics\08_deltacliffs\x09\foley\x09_07_fol) (sleep (- (camera_time) 5)) (fade_out 0 0 0 5) (sleep 5) (x09_scene_06_cleanup) ) X09 SCENE 07 -------------------------------------------------------- (script dormant x09_foley_7 (sleep 0) (sound_impulse_start sound\cinematics\08_deltacliffs\x09\foley\x09_07_fol none 1) (print "x09 foley 07 start") ) (script dormant x09_0150_to1 (sleep 100) (sound_impulse_start_effect sound\dialog\levels\08_controlroom\cinematic\x09_0150_to1 none 1 radio_default_in) (cinematic_subtitle x09_0150_to1 3) ) (script dormant cinematic_lighting_x09_07 (cinematic_lighting_set_primary_light 16 -32 .8 .6 .4) (cinematic_lighting_set_secondary_light 20 180 .3 .3 .5) (cinematic_lighting_set_ambient_light .2 .2 .2) (object_uses_cinematic_lighting forerunner_ship 1) ) (script static void x09_problem_actors_08 (print "problem actors") (object_create_anew chief) (object_create_anew x09_alcove) (object_create_anew bloom_quad) (object_cinematic_lod chief true) (object_cinematic_lod x09_alcove true) ) (script static void x09_07_setup (object_create_anew slipspace) (object_create_anew_containing earth_battle) (object_create_anew forerunner_ship) (object_create_anew matte_earth) (object_create_anew matte_moon) (object_cinematic_lod forerunner_ship true) (object_cinematic_lod matte_earth true) (object_cinematic_lod matte_moon true) (wake x09_foley_7) (wake x09_0150_to1) (wake cinematic_lighting_x09_07) ) (script static void x09_scene_07_cleanup (object_destroy slipspace) (object_destroy_containing earth_battle) (object_destroy forerunner_ship) (object_destroy_containing matte) ) (script static void x09_scene_07 (sleep 60) (x09_07_setup) (camera_set_animation_relative objects\characters\cinematic_camera\x09\x09 "x09_07" none "anchor_flag_x09_02") (scenery_animation_start_relative forerunner_ship objects\cinematics\forerunner\forerunner_ship\x09\x09 "forerunner_ship_07" anchor_x09_02) (scenery_animation_start_relative cairo scenarios\objects\solo\spacestation\ss_prop\x09\x09 "ss_prop_07" anchor_x09_02) (scenery_animation_start_relative matte_earth objects\cinematics\matte_paintings\earth_space\x09\x09 "earth_space_07" anchor_x09_02) (scenery_animation_start_relative matte_moon objects\cinematics\matte_paintings\moon\x09\x09 "moon_07" anchor_x09_02) (fade_in 0 0 0 5) (sleep (- (camera_time) prediction_offset)) (x09_08_predict_stub) (x09_problem_actors_08) (sleep (- (camera_time) sound_offset)) (sound_impulse_predict sound\cinematics\08_deltacliffs\x09\music\x09_08_mus) (sound_impulse_predict sound\cinematics\08_deltacliffs\x09\foley\x09_03_fol) (sleep (- (camera_time) 5)) (fade_out 1 1 1 5) (sleep 5) (x09_scene_07_cleanup) ) X09 SCENE 08 -------------------------------------------------------- (script dormant x09_score_8 (sleep 338) (sound_impulse_start sound\cinematics\08_deltacliffs\x09\music\x09_08_mus none 1) (print "x09 score 08 start") ) (script dormant x09_foley_8 (sleep 0) (sound_impulse_start sound\cinematics\08_deltacliffs\x09\foley\x09_08_fol none 1) (print "x09 foley 08 start") ) (script dormant x09_0160_lhd (sleep 0) (sound_impulse_start_effect sound\dialog\levels\08_controlroom\cinematic\x09_0160_lhd none 1 radio_default_loop) (cinematic_subtitle x09_0160_lhd 2) ) (script dormant x09_0180_mas (sleep 69) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\x09_0180_mas chief 1) (cinematic_subtitle x09_0180_mas 2) ) (script dormant x09_0190_mas (sleep 132) (sound_impulse_start_effect sound\dialog\levels\08_controlroom\cinematic\x09_0190_mas none 1 radio_default_out) (cinematic_subtitle x09_0190_mas 2) ) (script dormant x09_0200_lhd (sleep 183) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\x09_0200_lhd hood 1) (cinematic_subtitle x09_0200_lhd 1) ) (script dormant x09_0210_lhd (sleep 232) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\x09_0210_lhd hood 1) (cinematic_subtitle x09_0210_lhd 3) ) (script dormant x09_0220_mas (sleep 342) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\x09_0220_mas chief 1) (cinematic_subtitle x09_0220_mas 3) ) (script dormant cinematic_light_x09_chief_01 (print "light chief 01") (cinematic_lighting_set_primary_light -20 278 0.388235 0.427451 0.494118) (cinematic_lighting_set_secondary_light 42 224 0.0431373 0.0431373 0.0666667) (cinematic_lighting_set_ambient_light 0 0 0) (rasterizer_bloom_override_threshold .3) (rasterizer_bloom_override_brightness .5) (object_uses_cinematic_lighting chief 1) (object_uses_cinematic_lighting hood 1) (object_uses_cinematic_lighting cairo_bridge 1) (object_uses_cinematic_lighting x09_alcove 1) ) (script dormant cinematic_light_x09_hood_01 (sleep 124) (print "light hood 01") (cinematic_lighting_set_primary_light 0 94 0.47451 0.443137 0.333333) (cinematic_lighting_set_secondary_light 0 320 0.184314 0.176471 0.266667) (cinematic_lighting_set_ambient_light 0 0 0) (rasterizer_bloom_override_threshold .75) (rasterizer_bloom_override_brightness .5) ) (script dormant final_explosion (time_code_reset) (sleep 135) (object_create_anew_containing blast_base) (effect_new_on_object_marker effects\cinematics\01_outro\covenant_tiny_explosion blast_base "marker") (sleep 110) (effect_new_on_object_marker effects\cinematics\01_outro\covenant_tiny_explosion blast_base2 "marker") ) (script dormant cinematic_light_x09_chief_02 (sleep 277) (print "light chief 02") (cinematic_lighting_set_primary_light -20 278 0.388235 0.427451 0.494118) (cinematic_lighting_set_secondary_light 42 224 0.0431373 0.0431373 0.0666667) (cinematic_lighting_set_ambient_light 0 0 0) (rasterizer_bloom_override_threshold .3) (rasterizer_bloom_override_brightness .5) ) (script dormant x09_hood_emotion_08 (sleep 43) (unit_set_emotional_state hood shocked .5 30) (sleep 45) (unit_set_emotional_state hood happy .25 90) ) (script dormant shake_chief (print "shake") (player_effect_set_max_rotation 0 1 1) (player_effect_start .75 0) (sleep 15) (player_effect_stop 3) ) (script static void x09_08_setup (object_create_anew hood) (object_create_anew cairo_bridge) (object_cinematic_lod hood true) (object_cinematic_lod cairo_bridge true) (object_create_anew_containing cairo_effect) (unit_set_emotional_state hood angry .5 0) (wake x09_hood_emotion_08) (wake x09_score_8) (wake x09_foley_8) (wake x09_0160_lhd) (wake x09_0180_mas) (wake x09_0190_mas) (wake x09_0200_lhd) (wake x09_0210_lhd) (wake x09_0220_mas) (wake shake_chief) (wake final_explosion) (wake cinematic_light_x09_chief_01) (wake cinematic_light_x09_hood_01) (wake cinematic_light_x09_chief_02) ) (script static void x09_scene_08_cleanup (object_destroy chief) (object_destroy hood) (object_destroy cairo_bridge) (object_destroy x09_alcove) (object_destroy bloom_quad) (object_destroy_containing blast_base) ) (script static void x09_scene_08 (x09_08_setup) (camera_set_animation_relative objects\characters\cinematic_camera\x09\x09 "x09_08" none "anchor_flag_x09_02") (custom_animation_relative chief objects\characters\masterchief\x09\x09 "chief_08" false anchor_x09_02) (custom_animation_relative hood objects\characters\lord_hood\x09\x09 "hood_08" false anchor_x09_02) (scenery_animation_start_relative cairo_bridge objects\cinematics\human\cairo_bridge\x09\x09 "cairo_bridge_08" anchor_x09_02) (scenery_animation_start_relative x09_alcove objects\cinematics\forerunner\forerunner_ship_alcove\x09\x09 "alcove_08" anchor_x09_02) (scenery_animation_start_relative bloom_quad scenarios\objects\special\bloom_quad\x09\x09 "bloom_quad_08" anchor_x09_02) (sleep 10) (fade_in 1 1 1 5) (sleep (- (camera_time) 5)) (fade_out 0 0 0 5) (sleep 5) (sleep 401) (x09_scene_08_cleanup) (rasterizer_bloom_override 0) ) X10 SCENE 01 -------------------------------------------------------- (script dormant x10_score_1 (sleep 0) (sound_impulse_start sound\cinematics\08_deltacliffs\x10\music\x10_01_mus none 1) (print "x10 score 01 start") ) (script dormant x10_foley_1 (sleep 0) (sound_impulse_start sound\cinematics\08_deltacliffs\x10\foley\x10_01_fol none 1) (print "x10 foley 01 start") ) (script dormant x10_0010_grv (sleep 496) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\x10_0010_grv none 1) (cinematic_subtitle x10_0010_grv 6) ) (script dormant cinematic_lighting_x10_01 (cinematic_lighting_set_primary_light 51 28 0.380392 0.384314 0.341176) (cinematic_lighting_set_secondary_light -53 202 0.0588235 0.356863 0.356863) (cinematic_lighting_set_ambient_light 0.0901961 0.117647 0.0823529) (rasterizer_bloom_override 1) (rasterizer_bloom_override_threshold .3) (rasterizer_bloom_override_brightness .5) (object_uses_cinematic_lighting tentacle_01 1) (object_uses_cinematic_lighting tentacle_02 1) (object_uses_cinematic_lighting tentacle_03 1) (object_uses_cinematic_lighting tentacle_04 1) ) (script static void x10_problem_actors_01 (print "problem actors") (object_create_anew spore_01) (object_create_anew spore_02) (object_create_anew spore_03) (object_cinematic_lod spore_01 true) (object_cinematic_lod spore_02 true) (object_cinematic_lod spore_03 true) ) (script static void x10_scene_01_setup (object_create_anew x09_chamber_door) (object_create_anew tentacle_01) (object_create_anew tentacle_02) (object_create_anew tentacle_03) (object_create_anew tentacle_04) (object_cinematic_lod x09_chamber_door true) (object_cinematic_lod tentacle_01 true) (object_cinematic_lod tentacle_02 true) (object_cinematic_lod tentacle_03 true) (object_cinematic_lod tentacle_04 true) (object_cinematic_visibility tentacle_01 true) (object_cinematic_visibility tentacle_02 true) (object_cinematic_visibility tentacle_03 true) (object_cinematic_visibility tentacle_04 true) (wake x10_score_1) (wake x10_foley_1) (wake x10_0010_grv) (wake cinematic_lighting_x10_01) ) (script static void x10_scene_01_cleanup (object_destroy x09_chamber_door) (object_destroy_containing spore) ) (script static void x10_scene_01 (fade_out 0 0 0 0) (camera_control on) (cinematic_start) (cinematic_outro_start) (set cinematic_letterbox_style 1) (camera_set_field_of_view 60 0) (weather_start 0) (weather_change_intensity 0 1) (x10_problem_actors_01) (x10_01_predict_stub) (sound_impulse_predict sound\cinematics\08_deltacliffs\x10\music\x10_01_mus) (sound_impulse_predict sound\cinematics\08_deltacliffs\x10\foley\x10_01_fol) (sleep prediction_offset) (x10_scene_01_setup) (camera_set_animation_relative objects\characters\cinematic_camera\x10\x10 "x10_01" none "anchor_flag_x10") (scenery_animation_start_relative x09_chamber_door scenarios\objects\solo\highcharity\high_door_grand\x10\x10 "high_door_grand_01" anchor_x10) (scenery_animation_start_relative spore_01 objects\cinematics\flood\flood_spore\x10\x10 "spore01_01" anchor_x10) (scenery_animation_start_relative spore_02 objects\cinematics\flood\flood_spore\x10\x10 "spore02_01" anchor_x10) (scenery_animation_start_relative spore_03 objects\cinematics\flood\flood_spore\x10\x10 "spore03_01" anchor_x10) (scenery_animation_start_relative tentacle_01 objects\characters\gravemind\tentacle_capture\x10\x10 "tentacle01_01" anchor_x10) (scenery_animation_start_relative tentacle_02 objects\characters\gravemind\tentacle_capture\x10\x10 "tentacle02_01" anchor_x10) (scenery_animation_start_relative tentacle_03 objects\characters\gravemind\tentacle_capture\x10\x10 "tentacle03_01" anchor_x10) (fade_in 0 0 0 60) (sleep (- (camera_time) prediction_offset)) (x10_02_predict_stub) (cinematic_screen_effect_start true) (sleep (- (camera_time) 1)) (cinematic_screen_effect_set_crossfade 2) (sleep 1) (x10_scene_01_cleanup) ) X10 SCENE 02 -------------------------------------------------------- (script dormant x10_score_2 (sleep 553) (sound_looping_start sound\cinematics\08_deltacliffs\x10\music\x10_02_mus none 1) (print "x10 score 02 start") ) (script dormant x10_0020_grv (sleep 0) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\x10_0020_grv none 1) (cinematic_subtitle x10_0020_grv 8) ) (script dormant x10_0030_grv (sleep 260) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\x10_0030_grv none 1) (cinematic_subtitle x10_0030_grv 5) ) (script dormant x10_0040_cor (sleep 496) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\x10_0040_cor cortana 1) (cinematic_subtitle x10_0040_cor 1) ) (script dormant x10_0041_cor (sleep 520) (unit_set_emotional_state cortana pain .25 60) (print "cortana - pain .25 60") (sleep 30) (sound_impulse_start sound\dialog\levels\08_controlroom\cinematic\x10_0041_cor cortana 1) (cinematic_subtitle x10_0041_cor 1) ) (script dormant cinematic_lighting_x10_02 (cinematic_lighting_set_primary_light 51 28 0.380392 0.384314 0.341176) (cinematic_lighting_set_secondary_light -53 202 0.0588235 0.356863 0.356863) (cinematic_lighting_set_ambient_light 0.0901961 0.117647 0.0823529) (object_uses_cinematic_lighting cortana 1) ) (script dormant effect_cortana_appear (sleep 410) (print "cortana appears") (effect_new_on_object_marker effects\objects\characters\cortana\cortana_on_off_65 cortana_stand "marker") ) (script static void x10_scene_02_setup (object_create_anew cortana) (object_cinematic_lod cortana true) (object_create_anew cortana_stand) (unit_set_emotional_state cortana repulsed .5 0) (print "cortana - repulsed .5 0") (wake x10_score_2) (wake x10_0020_grv) (wake x10_0030_grv) (wake x10_0040_cor) (wake x10_0041_cor) (wake effect_cortana_appear) (wake cinematic_lighting_x10_02) (cinematic_set_near_clip_distance .05) (print "setting near clip distance to .05") ) (script static void x10_scene_02_cleanup (object_destroy_containing cortana) (object_destroy_containing tentacle) ) (script static void x10_scene_02 (time_code_reset) (x10_scene_02_setup) (camera_set_animation_relative objects\characters\cinematic_camera\x10\x10 "x10_02" none "anchor_flag_x10") (custom_animation_relative cortana objects\characters\cortana\x10\x10 "cortana_02" false anchor_x10) (scenery_animation_start_relative tentacle_01 objects\characters\gravemind\tentacle_capture\x10\x10 "tentacle01_02" anchor_x10) (scenery_animation_start_relative tentacle_02 objects\characters\gravemind\tentacle_capture\x10\x10 "tentacle02_02" anchor_x10) (scenery_animation_start_relative tentacle_03 objects\characters\gravemind\tentacle_capture\x10\x10 "tentacle03_02" anchor_x10) (scenery_animation_start_relative tentacle_04 objects\characters\gravemind\tentacle_capture\x10\x10 "tentacle04_02" anchor_x10) (sleep (- (camera_time) 5)) (fade_out 0 0 0 5) (sleep 5) (cinematic_set_near_clip_distance .06) (print "setting near clip distance to .06") (sleep 328) ) (script static void x10 (switch_bsp_by_name high_0) (sleep 1) (x10_scene_01) (x10_scene_02) ) (script static void x09 (texture_cache_flush) (geometry_cache_flush) (switch_bsp_by_name deltacontrolroom_bsp4) (sleep 1) (sound_class_set_gain amb 0 15) (x09_scene_01) (x09_scene_02) (switch_bsp_by_name deltacontrolroom_bsp0) (sleep 1) (x09_scene_03) (x09_scene_04) (switch_bsp_by_name deltacontrolroom_bsp4) (sleep 1) (x09_scene_05) (x09_scene_06) (switch_bsp_by_name deltacontrolroom_bsp0) (sleep 1) (x09_scene_07) (x09_scene_08) (sleep 30) (print "30 ticks of black for marty") (cinematic_show_letterbox 0) (play_credits) (sleep_until (bink_done) 1) (sleep 30) (x10) (sleep 30) (print "30 ticks of black for marty") (game_won) )