Display Formated Code Attachments Snippet

Display Formated Code Attachments Snippet

This snippet displays all attachments for a page in formated form. One use case is for code examples page - attach a code example to a page and it is automatically displayed on the page. The file names are URLs to download the code. It works well when the file-names of the attachments are descriptive.

One possible extension would be to select language type based on the mime type of the attachment.

The following snippet is set to format attachments of Clojure code and is in XWiki 2.0 syntax (for something close in XWiki 1.0 syntax, see below):

{{velocity}}
#foreach( $attachment in $doc.getAttachmentList() )
* [[$attachment.getFilename()>>attach:$attachment.getFilename()]] :
{{code language=clojure}} $attachment.getContentAsString() {{/code}}
\\
#end
{{/velocity}}

(the spaces in above code are significant, they make attachments display with a nice gap between the blocks)

The XWiki syntax version 1.0 alternative (no highlighting for Clojure code):

#foreach( $attachment in $doc.getAttachmentList() )
* {attach:$attachment.getFilename()|file=$attachment.getFilename()} :
#set($my_content = $attachment.getContentAsString())
#set($codestart = "{CODE:none}")
$codestart.toLowerCase()
$my_content
#set($codeend = "{CODE}")
$codeend.toLowerCase()
\\
\\
#end

Example (result of 1.0 syntax code):

