Back

pp (clj)

(source)

macro

(pp)
A convenience macro that pretty prints the last thing output. This is exactly equivalent to (pprint *1).

Examples

clojure
(ns clojure.test-clojure.printer
  (:use clojure.test
        [clojure.test-helper :only [platform-newlines]])
  (:require [clojure.pprint :refer [pprint]]))

(deftest print-ns-maps
  (are [m s-on pp-on s-off]
    (and (= s-on (binding [*print-namespace-maps* true] (pr-str m)))
      (= (platform-newlines pp-on) (binding [*print-namespace-maps* true] (with-out-str (pprint m))))
      (= s-off (binding [*print-namespace-maps* false] (pr-str m))))
    {} "{}" "{}\n" "{}"
    {:a 1, :b 2} "{:a 1, :b 2}" "{:a 1, :b 2}\n" "{:a 1, :b 2}"
    {:user/a 1} "#:user{:a 1}" "#:user{:a 1}\n" "{:user/a 1}"
    {:user/a 1, :user/b 2} "#:user{:a 1, :b 2}" "#:user{:a 1, :b 2}\n" "{:user/a 1, :user/b 2}"
    {:user/a 1, :b 2} "{:user/a 1, :b 2}" "{:user/a 1, :b 2}\n" "{:user/a 1, :b 2}"
    {:user/a 1, 'user/b 2} "#:user{:a 1, b 2}" "#:user{:a 1, b 2}\n" "{:user/a 1, user/b 2}"
    {:user/a 1, :foo/b 2} "{:user/a 1, :foo/b 2}" "{:user/a 1, :foo/b 2}\n" "{:user/a 1, :foo/b 2}"
clojure
  "(ns autodoc.build-html
  \"This is the namespace that builds the HTML pages themselves.
It is implemented with a number of custom enlive templates.\"
  {:skip-wiki true, :author \"Tom Faulhaber\"}
  (:refer-clojure :exclude [empty complement])
  (:import [java.util.jar JarFile]
           [java.io File FileWriter BufferedWriter StringReader
                    BufferedInputStream BufferedOutputStream
                    ByteArrayOutputStream FileReader FileInputStream]
           [java.util.regex Pattern])
  (:require [clojure.string :as str])
  (:use [net.cgrand.enlive-html :exclude (deftemplate)]
        [clojure.java.io :only (as-file file writer)]
        [clojure.java.shell :only (sh)]
        [clojure.pprint :only (pprint cl-format pprint-ident
                               pprint-logical-block set-pprint-dispatch
                               get-pretty-writer fresh-line)]
        [clojure.data.json :only (pprint-json)]
        [autodoc.collect-info :only (contrib-info)]
        [autodoc.params :only (params expand-classpath)])
  (:use clojure.set clojure.java.io clojure.data clojure.java.browse
        clojure.inspector clojure.zip clojure.stacktrace))")

(defn tst-pprint
  "A helper function to pprint to a string with a restricted right margin"
  [right-margin obj]
  (binding [*print-right-margin* right-margin
            *print-pretty* true]
    (write obj :stream nil)))

;;; A bunch of predefined data to print
(def future-filled (future-call (fn [] 100)))
@future-filled
(def future-unfilled (future-call (fn [] (.acquire (java.util.concurrent.Semaphore. 0)))))
(def promise-filled (promise))
(deliver promise-filled '(first second third))
(def promise-unfilled (promise))
(def basic-agent (agent '(first second third)))
(def basic-atom (atom '(first second third)))
(def basic-ref (ref '(first second third)))
(def delay-forced (delay '(first second third)))
(force delay-forced)
(def delay-unforced (delay '(first second third)))
(defrecord pprint-test-rec [a b c])

(simple-tests pprint-datastructures-tests
 (tst-pprint 20 future-filled) #"#<Future@[0-9a-f]+: \r?\n  100>"
 (tst-pprint 20 future-unfilled) #"#<Future@[0-9a-f]+: \r?\n  :pending>"
 (tst-pprint 20 promise-filled) #"#<Promise@[0-9a-f]+: \r?\n  \(first\r?\n   second\r?\n   third\)>"
 ;; This hangs currently, cause we can't figure out whether a promise is filled
 ;;(tst-pprint 20 promise-unfilled) #"#<Promise@[0-9a-f]+: \r?\n  :pending>"
 (tst-pprint 20 basic-agent) #"#<Agent@[0-9a-f]+: \r?\n  \(first\r?\n   second\r?\n   third\)>"
 (tst-pprint 20 basic-atom) #"#<Atom@[0-9a-f]+: \r?\n  \(first\r?\n   second\r?\n   third\r?\)>"
 (tst-pprint 20 basic-ref) #"#<Ref@[0-9a-f]+: \r?\n  \(first\r?\n   second\r?\n   third\)>"
 (tst-pprint 20 delay-forced) #"#<Delay@[0-9a-f]+: \r?\n  \(first\r?\n   second\r?\n   third\)>"
 ;; Currently no way not to force the delay
 ;;(tst-pprint 20 delay-unforced) #"#<Delay@[0-9a-f]+: \n  :pending>"
 (tst-pprint 20 (pprint-test-rec. 'first 'second 'third)) "{:a first,\n :b second,\n :c third}"

 ;; basic java arrays: fails owing to assembla ticket #346
 ;;(tst-pprint 10 (int-array (range 7))) "[0,\n 1,\n 2,\n 3,\n 4,\n 5,\n 6]"
 (tst-pprint 15 (reduce conj clojure.lang.PersistentQueue/EMPTY (range 10)))
 "<-(0\n   1\n   2\n   3\n   4\n   5\n   6\n   7\n   8\n   9)-<"
 )

(defmethod test-dispatch true [avec]
  (pprint-logical-block :prefix "[" :suffix "]"
    (loop [aseq (seq avec)]
      (when aseq
	(write-out (first aseq))
	(when (next aseq)
	  (.write ^java.io.Writer *out* " ")
	  (pprint-newline :linear)
	  (recur (next aseq)))))))

(simple-tests dispatch-tests
  (with-pprint-dispatch test-dispatch
    (with-out-str 
      (pprint '("hello" "there"))))
  "[\"hello\" \"there\"]\n"
)

(simple-tests print-length-tests
  (binding [*print-length* 1] (with-out-str (pprint '(a b c d e f))))
  "(a ...)\n"
  (binding [*print-length* 2] (with-out-str (pprint '(a b c d e f))))
  "(a b ...)\n"
  (binding [*print-length* 6] (with-out-str (pprint '(a b c d e f))))
  "(a b c d e f)\n"
  (binding [*print-length* 8] (with-out-str (pprint '(a b c d e f))))
  "(a b c d e f)\n"

  (binding [*print-length* 1] (with-out-str (pprint [1 2 3 4 5 6])))
  "[1 ...]\n"
  (binding [*print-length* 2] (with-out-str (pprint [1 2 3 4 5 6])))
  "[1 2 ...]\n"
  (binding [*print-length* 6] (with-out-str (pprint [1 2 3 4 5 6])))
  "[1 2 3 4 5 6]\n"
  (binding [*print-length* 8] (with-out-str (pprint [1 2 3 4 5 6])))
  "[1 2 3 4 5 6]\n"

  (binding [*print-length* 1] (with-out-str (pprint (sorted-set 1 2 3 4 5 6))))
  "#{1 ...}\n"
  (binding [*print-length* 2] (with-out-str (pprint (sorted-set 1 2 3 4 5 6))))
  "#{1 2 ...}\n"
  (binding [*print-length* 6] (with-out-str (pprint (sorted-set 1 2 3 4 5 6))))
  "#{1 2 3 4 5 6}\n"
  (binding [*print-length* 8] (with-out-str (pprint (sorted-set 1 2 3 4 5 6))))
  "#{1 2 3 4 5 6}\n"

  (binding [*print-length* 1] (with-out-str (pprint (sorted-map 1 2, 3 4, 5 6, 7 8, 9 10, 11 12))))
  "{1 2, ...}\n"
  (binding [*print-length* 2] (with-out-str (pprint (sorted-map 1 2, 3 4, 5 6, 7 8, 9 10, 11 12))))
  "{1 2, 3 4, ...}\n"
  (binding [*print-length* 6] (with-out-str (pprint (sorted-map 1 2, 3 4, 5 6, 7 8, 9 10, 11 12))))
  "{1 2, 3 4, 5 6, 7 8, 9 10, 11 12}\n"
  (binding [*print-length* 8] (with-out-str (pprint (sorted-map 1 2, 3 4, 5 6, 7 8, 9 10, 11 12))))
  "{1 2, 3 4, 5 6, 7 8, 9 10, 11 12}\n"


  (binding [*print-length* 1] (with-out-str (pprint (int-array [1 2 3 4 5 6]))))
  "[1, ...]\n"
  (binding [*print-length* 2] (with-out-str (pprint (int-array [1 2 3 4 5 6]))))
  "[1, 2, ...]\n"
  (binding [*print-length* 6] (with-out-str (pprint (int-array [1 2 3 4 5 6]))))
  "[1, 2, 3, 4, 5, 6]\n"
  (binding [*print-length* 8] (with-out-str (pprint (int-array [1 2 3 4 5 6]))))
  "[1, 2, 3, 4, 5, 6]\n"
  )

(deftest test-flush-underlying-pprint
  []
  (let [[out flush-count-atom] (flush-alerting-writer (java.io.StringWriter.))]
    (binding [*out* out
              *flush-on-newline* true]
      (pprint (range 50))
      (pprint (range 50)))
    (is (= @flush-count-atom 2) "pprint flushes on newline")))

(deftest test-noflush-underlying-pprint
  []
  (let [[out flush-count-atom] (flush-alerting-writer (java.io.StringWriter.))]
    (binding [*out* out
              *flush-on-newline* nil]
      (pprint (range 50))
      (pprint (range 50)))
    (is (= @flush-count-atom 0) "pprint flushes on newline")))

(deftest test-pprint-calendar
  (let [calendar (doto (java.util.GregorianCalendar. 2014 3 29 14 0 0)
                   (.setTimeZone (java.util.TimeZone/getTimeZone "GMT")))
        calendar-str (with-out-str (pprint calendar))]
    (is (= (str/split-lines calendar-str)
           ["#inst \"2014-04-29T14:00:00.000+00:00\""])
        "calendar object pretty prints")))

(deftest test-print-meta
  (let [r (with-meta (range 24) {:b 2})]
    (are [expected val] (= (platform-newlines expected) (with-out-str (binding [*print-meta* true] (pprint val))))
      "^{:a 1, :b 2} {:x 1, :y 2}\n"
      ^{:a 1 :b 2} {:x 1 :y 2}
clojure
(ns clojure.test-clojure.pprint
  (:refer-clojure :exclude [format])
  (:require [clojure.string :as str])
  (:use [clojure.test :only (deftest is are run-tests)]
        [clojure.test-helper :only [platform-newlines]]
        clojure.test-clojure.pprint.test-helper
        clojure.pprint))

(load "pprint/test_cl_format")
(load "pprint/test_pretty")
clojure

(ns clojure.test-clojure.java-interop
  (:use clojure.test)
  (:require [clojure.data :as data]
            [clojure.inspector]
            [clojure.pprint :as pp]
            [clojure.set :as set]
            [clojure.test-clojure.proxy.examples :as proxy-examples])
  (:import java.util.Base64
           (java.util.concurrent.atomic AtomicLong AtomicInteger)))


(deftest test-dot
  ; (.instanceMember instance args*)
  (are [x] (= x "FRED")
      (.toUpperCase "fred") 
      (. "fred" toUpperCase)
      (. "fred" (toUpperCase)) )

;https://clojure.atlassian.net/browse/CLJ-1973
(deftest test-proxy-method-order
  (let [class-reader (clojure.asm.ClassReader. proxy-examples/proxy1-class-name)
        method-order (atom [])
        method-visitor (proxy [clojure.asm.ClassVisitor] [clojure.asm.Opcodes/ASM4 nil]
                         (visitMethod [access name descriptor signature exceptions]
                           (swap! method-order conj {:name name :descriptor descriptor})
                           nil))
        _ (.accept class-reader method-visitor 0)
        expected [{:name "<init>", :descriptor "()V"}
                  {:name "__initClojureFnMappings", :descriptor "(Lclojure/lang/IPersistentMap;)V"}
                  {:name "__updateClojureFnMappings", :descriptor "(Lclojure/lang/IPersistentMap;)V"}
                  {:name "__getClojureFnMappings", :descriptor "()Lclojure/lang/IPersistentMap;"}
                  {:name "clone", :descriptor "()Ljava/lang/Object;"}
                  {:name "hashCode", :descriptor "()I"}
                  {:name "toString", :descriptor "()Ljava/lang/String;"}
                  {:name "equals", :descriptor "(Ljava/lang/Object;)Z"}
                  {:name "a", :descriptor "(Ljava/io/File;)Z"}
                  {:name "a", :descriptor "(Ljava/lang/Boolean;)Ljava/lang/Object;"}
                  {:name "a", :descriptor "(Ljava/lang/Runnable;)Z"}
                  {:name "a", :descriptor "(Ljava/lang/String;)I"}
                  {:name "b", :descriptor "(Ljava/lang/String;)Ljava/lang/Object;"}
                  {:name "c", :descriptor "(Ljava/lang/String;)Ljava/lang/Object;"}
                  {:name "d", :descriptor "(Ljava/lang/String;)Ljava/lang/Object;"}
                  {:name "a", :descriptor "(Ljava/lang/Boolean;Ljava/lang/String;)I"}
                  {:name "a", :descriptor "(Ljava/lang/String;Ljava/io/File;)Z"}
                  {:name "a", :descriptor "(Ljava/lang/String;Ljava/lang/Runnable;)Z"}
                  {:name "a", :descriptor "(Ljava/lang/String;Ljava/lang/String;)I"}]
        actual @method-order]
    (is (= expected actual)
        (with-out-str (pp/pprint (data/diff expected actual))))))

;; http://dev.clojure.org/jira/browse/CLJ-1657
(deftest test-proxy-abstract-super
  (let [p (proxy [java.io.Writer] [])]
    (is (thrown? UnsupportedOperationException (.close p)))))

(defn queue [& contents]
  (apply conj (clojure.lang.PersistentQueue/EMPTY) contents))
logseq/logseq
(ns frontend.pubsub
  "All mults and pubs are collected to this ns.
  vars with suffix '-mult' is a/Mult, use a/tap and a/untap on them. used by event subscribers
  vars with suffix '-pub' is a/Pub, use a/sub and a/unsub on them. used by event subscribers
  vars with suffix '-ch' is chan used by event publishers."
  {:clj-kondo/config {:linters {:unresolved-symbol {:level :off}}}}
  #?(:cljs (:require-macros [frontend.pubsub :refer [def-mult-or-pub chan-of]]))
  (:require [clojure.core.async :as a :refer [chan mult pub]]
            [clojure.core.async.impl.protocols :as ap]
            [malli.core :as m]
            [malli.dev.pretty :as mdp]
            [clojure.pprint :as pp]))

(defmacro def-mult-or-pub
  "define following vars:
  - `symbol-name`-ch for event publisher.
  - `symbol-name`-mult or `symbol-name`-pub for event subscribers.
  - `symbol-name`-validator is malli schema validator
  def -pub var when `:topic-fn` exists otherwise -mult var"
  [symbol-name doc-string malli-schema & {:keys [ch-buffer topic-fn]
                                          :or   {ch-buffer 1}}]
  (let [schema-validator-name (symbol (str symbol-name "-validator"))
        schema-name           (symbol (str symbol-name "-schema"))
        ch-name               (symbol (str symbol-name "-ch"))
        mult-or-pub-name      (if topic-fn
                                (symbol (str symbol-name "-pub"))
                                (symbol (str symbol-name "-mult")))
        doc-string*           (str doc-string "\nMalli-schema:\n" (with-out-str (pp/pprint malli-schema)))]
    `(do
       (def ~schema-name ~malli-schema)
       (def ~schema-validator-name (m/validator ~malli-schema))
       (def ~ch-name ~doc-string* (chan-of ~malli-schema ~schema-validator-name ~ch-buffer))
       ~(if topic-fn
          `(def ~mult-or-pub-name ~doc-string* (pub ~ch-name ~topic-fn))
          `(def ~mult-or-pub-name ~doc-string* (mult ~ch-name))))))

(def-mult-or-pub app-wake-up-from-sleep
  "app wake up from sleep event"
  [:map
   [:last-activated-at :int]
   [:now :int]])
babashka/babashka
#!/usr/bin/env bb
(require '[babashka.classpath :refer [add-classpath]])
(require '[clojure.java.shell :refer [sh]])
(require '[clojure.pprint :refer [pprint]])

;; Print the configuration we just read in
(pprint conf)

;;=>
#_{:datomic {:url "CHANGE ME"}
   :aws {:access-key "AND ME"
         :secret-key "ME TOO"
         :region "FILL ME IN AS WELL"
         :visiblity-timeout-sec 30
         :max-conn 50
         :queue "cprop-dev"}
   :io {:http {:pool {:socket-timeout 600000
                      :conn-timeout :I-SHOULD-BE-A-NUMBER
                      :conn-req-timeout 600000
                      :max-total 200
                      :max-per-route :ME-ALSO}}}
   :other-things ["I am a vector and also like to place the substitute game"]}
(let [conf (load-config
            :file "cprop.edn"
            :merge [(from-props-file "cprop-override.properties")])]
  (pprint conf))
chr15m/sitefox
(ns update-deps
  (:require
    ["fs" :as fs]
    [clojure.edn :as edn]
    [clojure.pprint :refer [pprint]]))

(let [package (js/require "../package.json")
      js-deps (js->clj (aget package "dependencies"))
      deps (edn/read-string (fs/readFileSync "src/deps.cljs" "utf8"))
      deps-updated (assoc deps :npm-deps js-deps)]
  (binding [*print-fn* (fn [s]
                         (fs/writeFileSync "src/deps.cljs" s))]
    (pprint deps-updated)))
babashka/pod-registry
(require '[clojure.pprint :as pprint])

(pprint/pprint images)
clojure-finance/clojure-backtesting
(ns clojure-backtesting.examples.roc
  (:require [clojure-backtesting.data :refer :all]
            [clojure-backtesting.data-management :refer :all]
            [clojure-backtesting.portfolio :refer :all]
            [clojure-backtesting.order :refer :all]
            [clojure-backtesting.evaluate :refer :all]
            [clojure-backtesting.plot :refer :all]
            [clojure-backtesting.counter :refer :all]
            [clojure-backtesting.automation :refer :all]
            [clojure-backtesting.parameters :refer :all]
            [clojure-backtesting.indicators :refer :all]
            [clojure-backtesting.direct :refer :all]
            [clojure.string :as str]
            [clojure.java.io :as io]
            [clojure.pprint :as pprint]
  ) ;; require all libriaries from core
)
;; @@
;; =>
;;; {"type":"html","content":"<span class='clj-nil'>nil</span>","value":"nil"}
;; <=

;; **
;;; ### Rate of Change (ROC) strategy
;;; 
;;; ROC = (Closing price - Closing n periods ago) / Closing n periods ago * 100
;;; 
;;; We'll trade according to the following rules:
;;; - **Buy signal**: when ROC crosses the lower threshold (e.g. -30)
;;; - **Sell signal**: when ROC crosses the upper threshold (e.g. +30
;; **

;; @@
(def lower-threshold -30)
(def upper-threshold 30)
    
(while (< (compare (get-date) "1981-12-25") 0)
  (let [roc (* (ROC "14593" 10) 100)]
    (if (< roc lower-threshold)
      (order "14593" 1 :print false)) ; buy signal
    (if (> roc upper-threshold)
      (order "14593" -1 :print false))) ; sell signal
  (update-eval-report)
  (next-date))
(end-order)
;; @@
;; =>
;;; {"type":"html","content":"<span class='clj-unkown'>true</span>","value":"true"}
;; <=