Created
August 15, 2012 13:59
-
-
Save narkisr/3360382 to your computer and use it in GitHub Desktop.
Using Noir and incanter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns simple_server | |
(:gen-class) | |
(:use [noir.server :only (start load-views)]) | |
) | |
(load-views "src/simple_web_app") | |
(defn -main [& m] | |
(let [port (Integer. (get (System/getenv) "PORT" "8080"))] | |
(start port {:mode :dev :ns 'stats-web}))) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# an updated version of http://data-sorcery.org/2009/11/29/incanter-webapp/ | |
(ns simple_web_app | |
(:use | |
[noir.response :only (content-type)] | |
[noir.core :only (defpage)] | |
hiccup.core | |
hiccup.form-helpers | |
[incanter core stats charts]) | |
(:import (java.io ByteArrayOutputStream | |
ByteArrayInputStream))) | |
;; Pass a map as the first argument to be | |
;; set as attributes of the element | |
(defn html-doc | |
[title & body] | |
(html | |
[:html | |
[:head | |
[:title title]] | |
[:body | |
[:div | |
[:h2 | |
[:a {:href "/"} | |
"Generate a normal sample"]]] | |
body]])) | |
(def sample-form | |
(html-doc "sample-normal histogram" | |
(form-to [:post "/sample-normal"] | |
"sample size: " (text-field {:size 4} :size) | |
"mean: " (text-field {:size 4} :mean) | |
"sd: " (text-field {:size 4} :sd) | |
(submit-button "view")))) | |
(defn gen-samp-hist-png | |
[size-str mean-str sd-str] | |
(let [size (if (nil? size-str) 1000 (Integer/parseInt size-str)) | |
m (if (nil? mean-str) 0 (Double/parseDouble mean-str)) | |
s (if (nil? sd-str) 1 (Double/parseDouble sd-str)) | |
samp (sample-normal size :mean m :sd s) | |
chart (histogram samp :title "Normal Sample" | |
:x-label (str "sample-size = " size | |
", mean = " m | |
", sd = " s)) | |
out-stream (ByteArrayOutputStream.) | |
in-stream (do | |
(save chart out-stream) | |
(ByteArrayInputStream. | |
(.toByteArray out-stream))) | |
header {:status 200 :headers {"Content-Type" "image/png"}}] | |
{:headers {"Content-Type" "image/png"} :body in-stream} | |
)) | |
(defpage "/" [] sample-form) | |
(defpage [:post "/sample-normal"] {:as params} | |
(gen-samp-hist-png (params :size) (params :mean) (params :sd))) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment