Public Vars

Back

or (clj)

(source)

macro

(or) (or x) (or x & next)
Evaluates exprs one at a time, from left to right. If a form returns a logical true value, or returns that value and doesn't evaluate any of the other expressions, otherwise it returns the value of the last expression. (or) returns nil.

Examples

clojure
(ns clojure.test-clojure.server
    (:import java.util.Random)
    (:require [clojure.test :refer :all])
    (:require [clojure.core.server :as s]))

(defn check-invalid-opts
  [opts msg]
  (try
    (#'clojure.core.server/validate-opts opts)
    (is nil)
    (catch Exception e
      (is (= (ex-data e) opts))
      (is (= msg (.getMessage e))))))

(deftest test-validate-opts
  (check-invalid-opts {} "Missing required socket server property :name")
  (check-invalid-opts {:name "a" :accept 'clojure.core/+} "Missing required socket server property :port")
  (doseq [port [-1 "5" 999999]]
    (check-invalid-opts {:name "a" :port port :accept 'clojure.core/+} (str "Invalid socket server port: " port)))
  (check-invalid-opts {:name "a" :port 5555} "Missing required socket server property :accept"))
clojure
(ns clojure.test-clojure.reducers
  (:require [clojure.core.reducers :as r]
            [clojure.test.generative :refer (defspec)]
            [clojure.data.generators :as gen])
  (:use clojure.test))

(defmacro defequivtest
  ;; f is the core fn, r is the reducers equivalent, rt is the reducible ->
  ;; coll transformer
  [name [f r rt] fns]
  `(deftest ~name
     (let [c# (range -100 1000)]
       (doseq [fn# ~fns]
         (is (= (~f fn# c#)
                (~rt (~r fn# c#))))))))


(deftest test-sorted-maps
  (let [m (into (sorted-map)
                '{1 a, 2 b, 3 c, 4 d})]
    (is (= "1a2b3c4d" (reduce-kv str "" m))
        "Sorted maps should reduce-kv in sorted order")
    (is (= 1 (reduce-kv (fn [acc k v]
                          (reduced (+ acc k)))
                        0 m))
        "Sorted maps should stop reduction when asked")))

(defn gen-num []
  (gen/uniform 0 2000))

(deftest test-closed-over-clearing
  ;; this will throw OutOfMemory without proper reference clearing
  (is (number? (reduce + 0 (r/map identity (range 1e8))))))
clojure
(deftest division
  (is (= clojure.core// /))
  (binding [*ns* *ns*]
    (eval '(do (ns foo
                 (:require [clojure.core :as bar])
                 (:use [clojure.test]))
               (is (= clojure.core// bar//))))))

(deftest Instants
  (testing "Instants are read as java.util.Date by default"
    (is (= java.util.Date (class #inst "2010-11-12T13:14:15.666"))))
  (let [s "#inst \"2010-11-12T13:14:15.666-06:00\""]
    (binding [*data-readers* {'inst read-instant-date}]
      (testing "read-instant-date produces java.util.Date"
        (is (= java.util.Date (class (read-string s)))))
      (testing "java.util.Date instants round-trips"
        (is (= (-> s read-string)
               (-> s read-string pr-str read-string))))
      (testing "java.util.Date instants round-trip throughout the year"
        (doseq [month (range 1 13) day (range 1 29) hour (range 1 23)]
          (let [s (format "#inst \"2010-%02d-%02dT%02d:14:15.666-06:00\"" month day hour)]
            (is (= (-> s read-string)
                   (-> s read-string pr-str read-string))))))
      (testing "java.util.Date handling DST in time zones"
        (let [dtz (TimeZone/getDefault)]
          (try
            ;; A timezone with DST in effect during 2010-11-12
            (TimeZone/setDefault (TimeZone/getTimeZone "Australia/Sydney"))
            (is (= (-> s read-string)
                   (-> s read-string pr-str read-string)))
            (finally (TimeZone/setDefault dtz)))))
      (testing "java.util.Date should always print in UTC"
        (let [d (read-string s)
              pstr (print-str d)
              len (.length pstr)]
          (is (= (subs pstr (- len 7)) "-00:00\"")))))
    (binding [*data-readers* {'inst read-instant-calendar}]
      (testing "read-instant-calendar produces java.util.Calendar"
        (is (instance? java.util.Calendar (read-string s))))
      (testing "java.util.Calendar round-trips"
        (is (= (-> s read-string)
               (-> s read-string pr-str read-string))))
      (testing "java.util.Calendar remembers timezone in literal"
        (is (= "#inst \"2010-11-12T13:14:15.666-06:00\""
               (-> s read-string pr-str)))
        (is (= (-> s read-string)
               (-> s read-string pr-str read-string))))
      (testing "java.util.Calendar preserves milliseconds"
        (is (= 666 (-> s read-string
                       (.get java.util.Calendar/MILLISECOND)))))))
  (let [s "#inst \"2010-11-12T13:14:15.123456789\""
        s2 "#inst \"2010-11-12T13:14:15.123\""
        s3 "#inst \"2010-11-12T13:14:15.123456789123\""]
    (binding [*data-readers* {'inst read-instant-timestamp}]
      (testing "read-instant-timestamp produces java.sql.Timestamp"
        (is (= java.sql.Timestamp (class (read-string s)))))
      (testing "java.sql.Timestamp preserves nanoseconds"
        (is (= 123456789 (-> s read-string .getNanos)))
        (is (= 123456789 (-> s read-string pr-str read-string .getNanos)))
        ;; truncate at nanos for s3
        (is (= 123456789 (-> s3 read-string pr-str read-string .getNanos))))
      (testing "java.sql.Timestamp should compare nanos"
        (is (= (read-string s) (read-string s3)))
        (is (not= (read-string s) (read-string s2)))))
    (binding [*data-readers* {'inst read-instant-date}]
      (testing "read-instant-date should truncate at milliseconds"
        (is (= (read-string s) (read-string s2) (read-string s3))))))
  (let [s "#inst \"2010-11-12T03:14:15.123+05:00\""
        s2 "#inst \"2010-11-11T22:14:15.123Z\""]
    (binding [*data-readers* {'inst read-instant-date}]
      (testing "read-instant-date should convert to UTC"
        (is (= (read-string s) (read-string s2)))))
    (binding [*data-readers* {'inst read-instant-timestamp}]
      (testing "read-instant-timestamp should convert to UTC"
        (is (= (read-string s) (read-string s2)))))
    (binding [*data-readers* {'inst read-instant-calendar}]
      (testing "read-instant-calendar should preserve timezone"
        (is (not= (read-string s) (read-string s2)))))))

(deftest unknown-tag
  (let [my-unknown (fn [tag val] {:unknown-tag tag :value val})
        throw-on-unknown (fn [tag val] (throw (RuntimeException. (str "No data reader function for tag " tag))))
        my-uuid (partial my-unknown 'uuid)
        u "#uuid \"550e8400-e29b-41d4-a716-446655440000\""
        s "#never.heard.of/some-tag [1 2]" ]
    (binding [*data-readers* {'uuid my-uuid}
              *default-data-reader-fn* my-unknown]
      (testing "Unknown tag"
        (is (= (read-string s)
               {:unknown-tag 'never.heard.of/some-tag
                :value [1 2]})))
      (testing "Override uuid tag"
        (is (= (read-string u)
               {:unknown-tag 'uuid
                :value "550e8400-e29b-41d4-a716-446655440000"}))))

    (binding [*default-data-reader-fn* throw-on-unknown]
      (testing "Unknown tag with custom throw-on-unknown"
        (are [err msg form] (thrown-with-msg? err msg (read-string form))
             Exception #"No data reader function for tag foo" "#foo [1 2]"
             Exception #"No data reader function for tag bar/foo" "#bar/foo [1 2]"
             Exception #"No data reader function for tag bar.baz/foo" "#bar.baz/foo [1 2]")))

    (testing "Unknown tag out-of-the-box behavior (like Clojure 1.4)"
      (are [err msg form] (thrown-with-msg? err msg (read-string form))
           Exception #"No reader function for tag foo" "#foo [1 2]"
           Exception #"No reader function for tag bar/foo" "#bar/foo [1 2]"
           Exception #"No reader function for tag bar.baz/foo" "#bar.baz/foo [1 2]"))))

(defrecord TestRecord [x y])

(deftest preserve-read-cond-test
  (let [x (read-string {:read-cond :preserve} "#?(:clj foo :cljs bar)" )]
       (is (reader-conditional? x))
       (is (not (:splicing? x)))
       (is (= :foo (get x :no-such-key :foo)))
       (is (= (:form x) '(:clj foo :cljs bar)))
       (is (= x (reader-conditional '(:clj foo :cljs bar) false))))
  (let [x (read-string {:read-cond :preserve} "#?@(:clj [foo])" )]
       (is (reader-conditional? x))
       (is (:splicing? x))
       (is (= :foo (get x :no-such-key :foo)))
       (is (= (:form x) '(:clj [foo])))
       (is (= x (reader-conditional '(:clj [foo]) true))))
  (is (thrown-with-msg? RuntimeException #"No reader function for tag"
                        (read-string {:read-cond :preserve} "#js {:x 1 :y 2}" )))
  (let [x (read-string {:read-cond :preserve} "#?(:cljs #js {:x 1 :y 2})")
        [platform tl] (:form x)]
       (is (reader-conditional? x))
       (is (tagged-literal? tl))
       (is (= 'js (:tag tl)))
       (is (= {:x 1 :y 2} (:form tl)))
       (is (= :foo (get tl :no-such-key :foo)))
       (is (= tl (tagged-literal 'js {:x 1 :y 2}))))
  (testing "print form roundtrips"
           (doseq [s ["#?(:clj foo :cljs bar)"
                      "#?(:cljs #js {:x 1, :y 2})"
                      "#?(:clj #clojure.test_clojure.reader.TestRecord [42 85])"]]
                  (is (= s (pr-str (read-string {:read-cond :preserve} s)))))))

(deftest reader-conditionals
  (testing "basic read-cond"
    (is (= '[foo-form]
           (read-string {:read-cond :allow :features #{:foo}} "[#?(:foo foo-form :bar bar-form)]")))
    (is (= '[bar-form]
           (read-string {:read-cond :allow :features #{:bar}} "[#?(:foo foo-form :bar bar-form)]")))
    (is (= '[foo-form]
           (read-string {:read-cond :allow :features #{:foo :bar}} "[#?(:foo foo-form :bar bar-form)]")))
    (is (= '[]
           (read-string {:read-cond :allow :features #{:baz}} "[#?( :foo foo-form :bar bar-form)]"))))
  (testing "environmental features"
    (is (= "clojure" #?(:clj "clojure" :cljs "clojurescript" :default "default"))))
  (testing "default features"
    (is (= "default" #?(:clj-clr "clr" :cljs "cljs" :default "default"))))
  (testing "splicing"
    (is (= [] [#?@(:clj [])]))
    (is (= [:a] [#?@(:clj [:a])]))
    (is (= [:a :b] [#?@(:clj [:a :b])]))
    (is (= [:a :b :c] [#?@(:clj [:a :b :c])]))
    (is (= [:a :b :c] [#?@(:clj [:a :b :c])])))
  (testing "nested splicing"
    (is (= [:a :b :c :d :e]
           [#?@(:clj [:a #?@(:clj [:b #?@(:clj [:c]) :d]):e])]))
    (is (= '(+ 1 (+ 2 3))
           '(+ #?@(:clj [1 (+ #?@(:clj [2 3]))]))))
    (is (= '(+ (+ 2 3) 1)
           '(+ #?@(:clj [(+ #?@(:clj [2 3])) 1]))))
    (is (= [:a [:b [:c] :d] :e]
           [#?@(:clj [:a [#?@(:clj [:b #?@(:clj [[:c]]) :d])] :e])])))
  (testing "bypass unknown tagged literals"
    (is (= [1 2 3] #?(:cljs #js [1 2 3] :clj [1 2 3])))
    (is (= :clojure #?(:foo #some.nonexistent.Record {:x 1} :clj :clojure))))
  (testing "error cases"
    (is (thrown-with-msg? RuntimeException #"Feature should be a keyword" (read-string {:read-cond :allow} "#?((+ 1 2) :a)")))
    (is (thrown-with-msg? RuntimeException #"even number of forms" (read-string {:read-cond :allow} "#?(:cljs :a :clj)")))
    (is (thrown-with-msg? RuntimeException #"read-cond-splicing must implement" (read-string {:read-cond :allow} "#?@(:clj :a)")))
    (is (thrown-with-msg? RuntimeException #"is reserved" (read-string {:read-cond :allow} "#?@(:foo :a :else :b)")))
    (is (thrown-with-msg? RuntimeException #"must be a list" (read-string {:read-cond :allow} "#?[:foo :a :else :b]")))
    (is (thrown-with-msg? RuntimeException #"Conditional read not allowed" (read-string {:read-cond :BOGUS} "#?[:clj :a :default nil]")))
    (is (thrown-with-msg? RuntimeException #"Conditional read not allowed" (read-string "#?[:clj :a :default nil]")))
    (is (thrown-with-msg? RuntimeException #"Reader conditional splicing not allowed at the top level" (read-string {:read-cond :allow} "#?@(:clj [1 2])")))
    (is (thrown-with-msg? RuntimeException #"Reader conditional splicing not allowed at the top level" (read-string {:read-cond :allow} "#?@(:clj [1])")))
    (is (thrown-with-msg? RuntimeException #"Reader conditional splicing not allowed at the top level" (read-string {:read-cond :allow} "#?@(:clj []) 1"))))
  (testing "clj-1698-regression"
    (let [opts {:features #{:clj} :read-cond :allow}]
      (is (= 1 (read-string opts "#?(:cljs {'a 1 'b 2} :clj 1)")))
      (is (= 1 (read-string opts "#?(:cljs (let [{{b :b} :a {d :d} :c} {}]) :clj 1)")))
      (is (= '(def m {}) (read-string opts "(def m #?(:cljs ^{:a :b} {} :clj  ^{:a :b} {}))")))
      (is (= '(def m {}) (read-string opts "(def m #?(:cljs ^{:a :b} {} :clj ^{:a :b} {}))")))
      (is (= 1 (read-string opts "#?(:cljs {:a #_:b :c} :clj 1)")))))
  (testing "nil expressions"
    (is (nil? #?(:default nil)))
    (is (nil? #?(:foo :bar :clj nil)))
    (is (nil? #?(:clj nil :foo :bar)))
    (is (nil? #?(:foo :bar :default nil)))))

(deftest namespaced-map-errors
  (are [err msg form] (thrown-with-msg? err msg (read-string form))
                      Exception #"Invalid token" "#:::"
                      Exception #"Namespaced map literal must contain an even number of forms" "#:s{1}"
                      Exception #"Namespaced map must specify a valid namespace" "#:s/t{1 2}"
                      Exception #"Unknown auto-resolved namespace alias" "#::BOGUS{1 2}"
                      Exception #"Namespaced map must specify a namespace" "#: s{:a 1}"
                      Exception #"Duplicate key: :user/a" "#::{:a 1 :a 2}"
                      Exception #"Duplicate key: user/a" "#::{a 1 a 2}"))
clojure/core.async
;; The clojure.core.async namespace contains the public API.
(require '[clojure.core.async :as async :refer :all])

;; Data is transmitted on queue-like channels. By default channels
;; are unbuffered (0-length) - they require producer and consumer to
;; rendezvous for the transfer of a value through the channel.

;; In ordinary threads, we use `>!!` (blocking put) and `<!!`
;; (blocking take) to communicate via channels.

;; Here we convert our prior channel example to use go blocks:
(let [c (chan)]
  (go (>! c "hello"))
  (assert (= "hello" (<!! (go (<! c)))))
  (close! c))

;; Instead of the explicit thread and blocking call, we use a go block
;; for the producer. The consumer uses a go block to take, then
;; returns a result channel, from which we do a blocking take.

;; One killer feature for channels over queues is the ability to wait
;; on many channels at the same time (like a socket select). This is
;; done with `alts!!` (ordinary threads) or `alts!` in go blocks.

;; We can create a background thread with alts that combines inputs on
;; either of two channels. `alts!!` takes a set of operations
;; to perform - either a channel to take from or a [channel value] to put
;; and returns the value (nil for put) and channel that succeeded:

;; `timeout` creates a channel that waits for a specified ms, then closes:

;; We can combine timeout with `alts!` to do timed channel waits.
;; Here we wait for 100 ms for a value to arrive on the channel, then
;; give up:

;; Channels can also use custom buffers that have different policies
;; for the "full" case.  Two useful examples are provided in the API.
nextjournal/clerk
(ns viewers.controls
  "Demo of Clerk's two-way bindings."
  {:nextjournal.clerk/visibility {:code :show :result :show}}
  (:require [clojure.core :as core]
            [nextjournal.clerk :as clerk]
            [nextjournal.clerk.viewer :as viewer]))

;; We `defonce` an atom and tag it with `^::clerk/sync`. This will create a corresponding (reagent) atom in the browser.
^{::clerk/sync true}
(defonce number-atom
  (atom 0))

(def transform-var
  (comp clerk/mark-presented
        (clerk/update-val (fn [v] (viewer/->ViewerEval (list 'resolve (list 'quote (symbol v))))))))

(def render-text-input
  '(fn [state-atom]
     [:input {:type :text :value @state-atom :on-change #(swap! state-atom (constantly (.. % -target -value)))
              :class "px-3 py-3 placeholder-blueGray-300 text-blueGray-600 relative bg-white bg-white rounded text-sm border border-blueGray-300 outline-none focus:outline-none focus:ring w-full"}]))


^{::clerk/viewer {:render-fn (list 'comp render-slider 'deref) :transform-fn transform-var}}
#'number-atom

^{::clerk/viewer {:render-fn (list 'comp render-text-input 'deref) :transform-fn transform-var}}
#'name-atom

^{::clerk/viewer {:transform-fn transform-var
                  :render-fn '#(vector nextjournal.clerk.render/inspect @%)}}
#'number-atom

(def var-viewer
  {:pred var?
   :transform-fn transform-var
   :render-fn '(fn [x] [nextjournal.clerk.render/inspect @x])})

;; It might be more convenient to have a viewer that works on vars from defs and normal vars.

(def convenient-slider
  {:transform-fn (comp transform-var (clerk/update-val #(cond-> % (viewer/get-safe % ::clerk/var-from-def) ::clerk/var-from-def)))
   :render-fn '(fn [x] (let [state-atom (cond-> x (var? x) deref)]
                         [:input {:type :range :value @state-atom :on-change #(swap! state-atom (constantly (int (.. % -target -value))))}]))})
typedclojure/typedclojure
(ns ^:no-doc typed.clj.ext.clojure.core__reify
  "Typing rules clojure.core/reify"
  (:require [clojure.core.typed.internal :as internal]
            [typed.cljc.checker.check :as chk]
            [typed.cljc.analyzer :as ana2]
            [typed.cljc.checker.check.unanalyzed :refer [defuspecial]]))

;;======================
;; clojure.core/reify

(defuspecial defuspecial__reify
  "defuspecial implementation for clojure.core/reify"
  [{original-reify-form :form :as original-expr} expected]
  (-> original-expr
      ana2/analyze-outer
      ((fn [expr]
         {:pre [(= :unanalyzed (:op expr))]
          :post [(= :unanalyzed (:op %))]}
         (update expr :form (fn [form]
                              {:pre [(= 'reify* (first form))]}
                              (-> (list* (vary-meta (first form) assoc ::original-reify-expr original-expr)
                                         (rest form))
                                  (with-meta (meta form)))))))
      (chk/check-expr expected)))
Flexiana/framework
(ns xiana.interceptor.kebab-camel
  (:require
    [camel-snake-kebab.core :as csk]
    [camel-snake-kebab.extras :as cske]
    [clojure.core.memoize :as mem]))

(def request-type-params [:params :body-params :query-params :path-params :form-params :multipart-params])

(def camel-to-kebab
  (fn [resp]
    (cske/transform-keys
      (mem/fifo csk/->kebab-case {} :fifo/threshold 512) resp)))

(def kebab-to-camel
  (fn [resp]
    (cske/transform-keys
      (mem/fifo csk/->camelCase {} :fifo/threshold 512) resp)))

(def interceptor
  "The purpose is to make Js request compatible with clojure, and response compatible with Javascript.
  :request - {:params { "
  {:name  ::camel-to-kebab-case
   :enter (fn [state]
            (reduce
              (fn [state type-param]
                (update-in state [:request type-param] camel-to-kebab))
              state
              request-type-params))
   :leave (fn [state]
            (update-in state [:response :body] kebab-to-camel))})
bsless/more.async
(ns more.async.dataflow.node
  (:require
   [clojure.spec.alpha :as s]
   [clojure.core.async :as a]
   [more.async :as ma]
   [clojure.data]))

(s/def ::name (s/or :keyword keyword?
                    :string string?
                    :number number?
                    :symbol symbol?))

(defmulti ports ::type)

(doseq [t [::pipeline ::pipeline-blocking ::pipeline-async]]
  (defmethod ports t
    [{{to ::to from ::from} ::pipeline}]
    #{{::name from ::direction ::in}
      {::name to ::direction ::out}}))

(defmethod -compile ::batch
  [{{from ::from
     to ::to
     size ::size
     timeout ::timeout
     rf ::rf
     init ::init-fn
     finally ::finally-fn
     async? ::async?
     :or {rf conj init (constantly []) finally identity}}
    ::batch} env]
  (let [from (env from)
        to (env to)]
    (if async?
      (ma/batch! from to size timeout rf init finally)
      (a/thread (ma/batch!! from to size timeout rf init finally)))))

(defmethod ports ::batch
  [{{to ::to from ::from} ::batch}]
  #{{::name from ::direction ::in}
    {::name to ::direction ::out}})

(defmethod ports ::mult
  [{{to ::to from ::from} ::mult}]
  (into
   #{{::name from ::direction ::in}}
   (map (fn [to] {::name to ::direction ::out}))
   to))

(comment
  (s/explain-data
   ::mult
   {::from :in
    ::to* [:cbp-in :user-in]})
  (ports
   {::type ::mult
    ::name :cbm
    ::mult {::from :in ::to [:cbp-in :user-in]}}))

(defmethod ports ::pubsub
  [{{to ::sub from ::pub} ::pubsub}]
  (into
   #{{::name from
      ::direction ::in}}
   (map (fn [to] {::name to ::direction ::out}))
   to))

(defmethod ports ::produce
  [{{to ::to} ::produce}]
  #{{::name to ::direction ::out}})

(defmethod ports ::consume
  [{{from ::from} ::consume}]
  #{{::name from ::direction ::in}})

(defmethod ports ::split
  [{{to ::to-map from ::from} ::split}]
  (into
   #{{::name from ::direction ::in}}
   (map (fn [to] {::name to ::direction ::out}))
   (vals to)))

(defmethod ports ::reductions
  [{{to ::to from ::from} ::reductions}]
  #{{::name from ::direction ::in}
    {::name to ::direction ::out}})