; parallel version of factorial
; no any guarantees for this code - it is a toy implementation and
; could be incorrect
; idea is to apply * in parallel to a set of ranges representing the number n
; n - calculate factorial of this number
; m - number of digits of n (used to partition the number)
; z - the whole part of n/m
; partitions number n which is long m decimal digits into ranges
; fixme: the m should be calculated from n but this way one can decide
;        on the number of partitions by hand
; also, the partitioning is not optimal (large number take longer to multiply)
(defn part-num [n m]
  (let [z (Math/floor (/ n m))
	last-range (range (+ (* z m) 1) (+ n 1))
	]
    (cons (if last-range last-range '(1))
	  (for [x (range m)]
	    (range (+ (* x z) 1) (+ (* (+ x 1) z) 1))
	    )
	  )
    )
  )
; the same argumets as part-num
; e.g. call (pfactorial 100000 6); takes around 5 seconds on core 2 duo
(defn pfactorial [n m]
  (let [agents (map agent (part-num n m))]
    (doseq [a agents]
      (send a #(apply * %)))
    (apply await agents)
    (let [result (apply * (map deref agents))]
      (doseq [a agents]
	(send a (fn [_] nil)))
      result)
    )
  )


* parallel-lorenz63-example.clj :
; lorenz 63 - equation integration by RK4
; each result set calculation happens in parallel
(import 
 '(java.awt Color Graphics Dimension)
 '(java.awt.image BufferedImage)
 '(java.io File)
 '(javax.imageio ImageIO)
 '(javax.swing JFrame JPanel)
 )
(def image-width 800)
(def image-height 600)
(def image-scale 10)
(def running true); set to false to stop the animation
(def animation-sleep-ms 4000)
; lorenz equation parameters
(def sigma 10)
(def r 28.1)
(def b 8/3)
; iteration parameters
(def h 1/1000) ; delta t
(def num-of-steps 20000)
(def num-of-sets 10) ; how many initial conditions + results to generate
; lorenz63 equations in RK4 form
; -> iterator: (fn [[x y z t]]) -> [x y z t] time h forward
(defn lorenz-step [sigma r b h]
  (fn [[x y z t]]
    [
     (let [k1 (* sigma (- y x))
	   k2 (* sigma (- y (+ x (* 1/2 h k1))))
	   k3 (* sigma (- y (+ x (* 1/2 h k2))))
	   k4 (* sigma (- y (+ x (* h k3))))]
       (+ x (* 1/6 h (+ k1 (* 2 k2) (* 2 k3) k4)))
       )
     (let [k1 (- (* x (- r z)) y)
	   k2 (- (* x (- r z)) (+ y (* 1/2 h k1)))
	   k3 (- (* x (- r z)) (+ y (* 1/2 h k2)))
	   k4 (- (* x (- r z)) (+ y (* h k3)))]
       (+ y (* 1/6 h (+ k1 (* 2 k2) (* 2 k3) k4)))
       )
     (let [k1 (- (* x y) (* b z))
	   k2 (- (* x y) (* b (+ z (* 1/2 h k1))))
	   k3 (- (* x y) (* b (+ z (* 1/2 h k2))))
	   k4 (- (* x y) (* b (+ z (* h k3))))]
       (+ z (* 1/6 h (+ k1 (* 2 k2) (* 2 k3) k4)))
       )
     (+ t h)
     ]
    )
  )
; will be called on array of initial conditions
(defn do-lorenz [[sigma r b h num-of-steps [x0 y0 z0 t0]]]
  (let [ls (lorenz-step sigma r b h)]
    (take num-of-steps (iterate ls [x0 y0 z0 t0]))))
; return function which generates random numbers in specified interval
(defn rnd-in-interval [[min max]]
     (fn []
       (let [delta (- max min)]
         (+ min (rand delta))
         )
       )
     )
(def random-number (rnd-in-interval [-15 15]))
; -> function producing [] of starting parameters for do-lorenz
(defn start-parameters-maker [sigma r b h num-of-steps]
  (fn []
    [sigma r b h num-of-steps [(random-number) (random-number) (random-number) 0]]))
(def start-parameters (take num-of-sets
			    (repeatedly
			     (start-parameters-maker sigma r b h num-of-steps))))
; -> list of calculated sequences (calculation happens in parallel)
(defn do-all-lorenz []
  (let [agents (map agent (map do-lorenz start-parameters))]
    (doseq [a agents]
      (send a doall)) ; doall forces the calculation in agent
    (apply await agents)
    (let [results (into [] (map deref agents))]
      (doseq [a agents]
	; needed so repeated calls to do-all-lorens do not leak memory
	(send a (fn [_] nil)))
      results
      )
    )
  )
(def results [[[0 0 0 0]]]) ; needed so the animator can be defined
(def result (ref [])) ; needed so the render can get defined
; renders result
(defn render [#^Graphics g]
     (let [width image-width height image-height scale image-scale
	   image (new BufferedImage width height BufferedImage/TYPE_INT_ARGB)
	   bg (.getGraphics image)]
       (.setColor bg (new Color 0 0 0))
       (.fillRect bg 0 0 (.getWidth image) (.getHeight image))
       (doseq [l @result]
	 (.setColor bg (new Color 255 255 0))
	 (.drawRect bg (+ (/ width 2) (* scale (first l))) (+ (/ height 2) (* scale (second l))) 0 0)
	 )
       (.drawImage g image 0 0 nil)
       (.dispose bg)))
(def panel (doto (proxy [JPanel] []
	     (paint [g] (render g)))
	     (.setPreferredSize (Dimension. image-width image-height))))
(def frame (doto (JFrame.) (.add panel) .pack .show))
(def animator (agent 0)) ; holds index to currently rendered result
(defn animation [current]
  (when running
    (send-off *agent* #'animation) ; infinite loop, *agent* is current agent
    (dosync (alter result (fn [_] (nth results current))))
    (.setTitle frame (str
		      "lorenz63 ["
		      (.toString current)
		      "]: "
		      (.toString (first @result))))
    (.repaint panel)
    (Thread/sleep animation-sleep-ms))
  (if (< current (dec (count results))) (inc current) 0)
  )
(comment
(load-file "parallel-lorenz63.clj")
(def results (do-all-lorenz))
(send-off animator animation)
)


Tags:
Created by Vladimir Konrad on 2009/05/05 11:12
Last modified by Sergiu Dumitriu on 2009/06/04 18:50

This wiki is licensed under a Creative Commons license
2.2.1.27354