Story ID: RPC-236 Wrong arrow lol!

Story ID: RPC-236
Wrong arrow lol!

--- test/untangled_spec/provided_spec.cljc
+++ test/untangled_spec/provided_spec.cljc
@@ -33,7 +33,7 @@
                              (assertions
                                (p/parse-arrow-count '=1x=>) => 1
                                (p/parse-arrow-count '=7=>) => 7
-                               (p/parse-arrow-count '=234x=>) -> 234
+                               (p/parse-arrow-count '=234x=>) => 234
                                )
                              )
                    ))
@@ -219,7 +219,6 @@
                                                (if true :val
                                                  (dont-call)) => :val))
                                    )
-
                          )

                (behavior "allows any number of trailing forms"


Fix typo.

Fix typo.

--- test/workshop/jobs/challenge_6_0_test.clj
+++ test/workshop/jobs/challenge_6_0_test.clj
@@ -18,7 +18,7 @@
 ;; tasks, only to fail later in the workflow. The segments would then pass
 ;; through your stateful tasks again. Even if Onyx didn't use this specific
 ;; technique for fault tolerance, this would be still be problematic because
-;; it is provably impossible execute a distributed instruction exactly once -
+;; it is provably impossible to execute a distributed instruction exactly once -
 ;; see the Two Generals problem for why this is the case.

 ;; Clearly, many computations need to have perfectly correct aggregate answers,


deftask inputs match defn

deftask inputs match defn

Allows use of doc-strings and metadata in the task definition

--- src/matross/tasks/core.clj
+++ src/matross/tasks/core.clj
@@ -11,15 +11,23 @@
 (defn task-result [succeeded? changed? data]
   (TaskResult. succeeded? changed? data))

-(defmacro deftask [type [conn config] & body]
-  `(do
-    (defn ~type [~conn ~config] ~@body)
+(defmacro deftask
+  "Define a function and register it's name as an implementation of the matross.tasks.core/get-task multimethod.

-    (defmethod matross.tasks.core/get-task (keyword '~type) [spec#]
-       (reify
-         matross.tasks.core/ITask
-         (exec [_# conn#]
-           (~type conn# spec#))))))
+The arguments are the same as `defn`. The only expectation is that the first argument will be bound to the IRun instance to opereate on and the second argument will be bound to the current configuration."
+
+  [& fdecl]
+
+  (let [type (first fdecl)
+        param_count (count (some #(if (vector? %1) %1) fdecl))]
+    `(do
+       (defn ~@fdecl)
+
+       (defmethod matross.tasks.core/get-task (keyword '~type) [spec#]
+         (reify
+           matross.tasks.core/ITask
+           (exec [_# conn#]
+             (~type conn# spec#)))))))

 (defn run-task [conn conf]
   (exec (get-task conf) conn))


Misc clojure cleanup

Misc clojure cleanup

--- src/metabase/api/slack.clj
+++ src/metabase/api/slack.clj
@@ -9,10 +9,11 @@
 (defendpoint PUT "/settings"
   "Update Slack related settings. You must be a superuser to do this."
   [:as {{slack-token :slack-token, metabot-enabled :metabot-enabled, :as slack-settings} :body}]
-  {metabot-enabled [Required]}
+  {slack-token     [NonEmptyString]
+   metabot-enabled [Required]}
   (check-superuser)
-  (if (not slack-token)
-    (setting/set-many! { :slack-token nil, :metabot-enabled false })
+  (if-not slack-token
+    (setting/set-many! {:slack-token nil, :metabot-enabled false})
     (try
       ;; just check that channels.list doesn't throw an exception (a.k.a. that the token works)
       (when-not config/is-test?
@@ -20,7 +21,6 @@
       (setting/set-many! slack-settings)
       {:ok true}
       (catch clojure.lang.ExceptionInfo info
-        {:status 400, :body (ex-data info)})))
-  )
+        {:status 400, :body (ex-data info)}))))

 (define-routes)


Fix arity mistake

Fix arity mistake

--- src/net/sekao/nightcode/projects.clj
+++ src/net/sekao/nightcode/projects.clj
@@ -126,7 +126,7 @@
         path)
       (getPane [pref-state-atom runtime-state-atom _]
         (let [pane (or (get-in @runtime-state-atom [:project-panes path])
-                       (home-pane @pref-state-atom))]
+                       (home-pane @pref-state-atom @runtime-state-atom))]
           (swap! runtime-state-atom update :project-panes assoc path pane)
           pane)))))


Fix build failure message

Fix build failure message

--- src/puppeteer/app/slackbot/alice.clj
+++ src/puppeteer/app/slackbot/alice.clj
@@ -85,7 +85,6 @@
 (defn- build-failure
   [{:keys [message-usecase build-usecase conf-usecase job-usecase]}
    m]
-  (println m)
   (let [job (get-job job-usecase (:id m))]
     (when job
       (message-usecase/send-build-failure-message
@@ -94,7 +93,7 @@
          :user-name (:user-name job)
          :repo-name (:repo-name job)
          :branch-name (:branch-name job)
-         :error-message (:logUrl job)}))))
+         :error-message (:logUrl m)}))))

 (defmulti reaction
   (fn [_ m] (:type m)))


schedule :check-sync outside callback (which can be not called after locking/unlocking phone)

--- src/status_im/protocol/handlers.cljs
+++ src/status_im/protocol/handlers.cljs
@@ -74,18 +74,17 @@
         (when (and (not= sync-data state) (= :in-progress new-state))
           (dispatch [:set :sync-data state]))
         (when (not= sync-state new-state)
-          (dispatch [:set :sync-state new-state]))
-        (let [timeout (if (#{:done :synced} new-state) 60 10)]
-          (s/execute-later #(dispatch [:check-sync]) (s/s->ms timeout)))))))
+          (dispatch [:set :sync-state new-state]))))))

 (register-handler :check-sync
   (u/side-effect!
     (fn [{:keys [web3] :as db}]
       (if web3
-        (.getSyncing
-          (.-eth web3)
-          (fn [error sync]
-            (dispatch [:update-sync-state error sync])))
+        (do (.getSyncing
+              (.-eth web3)
+              (fn [error sync]
+                (dispatch [:update-sync-state error sync])))
+            (s/execute-later #(dispatch [:check-sync]) (s/s->ms 10)))
         (s/execute-later #(dispatch [:check-sync]) (s/s->ms 10))))))

 (register-handler :initialize-sync-listener


Test for function system-banners

Test for function system-banners

--- test/emender_jenkins/rest_api_test.clj
+++ test/emender_jenkins/rest_api_test.clj
@@ -463,3 +463,15 @@
                      :hostname   "hostname"
                      :test       "/api"} "hostname")))))

+(deftest test-system-banners
+    "Check the function emender-jenkins.rest-api/system-banners."
+    (testing "the function emender-jenkins.rest-api/system-banners."
+        (with-redefs [send-response (fn [response request] response)]
+            (let [request {}]
+                (is (= (system-banners request "/api/system/banners")
+                    {:message    "Alpha version"
+                     :type       "Warning"}))
+                (is (= (system-banners request "/api/system/xxx")
+                    nil
+                    ))))))
+


Lerp velocity... in hopes of making it smoother.

--- src/videotest/coral/motion_seeds.clj
+++ src/videotest/coral/motion_seeds.clj
@@ -13,8 +13,10 @@
 (def SEED-CREATE-ODDS 0.4)

 (def SEED-X-VEL-BOUND 20.0)
-(def SEED-Y-VEL-BOUND-MIN 5.0)
-(def SEED-Y-VEL-BOUND-MAX 20.0)
+;; (def SEED-Y-VEL-BOUND-MIN 5.0)
+;; (def SEED-Y-VEL-BOUND-MAX 20.0)
+(def SEED-Y-VEL-BOUND-MIN 2.0)
+(def SEED-Y-VEL-BOUND-MAX 15.0)

 (defn seed-created? []
@@ -22,7 +24,15 @@

 (defn init-motion-seed [rgb-in-mat hsv-out-mat x y rgba]
   (let [hsva (color/rgba->hsva rgb-in-mat hsv-out-mat rgba)]
-    {:x x :y y :color-rgba rgba :color-hsva hsva}))
+    {:x x :y y :color-rgba rgba :color-hsva hsva
+     :velocity [(q/map-range (rand)
+                             0.0 1.0
+                             (- SEED-X-VEL-BOUND)
+                             SEED-X-VEL-BOUND)
+                (q/map-range (rand)
+                             0.0 1.0
+                             SEED-Y-VEL-BOUND-MIN
+                             SEED-Y-VEL-BOUND-MAX)]}))

 (defn create-motion-seeds [bin-size {:keys [motion-trace motion-seeds color-record] :as state}]
   (let [rgb-in-mat (color/single-three-dim-color-mat)
@@ -46,24 +56,30 @@
       (> 0 (+ seed-w) x)
       (< display-w (- x seed-w))))

+(def SEED-VELOCITY-LERP 0.5)
+
 (defn move-motion-seeds [display-w display-h {:keys [motion-seeds] :as state}]
   (let [reduce-seed
-        (fn [memo {:keys [x y] :as seed}]
+        (fn [memo {:keys [x y velocity] :as seed}]
           (let [p-noise (pnoise/xy->perlin x y)
-                x (+ x
-                     (pnoise/perlin->range p-noise
-                                           (- SEED-X-VEL-BOUND)
-                                           SEED-X-VEL-BOUND))
-                y (+ y
-                     (pnoise/perlin->range p-noise
-                                           SEED-Y-VEL-BOUND-MIN
-                                           SEED-Y-VEL-BOUND-MAX))]
+                [vx vy] velocity
+                target-vx (pnoise/perlin->range p-noise
+                                                (- SEED-X-VEL-BOUND)
+                                                SEED-X-VEL-BOUND)
+                target-vy (pnoise/perlin->range p-noise
+                                                SEED-Y-VEL-BOUND-MIN
+                                                SEED-Y-VEL-BOUND-MAX)
+                lerp-vx (q/lerp vx target-vx SEED-VELOCITY-LERP)
+                lerp-vy (q/lerp vy target-vy SEED-VELOCITY-LERP)
+                x (+ x lerp-vx)
+                y (+ y lerp-vy)]
             (if (out-of-bounds? SEED-W display-w display-h x y)
               memo
               (conj memo (-> seed
                              (assoc-in [:p-noise] p-noise)
                              (assoc-in [:x] x)
-                             (assoc-in [:y] y))))))]
+                             (assoc-in [:y] y)
+                             (assoc-in [:velocity] [lerp-vx lerp-vy]))))))]
     (assoc-in state [:motion-seeds]
               (reduce reduce-seed
                       []


Fix stuuupid error in the 'alia/execute-chan' call

--- src/whisper2cyanite/metric_store.clj
+++ src/whisper2cyanite/metric_store.clj
@@ -69,6 +69,7 @@
                               (when run
                                 (async/take!
                                  (alia/execute-chan session
+                                                    query
                                                     {:consistency :any})
                                  (fn [rows-or-e]
                                    (if (instance? Throwable rows-or-e)


Adding a (status) alias for (server-status).

* old habits die hard ;-)

--- src/overtone/sc/server.clj
+++ src/overtone/sc/server.clj
@@ -147,6 +147,8 @@
           :timeout)))
     :disconnected))

+(def status server-status)
+
 (defn clear-msg-queue
   "Remove any scheduled OSC messages from the run queue."
   []


Resort to code eval

Resort to code eval

* Prints spurious warnings around plack.core namespaces and
  the planck.core/print-error var

* Obscure-for--user result if *e is blank:
    `undefined is not an object (evaluating 'error.cause')`

--- planck-cljs/src/planck/core.cljs
+++ planck-cljs/src/planck/core.cljs
@@ -204,9 +204,10 @@
                   (repl/print-doc
                     (let [sym (second expression-form)]
                           (with-compiler-env st (resolve env sym)))))
-            pst (let [sym (or (-> expression-form second second) '*e)
-                      err (with-compiler-env st (resolve env sym))]
-                  (print-error err)))
+            pst (let [sym (or (second expression-form) '*e)]
+                  (read-eval-print (str "(planck.core/print-error " sym ")")
+                                   expression?
+                                   false)))
           (prn nil))
         (try
           (cljs/eval-str


making the failing step in todopipeline really fail

--- src/todopipeline/steps.clj
+++ src/todopipeline/steps.clj
@@ -40,7 +40,7 @@
   (shell/bash cwd "./deploy-frontend.sh frontend_ci /tmp/mockrepo/client-snapshot.tar.gz"))

 (defn some-failing-step [& _]
-  (shell/bash "/" "echo 'i am going to fail now...'" "exit 1"))
+  (shell/bash "/" "echo \"i am going to fail now...\"" "exit 1"))

 (defn some-step-that-cant-be-reached [& _]
   {:status :success})


(SERVER-208) Improve error message for missing `puppet-admin` section

This commit improves the error message for a missing `puppet-admin`
section in the Trapperkeeper configuration at startup.

--- src/clj/puppetlabs/services/puppet_admin/puppet_admin_core.clj
+++ src/clj/puppetlabs/services/puppet_admin/puppet_admin_core.clj
@@ -72,7 +72,11 @@
   "Given the full Puppet Server config map, extract and return the settings for
   the Puppet Admin web service."
   [config]
-  (:puppet-admin config))
+  (if-let [settings (:puppet-admin config)]
+    settings
+    (throw (IllegalArgumentException.
+             (str "'puppet admin' section required but not found in "
+                  "configuration settings")))))

 (schema/defn ^:always-validate build-ring-handler :- IFn
   "Returns the ring handler for the Puppet Admin API."


Fix lock up

Fix lock up

--- planck-cljs/src/planck/repl.cljs
+++ planck-cljs/src/planck/repl.cljs
@@ -730,7 +730,8 @@

 (defn- compiling
   [m]
-  (if (:cache m)
+  (if (and (not (= :js (:lang m)))
+           (:cache m))
     (let [{:keys [source source-map]} (compile (assoc m
                                                  :sm-data @comp/*source-map-data*))]
       (when source-map


Turn on syntax highlighting in specs in doc output

--- planck-cljs/src/planck/repl.cljs
+++ planck-cljs/src/planck/repl.cljs
@@ -1166,12 +1166,11 @@

 (defn- format-spec
   [spec left-margin ns]
-  (let [raw-print (binding [theme (get-theme :plain)]
-                    (with-out-str (print-result (s/describe spec)
-                                    {::keyword-ns     ns
-                                     ::spec?          true
-                                     ::as-code?       true
-                                     ::term-width-adj (- left-margin)})))]
+  (let [raw-print (with-out-str (print-result (s/describe spec)
+                                  {::keyword-ns     ns
+                                   ::spec?          true
+                                   ::as-code?       true
+                                   ::term-width-adj (- left-margin)}))]
     (string/replace (str-butlast raw-print) #"\n"
       (apply str \newline (repeat left-margin " ")))))


Move current-ns up before first use

Move current-ns up before first use

Former-commit-id: 339ba1c38f5b7febaeb0ce907c654a34964c2806

--- planck-cljs/src/planck/repl.cljs
+++ planck-cljs/src/planck/repl.cljs
@@ -24,6 +24,8 @@

 (defonce st (cljs/empty-state))

+(defonce current-ns (atom 'cljs.user))
+
 (defn- known-namespaces
   []
   (keys (:cljs.analyzer/namespaces @st)))
@@ -54,8 +56,6 @@
     (transit-json->cljs (first (js/PLANCK_LOAD "cljs/core.cljs.cache.aot.json"))))
   (cljs/load-analysis-cache! st 'cljs.core$macros
     (transit-json->cljs (first (js/PLANCK_LOAD "cljs/core$macros.cljc.cache.json")))))
-
-(defonce current-ns (atom 'cljs.user))

 (defonce app-env (atom nil))


Fix bug in initializing *assert*

Fix bug in initializing *assert*

Fixes #398

--- planck-cljs/src/planck/repl.cljs
+++ planck-cljs/src/planck/repl.cljs
@@ -197,7 +197,7 @@

 (defn- setup-asserts [elide-asserts]
   (set! *assert* (not elide-asserts))
-  (swap! default-session-state assoc :*assert* elide-asserts))
+  (swap! default-session-state assoc :*assert* *assert*))

 (defn- ^:export init
   [repl verbose cache-path static-fns elide-asserts]


Improvements to completion candidates

Improvements to completion candidates

--- planck-cljs/src/planck/repl.cljs
+++ planck-cljs/src/planck/repl.cljs
@@ -65,12 +65,21 @@

 (defn- current-alias-map
   []
-  (get-in @st [::ana/namespaces @current-ns :requires]))
+  (->> (merge (get-in @st [::ana/namespaces @current-ns :requires])
+         (get-in @st [::ana/namespaces @current-ns :require-macros]))
+    (remove (fn [[k v]] (= k v)))
+    (into {})))

 (defn- all-ns
   "Returns a sequence of all namespaces."
   []
   (keys (::ana/namespaces @st)))
+
+(defn- drop-macros-suffix
+  [ns-name]
+  (if (s/ends-with? ns-name "$macros")
+    (apply str (drop-last 7 ns-name))
+    ns-name))

 (defn- get-namespace
   "Gets the AST for a given namespace."
@@ -375,12 +384,22 @@
    :gen-class
    :keywordize-keys])

+(defn- expand-typed-ns
+  "Expand the typed namespace symbol to a known namespace, consulting
+  current namespace aliases if necessary."
+  [typed-ns]
+  (or (get-in st [:cljs.analyzer/namespaces typed-ns :name])
+      (typed-ns (current-alias-map))
+      typed-ns))
+
 (defn- completion-candidates
-  [namespace-candidates top-form? typed-ns]
+  [top-form? typed-ns]
   (set (if typed-ns
-         (completion-candidates-for-ns (symbol typed-ns) false)
-         (concat namespace-candidates
+         (completion-candidates-for-ns (expand-typed-ns (symbol typed-ns)) false)
+         (concat
            (map str keyword-completions)
+           (map #(str (drop-macros-suffix (str %)) "/") (all-ns))
+           (map #(str % "/") (keys (current-alias-map)))
            (completion-candidates-for-ns 'cljs.core false)
            (completion-candidates-for-ns 'cljs.core$macros false)
            (completion-candidates-for-ns @current-ns true)
@@ -391,17 +410,16 @@

 (defn- ^:export get-completions
   [buffer]
-  (let [namespace-candidates (map str (all-ns))
-        top-form?            (re-find #"^\s*\(\s*[^()\s]*$" buffer)
-        typed-ns             (second (re-find #"(\b[a-zA-Z-.]+)/[a-zA-Z-]+$" buffer))]
-    (let [buffer-match-suffix (re-find #":?[a-zA-Z-]*$" buffer)
+  (let [top-form?            (re-find #"^\s*\(\s*[^()\s]*$" buffer)
+        typed-ns             (second (re-find #"\(+(\b[a-zA-Z-.]+)/[a-zA-Z-]+$" buffer))]
+    (let [buffer-match-suffix (re-find #":?[a-zA-Z-\.]*$" buffer)
           buffer-prefix       (subs buffer 0 (- (count buffer) (count buffer-match-suffix)))]
       (clj->js (if (= "" buffer-match-suffix)
                  []
                  (map #(str buffer-prefix %)
                    (sort
                      (filter (partial is-completion? buffer-match-suffix)
-                       (completion-candidates namespace-candidates top-form? typed-ns)))))))))
+                       (completion-candidates top-form? typed-ns)))))))))

 (defn- is-completely-readable?
   [source]
@@ -953,10 +971,7 @@
                    #(re-find str-or-pattern (str %))
                    #(s/includes? (str %) (str str-or-pattern)))]
     (sort (mapcat (fn [ns]
-                    (let [ns-name (str ns)
-                          ns-name (if (s/ends-with? ns-name "$macros")
-                                    (apply str (drop-last 7 ns-name))
-                                    ns-name)]
+                    (let [ns-name (drop-macros-suffix (str ns))]
                       (map #(symbol ns-name (str %))
                         (filter matches? (public-syms ns)))))
             (all-ns)))))


add missing reason to failing test (#310)

--- scheduler/test/cook/test/mesos/unscheduled.clj
+++ scheduler/test/cook/test/mesos/unscheduled.clj
@@ -72,7 +72,7 @@

 (deftest test-reasons
   (let [conn (restore-fresh-database! datomic-uri)
-        _ (quota/set-quota! conn "mforsyth" :count 2)
+        _ (quota/set-quota! conn "mforsyth" "test-reasons" :count 2)
         running-job-id1 (-> (create-dummy-job conn :user "mforsyth"
                                               :ncpus 1.0 :memory 3.0
                                               :job-state :job.state/running))


Bugfix: Multiple players

Bugfix: Multiple players

--- desktop/src-common/brain_gain_or_drain/screens/game.clj
+++ desktop/src-common/brain_gain_or_drain/screens/game.clj
@@ -46,11 +46,11 @@
       (letfn [(recreate-entity-on-screen [entity]
                 (recreate-entity entity (width screen) (height screen)))
               (eaten-by-players? [entity]
-                (some #([player] (eaten-by? player entity)) players))]
+                (some (fn [player] (eaten-by? player entity)) players))]
         (->> entities
              (move-entities (:delta-time screen) (game-input!))
              (when-entity gone? recreate-entity-on-screen)
-             (when-entity eaten-by-player? recreate-entity-on-screen)
+             (when-entity eaten-by-players? recreate-entity-on-screen)
              (render! screen)))))

   :on-resize


Fleshed out the plan overview page more.

Conflicts:
	src-cljs/frontend/components/org_settings.cljs

--- src-cljs/frontend/components/org_settings.cljs
+++ src-cljs/frontend/components/org_settings.cljs
@@ -881,14 +881,24 @@
       [:div
        [:fieldset [:legend (str org-name "'s plan")]]
        [:div.explanation
+        (when (pm/piggieback? plan org-name)
+          [:p "This organization's projects will build under "
+           [:a {:href (routes/v1-org-settings {:org (:org_name plan)})}
+            (:org_name plan) "'s plan."]])
         [:p
-         (str "Your builds will be distributed across " (pm/usable-containers plan) " containers.")]
+         (str "Builds will be distributed across " (pm/usable-containers plan) " containers.")]
         (when (pm/paid? plan)
           [:p
            (str (pm/paid-containers plan) " of these are paid, at $" (pm/stripe-cost plan) "/month. ")
-           "You can "
-           [:a {:href "#containers"} "add more"]
-           " at $" container-cost " per container  for more parallelism and shorter queue times."])
+           (when (pm/admin? plan)
+             (list
+              "You can "
+              ;; make sure to link to the add-containers page of the plan's org,
+              ;; in case of piggiebacking.
+              [:a {:href (routes/v1-org-settings-subpage {:org (:org_name plan)
+                                                          :subpage "add-containers"})}
+               "add more"]
+              " at $" container-cost " per container for more parallelism and shorter queue times."))])
         (when  (pm/freemium? plan)
           [:p (str (pm/freemium-containers plan) " container is free, forever.")])
         [:p "Additionally, projects that are public on GitHub will build with " pm/oss-containers " extra containers -- our gift to free and open source software."]]]))))


Fix transformation-test

Fix transformation-test

--- backend/test/akvo/lumen/lib/transformation_test.clj
+++ backend/test/akvo/lumen/lib/transformation_test.clj
@@ -583,12 +583,12 @@
                                            :data         target-data})
         apply-transformation (partial async-tx-apply {:tenant-conn *tenant-conn*} origin-dataset-id)
         tx                   (gen-transformation "core/merge-datasets"
-                                                 {::transformation.merge-datasets.source.s/datasetId            target-dataset-id
-                                                  ::transformation.merge-datasets.source.s/mergeColumn          "c1"
+                                                 {::transformation.merge-datasets.source.s/mergeColumn          "c1"
                                                   ::transformation.merge-datasets.source.s/aggregationDirection "DESC"
                                                   ::transformation.merge-datasets.source.s/mergeColumns         ["c4" "c3" "c2"]
                                                   ::transformation.merge-datasets.target.s/mergeColumn          "c1"}
-                                                 [:source :aggregationColumn] nil)
+                                                 [:source :aggregationColumn] nil
+                                                 [:source :datasetId] target-dataset-id)
         [tag _ :as res] (apply-transformation {:type           :transformation
                                                :transformation tx})]
     (is (= ::lib/ok tag))


added a table test

added a table test

--- test/cassidy/core_test.clj
+++ test/cassidy/core_test.clj
@@ -2,7 +2,8 @@
   (:require [clojure.test :refer :all]
             [cassidy.shon :as shon]
             [hiccup.core :refer [html]]
-            [clojure.pprint :refer [pprint]])
+            [clojure.pprint :refer [pprint]]
+            [cassidy.extensions :refer :all])
   (:import [java.util.concurrent.atomic AtomicLong AtomicInteger]
            [java.net URL URI]))

@@ -135,3 +136,10 @@
       (shon/pprint m)
       ;; Take a look
       (spit (java.io.File. "resources/testcustomshon.html") (shon/wrap-in-page m)))))
+
+(deftest write-a-table
+  (testing "create a table"
+    (let [t [{:col1 "string" :col2 3 :col3 (->Link "http://www.google.com" "Google" nil)}
+             {:col1 "zing" :col2 5 :col3 "amen"}]
+          tab (->Table t "caption" nil)]
+      (spit (java.io.File. "resources/testshontable.html") (shon/wrap-in-page tab)))))


(PE-6875) Bump trapperkeeper-ws-jetty9 to 1.0.1.

--- configs/pe-console-services/pe-console-services.clj
+++ configs/pe-console-services/pe-console-services.clj
@@ -7,7 +7,7 @@
                  [puppetlabs/rbac-ui "{{{pe-rbac-ui-version}}}"]
                  [puppetlabs/pe-activity-service "{{{pe-activity-service-version}}}"]
                  [puppetlabs/pe-trapperkeeper-proxy "{{{pe-trapperkeeper-proxy-version}}}"]
-                 [puppetlabs/trapperkeeper-webserver-jetty9 "0.9.0"]
+                 [puppetlabs/trapperkeeper-webserver-jetty9 "1.0.1"]
                  ;; There is a bug in leiningen that forces us to
                  ;; explicitly reference nrepl if we want it to be
                  ;; included in the uberjar.


Fixed tests to reflect use of original value when entered value is invalid.

--- test/re-com/time_test.cljs
+++ test/re-com/time_test.cljs
@@ -94,13 +94,14 @@

 (deftest test-validated-time-integer
   (are [expected actual] (= expected actual)
-    600   (time/validated-time-integer 600 0 2359)
-    630   (time/validated-time-integer 630 0 2359)
-    nil   (time/validated-time-integer 2230 0 2210)
-    2359  (time/validated-time-integer 2359 0 2359)
-    1500  (time/validated-time-integer 1575 600 2200)    ;; invalid minutes
-    nil   (time/validated-time-integer 500 600 2200)     ;; Too early
-    nil   (time/validated-time-integer 2315 600 2200)))  ;; Too late
+    600   (time/validated-time-integer 600 0 2359 nil)
+    630   (time/validated-time-integer 630 0 2359 nil)
+    nil   (time/validated-time-integer 2230 0 2210 nil)
+    2359  (time/validated-time-integer 2359 0 2359 nil)
+    nil   (time/validated-time-integer 1575 600 2200 nil)    ;; invalid minutes - returns nil because no previous value provided
+    1500  (time/validated-time-integer 1575 600 2200 1500)   ;; invalid minutes - returns 1500 because that was previous value provided
+    nil   (time/validated-time-integer 500 600 2200 nil)     ;; Too early
+    nil   (time/validated-time-integer 2315 600 2200 nil)))  ;; Too late

 (deftest test-validate-time-range
   (are [expected actual] (= expected actual)


update core test for new append and register

update core test for new append and register

--- test/riemann/core_test.clj
+++ test/riemann/core_test.clj
@@ -181,7 +181,7 @@
                         (is (= final @old-core)))))))

 (deftest serialization
-         (let [out (ref [])
+         (let [out (atom [])
                server (riemann.transport.tcp/tcp-server)
                stream (riemann.streams/append out)
                core   (logging/suppress ["riemann.transport.tcp"
@@ -308,7 +308,7 @@
                         :state "expired"}))))

 (deftest percentiles
-         (let [out (ref [])
+         (let [out (atom [])
                server (riemann.transport.tcp/tcp-server)
                stream (riemann.streams/percentiles 1 [0 0.5 0.95 0.99 1]
                                                  (riemann.streams/append out))


links to hangouts sessions

links to hangouts sessions

--- src/cljs/work_sessions/components/headers.cljs
+++ src/cljs/work_sessions/components/headers.cljs
@@ -138,7 +138,7 @@
                      [:div.details.schedule
                       #_[:hr]
                       [:h4.time-and-place
-                       [:a {:href "https://hangouts.google.com/hangouts/_/ld3v6bbvfrenjdl26pkiqdamoee"
+                       [:a {:href "http://sws.eeefff.org/session"
                             :target "blank"}
                         (unescapeEntities "Session #1")]
                        (gstring/unescapeEntities ": 26 May, 13:30 — 14:30 Helsinki time")]


Removed a function that should have been removed in commit 22ce586f736684643a96a70d3b48f922015fb242

--- src/clojush/problems/software/even_squares.clj
+++ src/clojush/problems/software/even_squares.clj
@@ -131,21 +131,6 @@
     (println (format "Test Case: %3d | Input/Output: %s" i (str case))))
   (println ";;******************************"))

-; Define error function. For now, each run uses different random inputs
-(defn even-squares-error-function
-  "Returns the error function for the Even Squares problem. Takes as
-   input Even Squares data domains."
-  [data-domains]
-  (let [[train-cases test-cases] (map #(sort-by first %)
-                                      (map even-squares-test-cases
-                                           (test-and-train-data-from-domains data-domains)))]
-    (when true ;; Change to false to not print test cases
-      (doseq [[i case] (map vector (range) train-cases)]
-        (println (format "Train Case: %3d | Input/Output: %s" i (str case))))
-      (doseq [[i case] (map vector (range) test-cases)]
-        (println (format "Test Case: %3d | Input/Output: %s" i (str case)))))
-   (make-even-squares-error-function-from-cases train-cases test-cases)))
-
 (defn even-squares-report
   "Custom generational report."
   [best population generation error-function report-simplifications]


add a couple of figwheel options

add a couple of figwheel options

--- src/leiningen/new/reagent_liveedit/project.clj
+++ src/leiningen/new/reagent_liveedit/project.clj
@@ -106,7 +106,9 @@

                    :figwheel {:http-server-root "public"
                               :server-port 3449
-                              :css-dirs ["resources/public/css"]}
+                              :css-dirs ["resources/public/css"]
+                              :server-logfile "logs/figwheel.log"
+                              :repl false}

                    :env {:dev? true}


Add directory search to load-spec

Add directory search to load-spec

Uses clojure.contrib.find-namespaces

--- src/main/clojure/com/stuartsierra/lazytest.clj
+++ src/main/clojure/com/stuartsierra/lazytest.clj
@@ -1,4 +1,6 @@
-(ns com.stuartsierra.lazytest)
+(ns com.stuartsierra.lazytest
+  (:use [clojure.contrib.find-namespaces
+         :only (find-namespaces-in-dir)]))

 ;;; PROTOCOLS

@@ -427,14 +429,29 @@
 (defn load-spec
   "Like find-spec but loads namespaces with require.  options will be
   passed to require, such as :reload, or :reload-all.  Returns the
-  spec or nil if none found."
-  [sym & options]
-  (if (symbol? sym)
-    (do (apply require sym options) (load-spec sym))
-    (find-spec sym)))
+  spec or nil if none found.
+
+  Argument may also be a java.io.File or String, which will load all
+  namespaces in the named directory."
+  [x & options]
+  (cond (symbol? x)
+        (do (apply require x options) (load-spec x))
+
+        (string? x)
+        (load-spec (java.io.File. x))
+
+        (instance? java.io.File x)
+        (if (.isDirectory x)
+          (let [names (find-namespaces-in-dir x)]
+            (doseq [n names] (apply require n options))
+            (find-spec names))
+          (throw (IllegalArgumentException.
+                  "File argument to load-spec must be a directory")))
+
+        :else (find-spec x)))

 (defn run-spec
   "Like load-spec but executes the specs once they are found."
-  [sym & options]
-  (when-let [s (apply load-spec sym options)]
+  [x & options]
+  (when-let [s (apply load-spec x options)]
     (s)))


Use oauth token

Use oauth token

--- src/clj/made_merits/service/github/boyscouting/scraper.clj
+++ src/clj/made_merits/service/github/boyscouting/scraper.clj
@@ -15,5 +15,9 @@
 (defn results [] (map
     (fn [repo]
       (println (str "processing " repo))
-      (hash-map :project repo :results (detector/detect (:body (client/get (to-url repo))))))
+      (hash-map :project repo
+                :results (detector/detect
+                           (:body
+                             (client/get
+                               (to-url repo {:oauth-token ~(get (System/getenv) "GITHUB_OAUTH_SECRET")}))))))
     repos))


Doubled max points

Doubled max points

--- src/clojush/problems/regression/pagie_hogeweg_with_erc.clj
+++ src/clojush/problems/regression/pagie_hogeweg_with_erc.clj
@@ -87,7 +87,7 @@
   {:error-function (partial error-function (count data));; Use all samples
    :atom-generators atom-generators
    :report-simplifications 0
-   :max-points 1000
+   :max-points 2000
    :max-genome-size-in-initial-program 500
    :evalpush-limit 500
    :population-size 1000


Fix indexing job in balanced-job-scheduler

--- src/onyx/scheduling/balanced_job_scheduler.clj
+++ src/onyx/scheduling/balanced_job_scheduler.clj
@@ -38,7 +38,7 @@
                   (let [covered (max 0 (- (cjs/job-lower-bound replica job-id) peer-count))]
                     (vector covered
                             peer-count
-                            (.indexOf ^clojure.lang.PersistentVector (vec (:jobs replica)) job)))))
+                            (.indexOf ^clojure.lang.PersistentVector (vec (:jobs replica)) job-id)))))
        (remove (fn [[job-id peer-count]]
                  (>= peer-count (cjs/job-upper-bound replica job-id))))
        (ffirst)))


Addressed review comments.

Addressed review comments.

--- src/cmr/system_int_test/data2/provider_holdings.clj
+++ src/cmr/system_int_test/data2/provider_holdings.clj
@@ -3,6 +3,11 @@
   (:require [clojure.data.xml :as x]
             [cmr.common.xml :as cx]
             [cheshire.core :as json]))
+
+(defmulti parse-provider-holdings
+  "Returns the parsed provider holdings based on the given format and result string"
+  (fn [format result]
+  format))

 (defn- xml-elem->provider-holding
   "Returns the provider holding entry by parsing the given xml struct"
@@ -12,22 +17,15 @@
    :granule-count (cx/long-at-path xml-elem [:granule-count])
    :provider-id (cx/string-at-path xml-elem [:provider-id])})

-(defn- parse-xml-provider-holdings
-  "Returns the parsed provider holdings for the given xml string"
-  [xml]
+(defmethod parse-provider-holdings :xml
+  [format xml]
   (let [xml-struct (x/parse-str xml)]
     (map xml-elem->provider-holding
          (cx/elements-at-path xml-struct [:provider-holding]))))

-(defn- parse-json-provider-holdings
-  "Returns the parsed provider holdings for the given json string"
-  [json-str]
+(defmethod parse-provider-holdings :json
+  [format json-str]
   (json/decode json-str true))

-(defn parse-provider-holdings
-  "Returns the parsed provider holdings based on the given format and result string"
-  [format result]
-  (if (= :xml format)
-    (parse-xml-provider-holdings result)
-    (parse-json-provider-holdings result)))

+


make the tests compare eval the syntax-quote expression for comparison rather than comparing the actual output

--- src/test/clojure/clojure/tools/reader_test.clj
+++ src/test/clojure/clojure/tools/reader_test.clj
@@ -31,11 +31,11 @@
 (deftest read-syntax-quote
   (is (= '`user/foo (binding [*ns* (the-ns 'user)]
                       (read-string "`foo"))))
-  (is (= () (read-string "`(~@[])")))
+  (is (= () (eval (read-string "`(~@[])"))))
   (is (= '`+ (read-string "`+")))
   (is (= '`foo/bar (read-string "`foo/bar")))
   (is (= '`1 (read-string "`1")))
-  (is (= '`(1 (~2 ~@(3))) (read-string "`(1 (~2 ~@(3)))"))))
+  (is (= `(1 (~2 ~@'(3))) (eval (read-string "`(1 (~2 ~@'(3)))")))))

 (deftest read-deref
   (is (= '@foo (read-string "@foo"))))


add gaurd to io-threads after npe seen

add gaurd to io-threads after npe seen

--- kafka-clj/src/kafka_clj/client.clj
+++ kafka-clj/src/kafka_clj/client.clj
@@ -381,7 +381,7 @@
 (defn create-connector [bootstrap-brokers {:keys [acks batch-fail-message-over-limit batch-byte-limit blacklisted-expire producer-retry-strategy topic-auto-create io-threads] :or {blacklisted-expire 1000 acks 0 batch-fail-message-over-limit true batch-byte-limit 10485760 producer-retry-strategy :default topic-auto-create true :io-threads 8} :as conf}]
   (let [
         ;all connector channels will use this shared pool for listening on write read events. 3 threads was tested with over 120 k messages per second
-        async-ctx (fthreads/shared-threads (inc io-threads))
+        async-ctx (fthreads/shared-threads (if (number? io-threads) (inc io-threads) 4))
         ^ScheduledExecutorService scheduled-service (Executors/newSingleThreadScheduledExecutor (daemon-thread-factory))
         metadata-producers-ref (ref (filter (complement nil?) (map #(delay (metadata-request-producer (:host %) (:port %) conf)) bootstrap-brokers)))
         brokers-metadata (ref (get-metadata @metadata-producers-ref conf))


adding debug info to healthy partition checking

--- kafka-clj/src/kafka_clj/client.clj
+++ kafka-clj/src/kafka_clj/client.clj
@@ -43,12 +43,16 @@
     (assoc m k (dissoc-in (m k) ks))))

 (defn- healthy-partition-rc? [^ProducerState state {:keys [host port error-code]}]
-  (and
-    host
-    port
-    (not (-> @(:blacklisted-producers-ref state) (get host) (get port)))
-    (not= error-code 5)
-    (not= error-code -1)))
+  (try
+    (and
+      host
+      port
+      (not (-> @(:blacklisted-producers-ref state) (get host) (get port)))
+      (not= error-code 5)
+      (not= error-code -1))
+    (catch Exception e (do
+                         (error "NPE while querying " (:blacklisted-producers-ref state) " keys " (keys state) " host " host " port " port)
+                         false))))

 (defn send-msg
   "Sends a message async and returns false if the connection is closed


Add API status to footer of page, close #49

--- frontend/src/cruncher/views.cljs
+++ frontend/src/cruncher/views.cljs
@@ -202,8 +202,6 @@
                       (dom/div #js {:className "pull-right"}
                                (vlib/login-indicator (om/props this)))
                       (dom/h1 nil "Poké-Cruncher"))
-             (dom/div #js {:className "pull-right"}
-                      (dom/div nil (status/api-connected-badge {})))
              (dom/span #js {:className "pull-right"} (vlib/loader (om/props this)))
              (dom/ul nil
                      (dom/li nil
@@ -301,6 +299,9 @@
              (dom/div nil (info-message (om/props this)))
              (view-dispatcher this)
              (dom/div nil (vlib/back-to-top))
+             (dom/hr nil)
+             (dom/div #js {:className ""}
+                      (dom/div nil (status/api-test (om/props this))))
              #_(dom/div nil (poketable (om/props this)))
              #_(dom/div nil (login)))))


added a work in progress note

added a work in progress note

--- src/tutorial/untangled_tutorial/A_Introduction.cljs
+++ src/tutorial/untangled_tutorial/A_Introduction.cljs
@@ -10,6 +10,10 @@
   This tutorial will walk you through the various parts of Untangled (alpha).

   Note that you can navigate to the table of contents any time using the `devcards` link at the top of the page.
+
+  **WORK IN PROGRESS**: We are working hard to round out documentation, code samples, and many
+  other things while also developing production software. Please be patient with us and feel
+  free to suggest (or make) contributions.

   ## About This Tutorial


replace a whole lot of frequency calc code with... frequencies :)

--- clojure/word-count/word-count.clj
+++ clojure/word-count/word-count.clj
@@ -7,13 +7,5 @@
 (defn- filter-words [str]
   (filter (comp not blank?) (tokenize str)))

-(defn- add-count-for [word counts]
-  (assoc counts word (inc (get counts word 0))))
-
-(defn- count [words counts]
-  (if (empty? words)
-    counts
-    (count (rest words) (add-count-for (first words) counts))))
-
 (defn word-count [str]
-  (count (filter-words str) {}))
+  (frequencies (filter-words str)))


Handle *sh-dir*

Handle *sh-dir*

Goes with the use of second in #331

--- planck-cljs/src/planck/shell.cljs
+++ planck-cljs/src/planck/shell.cljs
@@ -33,7 +33,7 @@
     (when (nil? cmd)
       (throw (s/explain ::sh-args args)))
     (let [{:keys [in in-enc out-enc env dir]}
-          (merge {:out-enc nil :in-enc nil :dir *sh-dir* :env *sh-env*}
+          (merge {:out-enc nil :in-enc nil :dir (and *sh-dir* [:sh-dir *sh-dir*]) :env *sh-env*}
             (into {} (map (comp (juxt :key :val) second) opts)))
           dir (and dir (:path (as-file (second dir))))
           [exit out err] (js->clj (js/PLANCK_SHELL_SH (clj->js cmd) in in-enc out-enc (clj->js (seq env)) dir))]


Add simple-report and better result metadata.

--- lazytest.clj
+++ lazytest.clj
@@ -75,7 +75,8 @@
   (eval (format-assertion a)))

 (defmacro assertion [locals & body]
-  (format-assertion (Assertion locals `(do ~@body))))
+  (format-assertion (Assertion locals (if (= 1 (count body))
+                                        (first body) `(do ~@body)))))

 (defmacro defassert
   "Defines an Assertion.
@@ -111,6 +112,10 @@
       (apply f (active c) states))
     (let [active (reduce close-context active (:parents c))]
       (dissoc active c))))
+
+(defn- coerce-context [c]
+  (if (and (symbol? c) (= ::Context (type (var-get (resolve c)))))
+    c (Context [] (fn [] c) nil)))

 (defmacro defcontext
   "Defines a context.
@@ -174,10 +179,6 @@
         (TestResult t results))
       (catch Throwable e (TestThrown t e)))))

-(defn- coerce-context [c]
-  (if (and (symbol? c) (= ::Context (type (var-get (resolve c)))))
-    c (Context [] (fn [] c) nil)))
-
 (defmacro deftest
   "Defines a test case containing assertions that share the same contexts.
   decl => docstring? [binding*] assertion*
@@ -200,9 +201,11 @@
                                     (if (seq as)
                                       (if (string? (first as))
                                         (recur (conj r `(with-meta (assertion ~locals ~(next as))
-                                                          {:doc ~(first as)}))
+                                                          {:doc ~(first as), :form '~(next as)}))
                                                (nnext as))
-                                        (recur (conj r `(assertion ~locals ~(first as))) (next as)))
+                                        (recur (conj r `(with-meta (assertion ~locals ~(first as))
+                                                          {:form '~(first as)}))
+                                               (next as)))
                                       r)))
               '~m)))))

@@ -227,6 +230,39 @@
   TestResult and all its children."
   [r]
   (tree-seq :children :children r))
+
+(require 'clojure.stacktrace)
+
+(defn result-identifier [r]
+  (let [m (meta (:source r))]
+    (or (:name m) (:form m)
+        (:source r))))
+
+(defn simple-report
+  ([r] (simple-report r ""))
+  ([r indent]
+     (cond (= ::TestResult (type r))
+           (do (println indent (if (success? r) "OK" "TEST")
+                        (result-identifier r))
+               (doseq [c (:children r)]
+                 (simple-report c (str indent "   "))))
+
+           (= ::TestThrown (type r))
+           (do (println indent "ERROR" (result-identifier r))
+               (when-let [d (:doc (meta r))] (prn d))
+               (clojure.stacktrace/print-cause-trace (:error r)))
+
+           (= ::AssertionPassed (type r))
+           (println indent "OK" (result-identifier r))
+
+           (= ::AssertionFailed (type r))
+           (do (println indent "FAIL" (result-identifier r))
+               (when-let [d (:doc (meta r))] (prn d)))
+
+           (= ::AssertionThrown (type r))
+           (do (println indent "ERROR" (result-identifier r))
+               (when-let [d (:doc (meta r))] (prn d))
+               (clojure.stacktrace/print-cause-trace (:error r))))))

 ;;; TESTABLE IMPLEMENTATIONS
@@ -417,6 +453,8 @@
 (assert (every? fn? (:children t10)))
 (assert (= "a is less than b"
            (:doc (meta (second (:children t10))))))
+(assert (= '(= a b)
+           (:form (meta (first (:children t10))))))

 ;; defsuite form
 (defsuite t11 "Suite t11" [c4 c5] t9 t10)
@@ -427,3 +465,31 @@
 (assert (= ::TestCase (type t11)))
 (assert (= [c4 c5] (:contexts t11)))
 (assert (= [t9 t10] (:children t11)))
+
+
+;; README examples
+    (defassert positive [x] (pos? x))
+    (success? (positive 1))
+    ;;=> true
+    (success? (positive -1))
+    ;;=> false
+    (success? (positive "hello"))
+    ;;=> false
+    (deftest addition [a 1, b 2]
+      (integer? a)
+      (integer? b)
+      (integer? (+ a b)))
+    (success? (addition))
+    ;;=> true
+    (defcontext random-int []
+      (rand-int Integer/MAX_VALUE))
+    (deftest random-addition [a random-int, b random-int]
+      (integer? (+ a b))
+      (= (+ a b) (+ b a)))
+
+    (success? (random-addition))
+    ;;=> true
+    (defsuite all-tests [] addition random-addition)
+
+    (success? (all-tests))
+    ;;=> true


Updated ExportJob in reports.scheduler to use :strs destructuring in its (let) binding.

--- reports/src/reports/scheduler.clj
+++ reports/src/reports/scheduler.clj
@@ -8,20 +8,15 @@

 (def cache (ref {}))

-(j/defjob ExportJob
-  [ctx]
-  (let [{baseURL "baseURL"
-         exportType "exportType"
-         sid "surveyId"
-         opts "opts"
-         reportId "reportId"} (qc/from-job-data ctx)
-         report (exp/doexport exportType baseURL sid opts)
-         path (s/join "/" (take-last 2 (s/split (.getAbsolutePath report) #"/")))]
+(j/defjob ExportJob [context]
+  (let [{:strs [baseURL exportType surveyId opts reportId]} (qc/from-job-data context)
+        report (exp/doexport exportType baseURL surveyId opts)
+        path (s/join "/" (take-last 2 (s/split (.getAbsolutePath report) #"/")))]
     (dosync
       (alter cache conj {{:id reportId
-                          :surveyId sid
+                          :surveyId surveyId
                           :baseURL baseURL} path}))
-    (qs/delete-job (j/key reportId))))
+    (qs/delete-job (j/key report-id))))

 (defn- get-executing-jobs []


promote to version

promote to version

--- clj-tcp/project.clj
+++ clj-tcp/project.clj
@@ -1,4 +1,4 @@
-(defproject clj-tcp "0.4.0-SNAPSHOT"
+(defproject clj-tcp "0.4.0"
   :description "Fast clojure tcp library based on netty"
   :url "https://github.com/gerritjvv/clj-tcp"
   :license {:name "Eclipse Public License"


Updates simple-xpath API.

Updates simple-xpath API.

The `evaluate' multimethod becomes `evaluate-internal', and a new
`evaluate' function now accepts XML and XPath strings in addition to
prepared XPath contexts and parsed XPath expression structures.

--- umm-spec-lib/src/cmr/umm_spec/simple_xpath.clj
+++ umm-spec-lib/src/cmr/umm_spec/simple_xpath.clj
@@ -339,6 +339,13 @@
     [(nth (as-vector data) index)]
     []))

+(defn- xpath-context?
+  [x]
+  (and (map? x)
+       (:type x)
+       (:root x)
+       (:context x)))
+
 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 ;; Public API

@@ -372,12 +379,12 @@

 (defmulti
   ^{:arglists '([xpath-context parsed-xpath])}
-  evaluate
+  evaluate-internal
   "Evaluates a parsed XPath against the given XPath context."
   (fn [xpath-context parsed-xpath]
     (:type xpath-context)))

-(defmethod evaluate :xml
+(defmethod evaluate-internal :xml
   [xpath-context {:keys [source selectors original-xpath]}]
   (try
     (let [source-elements (cond
@@ -389,7 +396,7 @@
     (catch Exception e
       (throw (Exception. (str "Error processing xpath: " original-xpath) e)))))

-(defmethod evaluate :data
+(defmethod evaluate-internal :data
   [xpath-context {:keys [source selectors original-xpath]}]
   (try
     (let [data (cond
@@ -406,3 +413,25 @@
     (catch Exception e
       (throw (Exception. (str "Error processing xpath: " original-xpath) e)))))

+
+(defn evaluate
+  "Returns the XPath context resulting from evaluating an XPath expression against XML or Clojure
+  data. The given context may be an XPath context, an XML string, or a Clojure data structure. The
+  given xpath-expression may be a string or a value as returned by parse-xpath."
+  [context xpath-expression]
+  (let [context (cond
+                  (xpath-context? context) context
+                  (string? context)        (create-xpath-context-for-xml context)
+                  :else                    (create-xpath-context-for-data context))
+        xpath-expression (if (string? xpath-expression)
+                           (parse-xpath xpath-expression)
+                           xpath-expression)]
+    (evaluate-internal context xpath-expression)))
+
+(defn text
+  "Returns the text of all nodes selected in an XPath context."
+  [context-or-node]
+  (cond
+    (string? context-or-node) context-or-node
+    (xpath-context? context-or-node) (apply str (map text (:context context-or-node)))
+    (:content context-or-node) (str/join (map text (:content context-or-node)))))


Drop the change-browser-repl-namespace code, it no longer works

See https://github.com/plexus/chestnut/issues/108

Due to changes in Piggieback, this simply no longer works, and it's not
obvious how to do this instead, or if it's even possible. So from now on
Clojurescript's REPL will start in cljs.user, and you will have
to (in-ns) yourself.

--- src/leiningen/new/chestnut/env/dev/clj/chestnut/dev.clj
+++ src/leiningen/new/chestnut/env/dev/clj/chestnut/dev.clj
@@ -18,8 +18,7 @@

 (defn browser-repl []
   (let [repl-env (weasel/repl-env :ip "0.0.0.0" :port 9001)]
-    (piggieback/cljs-repl :repl-env repl-env)
-    (piggieback/cljs-eval repl-env '(in-ns '{{project-ns}}.core) {})))
+    (piggieback/cljs-repl :repl-env repl-env)))

 (defn start-figwheel []
   (let [server (fig/start-server { :css-dirs ["resources/public/css"] })


Corrected boostrap user name.

Corrected boostrap user name.

--- bootstrap-app/src/cmr/bootstrap/config.clj
+++ bootstrap-app/src/cmr/bootstrap/config.clj
@@ -6,7 +6,7 @@

 (defconfig bootstrap-username
   "Defines the bootstrap database username."
-  {:default "cmr"})
+  {:default "CMR_BOOTSTRAP"})

 (defconfig bootstrap-password
   "Defines the bootstrap database password."


Don't use heroku mirrors

Don't use heroku mirrors

--- opt/profiles.clj
+++ opt/profiles.clj
@@ -1,3 +1 @@
-{:user {:mirrors {"central" "http://s3pository.herokuapp.com/maven-central"}}
- :production {:mirrors {"central" "http://s3pository.herokuapp.com/maven-central"}}
- :heroku {:mirrors {"central" "http://s3pository.herokuapp.com/maven-central"}}}
+{}


define test

define test

--- src-cljs/frontend/state.cljs
+++ src-cljs/frontend/state.cljs
@@ -9,7 +9,8 @@
    :ab-test-definitions {:a_is_a [true false]
                          :split_form [true false]
                          :parallelism_button [true false]
-                         :pricing_button_green [true false]}
+                         :pricing_button_green [true false]
+                         :pay_now_button [true false]}
    :changelog nil
    :environment "development"
    :settings {:projects {}            ; hash of project-id to settings


Allow nil strings in set-page-description!

--- src-cljs/frontend/utils.cljs
+++ src-cljs/frontend/utils.cljs
@@ -247,7 +247,7 @@
 (defn set-page-description!
   [description]
   (let [meta-el (.querySelector js/document "meta[name=description]")]
-    (.setAttribute meta-el "content" description)))
+    (.setAttribute meta-el "content" (str description))))

 (defn set-canonical!
   "Upserts a canonical URL if canonical-page is not nil, otherwise deletes the canonical rel."


want to change logic

want to change logic

--- Degree-of-an-Array/DoaA.clj
+++ Degree-of-an-Array/DoaA.clj
@@ -1 +1,17 @@
-(defn find-shortest-subarray [])
+(defn find-shortest-subarray [nums]
+  (loop [store-all-ele {}
+         stack-of-degree [0 []]
+         nums nums
+         ind 0]
+    (cond (empty? nums)
+          (apply min
+                 (map #(- (last (last (get store-all-ele %)))
+                          (first (last (get store-all-ele %))))
+                      ))
+          :else
+          (recur (try
+                   (if (> (count (last (get store-all-ele (first nums)))) 1)
+                     (update store-all-ele (first nums)
+                             (conj (last (get store-all-ele (first nums))) ind))))))))
+
+(defn update-store)


Made 'lens/projection' public, was not meant to be private.

--- src/active/clojure/lens.cljc
+++ src/active/clojure/lens.cljc
@@ -388,7 +388,7 @@
                      (shove r lens (yank v f)))
                    out
                    fields)))]
-  (defn- projection
+  (defn projection
     "A lens that projects multiple derived values into a new value,
   with `empty` being an initial new value, and `fields` a map or
   sequence of tuples, of a lens on the new value and lens over the


style issues

style issues

--- src/clj/just_married/css.clj
+++ src/clj/just_married/css.clj
@@ -108,7 +108,7 @@
    [:.navbar__container {:background-color (:dark-red COLOR-PALLETTE)
                          :font-weight "bolder"
                          :display "grid"
-                         :font-size "1.5em"
+                         :font-size "1.2em"
                          :grid-template-columns "repeat(5, 1fr)"
                          :grid-auto-rows "auto"
                          :grid-gap "1em"
@@ -123,6 +123,7 @@
         :text-decoration "none"}]

    [:a:hover {:color (:gold COLOR-PALLETTE)
+              :text-decoration "none"
               :border-left "1px solid white"
               :border-right "1px solid white"}]])


code clean-up

code clean-up

--- src/clj/salava/user/data.clj
+++ src/clj/salava/user/data.clj
@@ -206,7 +206,7 @@
                                                                                (when-not (blank? (str (:verified_by_obf b)))
                                                                                [:phrase
                                                                                [:chunk.chunk (str (t :badge/Verifiedbyobf ul) ": ")][:chunk (str (:verified_by_obf b) "  ")]])
-                                                                                (when-not (blank? (str (:issued_by_obf b)))
+                                                                                (when-not (blank? (:issued_by_obf b))
                                                                                [:phrase
                                                                                [:chunk.chunk (str (t :badge/Issuedbyobf ul) ": ")][:chunk (str (:issued_by_obf b))]"\n"])
                                                                                (when (not-empty (:tags b))
@@ -268,11 +268,7 @@
                                                                                [:paragraph
                                                                                (into [:paragraph] (for [c (:congratulations more-badge-info)]
                                                                                [:phrase
-                                                                                [:chunk (str c)] "\n"]))]
-                                                                                #_(when (= true  congratulated?
-                                                                                [:paragraph
-                                                                                (into [:paragraph] (for [c (:congratulations more-badge-info)]
-                                                                                [:chunk (str c)]))]))])
+                                                                                [:chunk (str c)] "\n"]))]])
                                                                                (when-not (blank? (str (:endorsement_count %)))
                                                                                [:phrase
                                                                                [:chunk.chunk (str (capitalize (t :badge/endorsements ul)) ": ")][:chunk (str (:endorsement_count %))]"\n"])
@@ -418,13 +414,13 @@
                                                  (when-not (empty? $user_followers)
                                                    (into [:paragraph
                                                           [:phrase.chunk (str (t :social/Followersusers ul) ": ")] [:spacer 0]] (for [follower $user_followers
-                                                                                :let [follower-id (:owner_id follower)
-                                                                                fname (:first_name follower)
-                                                                                lname (:last_name follower)
-                                                                                status (:status follower)]]
-                                                                                [:paragraph
-                                                                                [:anchor {:target (str site-url "/" "user/profile/" follower-id)} [:chunk.link (str fname " " lname ",  ")]]
-                                                                                [:chunk.chunk (str (t :user/Status ul) ": ")] [:chunk status]])))
+                                                                                :let [follower-id (:owner_id follower)
+                                                                                fname (:first_name follower)
+                                                                                lname (:last_name follower)
+                                                                                status (:status follower)]]
+                                                                                [:paragraph
+                                                                                [:anchor {:target (str site-url "/" "user/profile/" follower-id)} [:chunk.link (str fname " " lname ",  ")]]
+                                                                                [:chunk.chunk (str (t :user/Status ul) ": ")] [:chunk status]])))
                                                  (when-not (empty? $user_following)
                                                    (into [:paragraph
                                                           [:phrase.chunk (str (t :social/Followedusers ul) ": ")][:spacer 0]] (for [f $user_following


select proper item in drop-down

select proper item in drop-down

--- src/clj_money/web/shared.clj
+++ src/clj_money/web/shared.clj
@@ -283,7 +283,10 @@
     (when-not (:suppress-label? options)
       [:label {:for name} (humanize name)])
     [:select.form-control (merge (dissoc options :suppress-label?) {:id name :name name})
-     option-items]])
+     (map #(if (= value (get-in % [1 :value]))
+             (assoc-in % [1 :selected] true)
+             %)
+          option-items)]])

 (defn select-field
   ([model attribute option-items]


Remove clj-http.client require that is not used.

--- src/clj_ravendb/requests.clj
+++ src/clj_ravendb/requests.clj
@@ -1,5 +1,4 @@
 (ns clj-ravendb.requests
-  (:require [clj-http.client :as client])
   (:require [clojure.data.json :as json]))

 (defn- all-urls


s/get-string-1/fo/ where possible

s/get-string-1/fo/ where possible

--- src/babel/english/morphology.clj
+++ src/babel/english/morphology.clj
@@ -29,19 +29,20 @@
         (or (map? (get-in input [:english :a :english]))
             (map? (get-in input [:english :b :english]))))
    (string/join " "
-                (list (get-string-1 (get-in input [:english :a :english]))
-                      (get-string-1 (get-in input [:english :b :english]))))
+                (list (fo (get-in input [:english :a :english]))
+                      (fo (get-in input [:english :b :english]))))
    (and (map? input)
         (get-in input [:english :a])
         (get-in input [:english :b]))
    (string/join " "
-                (list (get-string-1 (get-in input [:english :a]))
-                      (get-string-1 (get-in input [:english :b]))))
+                (list (fo (get-in input [:english :a]))
+                      (fo (get-in input [:english :b]))))

    (and (map? input)
         (map? (get-in input [:english])))
    (get-string-1 (get-in input [:english]))

+   ;; TODO: this is the tricky part about combining fo and get-string-1.
    (and (map? input)
         (get-in input [:english]))
    (get-string-1 input)
@@ -50,8 +51,8 @@
         (get-in input [:a])
         (get-in input [:b]))
    (str (string/join " "
-                     (list (get-string-1 (get-in input [:a]))
-                           (get-string-1 (get-in input [:b])))))
+                     (list (fo (get-in input [:a]))
+                           (fo (get-in input [:b])))))

    (or (seq? input)
        (vector? input))


remove _ping API

remove _ping API

--- src/clj/dokkaa_builder/route.clj
+++ src/clj/dokkaa_builder/route.clj
@@ -62,9 +62,6 @@
       (apps/logs app-name user)
       {:status 401, :body "token is invalid"})))

-(defn ping [req]
-  {:status 200})
-
 (defn index [req]
   (if (friend/authorized? [:user] req)
     (pages/index)
@@ -91,7 +88,6 @@

 (defroutes routes
   (GET "/" req (index req))
-  (GET "/_ping"  [] ping)
   (GET "/status" req (status-page req))
   (context "/apps" req (friend/wrap-authorize apps-routes #{:user}))
   (context "/user" req (friend/wrap-authorize users-routes #{:user}))


Fixed request-ok

Fixed request-ok

--- src/clj/funstructor/commands.clj
+++ src/clj/funstructor/commands.clj
@@ -48,7 +48,7 @@
                    (fn [cards]
                      (map cards/cards cards)))
         (assoc :current-turn (:current-turn game-state))
-        (assoc :enemy-cards-num (count(:cards (game-state opponent-uuid))))
+        (assoc :enemy-cards-num (count (:cards (game-state opponent-uuid))))
         (assoc :enemy-funstruct (:funstruct (game-state opponent-uuid))))))

 (defmulti handle-command (fn [command channel] (:type command)))
@@ -57,7 +57,7 @@
     (add-channel channel uuid)
     (add-pending uuid)
     (println "Global state: " @global-state)
-    (send-commands :commands [{:type :request-ok
+    (send-commands :commands [{:type :game-request-ok
                                :uuid uuid
                                :pending (pending-players)}]
                    :channels (map channel-for-uuid (pending-players)))))


Remove old comments

Remove old comments

--- src/clj/reply/initialization.clj
+++ src/clj/reply/initialization.clj
@@ -102,13 +102,9 @@
     (use '[clojure.pprint :only ~'[pp pprint]])

     ~(export-definition 'reply.initialization/help)
-    ;~(export-definition 'reply.exit/exit)
-    ;(def ~'quit ~'exit)

     (ns reply.exports)
     ~(export-definition 'reply.initialization/intern-with-meta)
-
-    ;(~'intern-with-meta '~'user '~'quit #'user/exit)

     (binding [*err* (java.io.StringWriter.)]
       ~(export-definition 'reply.initialization/repl-defn)


Add log-clj to utils

Add log-clj to utils

--- src/cljs/hacker_agent/utils.cljs
+++ src/cljs/hacker_agent/utils.cljs
@@ -6,3 +6,6 @@
     (if prefix
       (update-in data prefix dissoc key)
       (dissoc data key))))
+
+(defn log-clj [o]
+  (.log js/console (clj->js o)))


Remove clear focus when project dir is changed

--- src/clojure/nightmod/screens.clj
+++ src/clojure/nightmod/screens.clj
@@ -322,8 +322,3 @@
            :clear-global-focus
            (fn [_ _ _ _]
              (u/clear-global-focus!)))
-
-(add-watch u/project-dir
-           :clear-global-focus
-           (fn [_ _ _ _]
-             (u/clear-global-focus!)))


Fix errors spec

Fix errors spec

--- src/com/wsscode/pathom/core.cljc
+++ src/com/wsscode/pathom/core.cljc
@@ -24,7 +24,7 @@

 (s/def ::errors (s/map-of vector? any?))

-(s/def ::errors* #(satisfies? IAtom %))
+(s/def ::errors* #(instance? IAtom %))

 (s/def ::process-error
   (s/fspec :args (s/cat :error any?)


Fixing use of group instead of tribe in split

--- src/civs/logic/tribe_choices.clj
+++ src/civs/logic/tribe_choices.clj
@@ -132,42 +132,42 @@
 (def split
   (PossibleEvent.
     :split
-    (fn [game tribe]
-      (let [c (crowding game tribe)
-            pop (-> tribe .population total-persons)
+    (fn [game group]
+      (let [c (crowding game group)
+            pop (-> group .population total-persons)
             world (.world game)
-            pos (.position tribe)
+            pos (.position group)
             possible-destinations (filter #(pos-free? game %) (land-cells-around world pos (migration-radius group)))]
         (if
           (and (> pop 35) (< c 0.9) (not (empty? possible-destinations)))
           (/ (opposite c) 2.7)
           0.0)))
-    (fn [game tribe]
+    (fn [game group]
       (let [ world (.world game)
-             pos (.position tribe)
-             sp (split-pop (.population tribe))
+             pos (.position group)
+             sp (split-pop (.population group))
              possible-destinations (filter #(pos-free? game %) (land-cells-around world pos (migration-radius group)))
              preferences (map (fn [pos] {
-                                          :preference (perturbate-low (prosperity-in-pos game tribe pos))
+                                          :preference (perturbate-low (prosperity-in-pos game group pos))
                                           :pos pos
                                           }) possible-destinations)
              preferences (sort-by :preference preferences)
              dest-target (:pos (first preferences))
-             language (get-language tribe)
+             language (get-language group)
              new-group-name (if (nil? language) :unnamed (.name language))
-             res (create-tribe game new-group-name dest-target (:leaving sp) (.culture tribe) (.society tribe))
+             res (create-tribe game new-group-name dest-target (:leaving sp) (.culture group) (.society group))
              game (:game res)]
-        (if (sedentary? tribe)
+        (if (sedentary? group)
           (let [settlement-name (if (nil? language) :unnamed (.name language))
                 game (:game (create-settlement game settlement-name dest-target (:id (:tribe res)) current-turn))]
             {
               :game game
-              :tribe (assoc tribe :population (:remaining sp))
+              :tribe (assoc group :population (:remaining sp))
               :params {}
             })
           {
             :game game
-            :tribe (assoc tribe :population (:remaining sp))
+            :tribe (assoc group :population (:remaining sp))
             :params {}
             })))))


Fix misspelled class

Fix misspelled class

--- src/clj/ji/service/templates.clj
+++ src/clj/ji/service/templates.clj
@@ -19,12 +19,12 @@
 (defn render-game [game-env]
   (page/html5
     (page/include-css "/stylesheets/app.css")
-    (html [:body#game.row.collapsed
+    (html [:body#game.row.collapse
            {:onload "ji.main.init();"
             :data-game-id (:id game-env)}
            [:div#messages.small-12.columns]
            [:div.small-12.columns
-            [:div#content.row.collapsed]]
+            [:div#content.row.collapse]]
            (page/include-js "/js/main.js")])))

 (defn render-game-create [game-id]
@@ -49,7 +49,7 @@
 (defn render-lobby [game-envs]
   (render-page
     (html
-      [:div.row.collapsed
+      [:div.row.collapse
        [:h1 "Games"]
        [:div.large-12.columns
         [:form


Add to 2016-nok function

Add to 2016-nok function

--- src/clj_simple_chart/ssb/kpi.clj
+++ src/clj_simple_chart/ssb/kpi.clj
@@ -79,6 +79,19 @@
                     (sort-by :dato)
                     (vec)))

+(def quarter-to-kpi (zipmap (mapv :dato quarterly)
+                            (mapv :kpi quarterly)))
+
+(def baseline-sum (->> parsed
+                       (filter #(= "2016" (:year %)))
+                       (mapv (comp read-string :kpi))
+                       (reduce + 0)))
+
+(def baseline (/ baseline-sum 12))
+
+(defn to-2016-nok [dato-with-quarter v]
+  (* v (/ baseline (get quarter-to-kpi dato-with-quarter))))
+
 (csv/write-csv "./data/08981/08981-kpi-quarterly.csv"
                {:data    (mapv #(assoc % :kpi (format "%.1f" (:kpi %))) quarterly)
                 :columns [:dato :kpi]})


refactor game loop

refactor game loop

--- src/cljs/triboard/game_loop.cljs
+++ src/cljs/triboard/game_loop.cljs
@@ -1,18 +1,17 @@
 (ns triboard.game-loop
+  (:require-macros
+    [cljs.core.async.macros :refer [go go-loop alt!]])
   (:require
     [cljs.core.async :as async :refer [put! chan <! >!]]
     [triboard.ai.ai :as ai]
     [triboard.logic.game :as game]
-    [triboard.store :as store])
-  (:require-macros
-    [cljs.core.async.macros :refer [go go-loop alt!]]
-    ))
+    [triboard.store :as store]))

 (def animation-delay 500)
 (def ai-move-delay 1000)

-(defn ai-computation
+(defn- ai-computation
   "Run the computation of the AI asynchronously:
    * Wait 500ms to start (animation might be frozen otherwise)
    * Wait 1s to play the move (avoid moves being played too fast)"
@@ -23,7 +22,7 @@
       (<! (async/timeout ai-move-delay))
       (<! ai-chan))))

-(defn handle-menu-event!
+(defn- handle-menu-event!
   "Handle the menu event"
   [msg]
   (case msg
@@ -32,7 +31,7 @@
     :restart (store/swap-game! game/restart-game)
     :undo (store/swap-game! game/undo-player-move)))

-(defn start-game-loop
+(defn- start-game-loop
   "Manage transitions between player moves, ai moves, and generic game events"
   []
   (let [player-moves (chan 1 (filter #(not @store/ai-player?)))
@@ -49,7 +48,11 @@
     {:game-events player-moves
      :menu-events menu-events}))

+
+;; -----------------------------------------
+;; Public API
+;; -----------------------------------------
+
 (defonce game-loop (start-game-loop))
-
 (defn send-game-event! [e] (put! (game-loop :game-events) e))
 (defn sent-menu-event! [e] (put! (game-loop :menu-events) e))


Allow connections to any server

Allow connections to any server

--- src/clojure/nightmod/sandbox.clj
+++ src/clojure/nightmod/sandbox.clj
@@ -72,7 +72,7 @@
                       (str File/separatorChar "*")
                       (FilePermission. "write")))
             (.add (ReflectPermission. "suppressAccessChecks"))
-            (.add (SocketPermission. "play-clj.net" "connect")))
+            (.add (SocketPermission. "*" "connect")))
           jvm/domain
           jvm/context))))

@@ -174,7 +174,3 @@
             (= screen (:screen screens/overlay-screen)))
       (screen-fn)
       (run-in-sandbox! screen-fn))))
-
-; use the play-clj.net server
-(intern 'play-clj.net-utils 'client-send-address "tcp://play-clj.net:4707")
-(intern 'play-clj.net-utils 'client-receive-address "tcp://play-clj.net:4708")


Fix core lint errors

Fix core lint errors

--- src/com/wsscode/pathom/core.cljc
+++ src/com/wsscode/pathom/core.cljc
@@ -10,7 +10,6 @@
         :cljs com.wsscode.async.async-cljs)
      :as casync
      :refer [go-catch <? let-chan chan? <?maybe <!maybe go-promise]]
-    [com.wsscode.pathom.misc :as p.misc]
     [com.wsscode.pathom.parser :as pp]
     [com.wsscode.pathom.trace :as pt]
     [edn-query-language.core :as eql]
@@ -21,7 +20,6 @@
   #?(:clj
      (:import
        (clojure.lang
-         IAtom
          IDeref))))

 ;; pathom core
@@ -137,8 +135,9 @@
     #{}
     children))

-(defn deep-merge [& xs]
+(defn deep-merge
   "Merges nested maps without overwriting existing keys."
+  [& xs]
   (if (every? #(or (map? %) (nil? %)) xs)
     (apply merge-with deep-merge xs)
     (last xs)))
@@ -153,8 +152,9 @@
   [query-expr]
   (-> (query->ast query-expr) :children first))

-(defn ast->query [query-ast]
+(defn ast->query
   "Given an AST convert it back into a query expression."
+  [query-ast]
   (pp/ast->expr query-ast true))

 (defn filter-ast [f ast]
@@ -979,8 +979,9 @@

 (def trace-plugin pt/trace-plugin)

-(defn collapse-error-path [m path]
+(defn collapse-error-path
   "Reduces the error path to the last available nesting on the map m."
+  [m path]
   (vec
     (loop [path' path]
       (if (zero? (count path'))
@@ -989,7 +990,7 @@
           path'
           (recur (butlast path')))))))

-(defn raise-errors [data]
+(defn raise-errors
   "Extract errors from the data root and inject those in the same level where
    the error item is present. For example:

@@ -1003,6 +1004,7 @@
             :com.wsscode.pathom.core/errors {:item {:error \"some error\"}}}

    This makes easier to reach for the error when rendering the UI."
+  [data]
   (reduce
     (fn [m [path err]]
       (if (= ::reader-error (get-in m path))
@@ -1355,9 +1357,10 @@
   (let [key (some-> ast :key)]
     (if (sequential? key) (second key))))

-(defn ensure-attrs [env attributes]
+(defn ensure-attrs
   "DEPRECATED: use p/entity
   Runs the parser against current element to garantee that some fields are loaded.
   This is useful when you need to ensure some values are loaded in order to fetch some
   more complex data."
+  [env attributes]
   (entity env attributes))


structure driven crawler now gets to use the entire state action

--- src/crawler/structure_driven.clj
+++ src/crawler/structure_driven.clj
@@ -15,4 +15,4 @@
   [body example-leaf]
   (similarity/similar? body example-leaf))

-(def extractor rc-extractor/state-action-sampled)
+(def extractor rc-extractor/state-action)


Store agree / disagree on user click

Store agree / disagree on user click

--- src/discuss/references/main.cljs
+++ src/discuss/references/main.cljs
@@ -24,6 +24,12 @@
   (let [url (str (:base config/api) (get-in config/api [:get :reference-usages]) "/" reference-id)]
     (com/ajax-get url {} reference-usage-handler)))

+(defn save-statement-change-view
+  "Saves the current selected statement (or the only one if there is only one available) and changes to
+   the view to configure own attitude."
+  [statement]
+  (rlib/save-selected-statement! statement)
+  (lib/change-view! :reference-agree-disagree))

 ;;;; Interaction with integrated references
 (defn click-reference
@@ -61,9 +67,7 @@
             author (:author data)]
         (dom/div #js {:className "bs-callout bs-callout-info"}
                  (dom/a #js {:href    "javascript:void(0)"
-                             :onClick (fn [_]
-                                        (rlib/save-selected-statement! data)
-                                        (lib/change-view! :reference-agree-disagree))}
+                             :onClick #(save-statement-change-view data)}
                         (dom/strong nil (:text statement)))
                  (dom/div nil "Issue: " (:title issue))
                  (dom/div nil "Author: " (:nickname author)))))))
@@ -94,10 +98,10 @@
                           "Do you agree or disagree with this statement?")
                  (om/build usage-view statement)
                  (dom/div #js {:className "text-center"}
-                          (bs/button-primary #(println "foo")
+                          (bs/button-primary #(rlib/supportive? true)
                                              (vlib/fa-icon "fa-thumbs-up")
                                              " Agree")
                           " "
-                          (bs/button-primary nil
+                          (bs/button-primary #(rlib/supportive? false)
                                              (vlib/fa-icon "fa-thumbs-down")
                                              " Disagree")))))))


Allow the content type to be multi-valued.

--- src/dragon/blog/content/core.clj
+++ src/dragon/blog/content/core.clj
@@ -1,18 +1,33 @@
 (ns dragon.blog.content.core
-  (:require [dragon.blog.content.rfc5322 :as rfc5322]
+  (:require [clojure.string :as string]
+            [dragon.blog.content.rfc5322 :as rfc5322]
             [dragon.event.system.core :as event]
             [dragon.event.tag :as tag]
+            [taoensso.timbre :as log]
             [trifl.fs :as fs]))
+
+(defn parse-content-type
+  [content-type]
+  (let [types (string/split content-type #",")
+        parts (count types)]
+    (if (= 1 parts)
+      (keyword content-type)
+      (map (comp keyword string/trim) types))))
+
+(defn file-extension-dispatch
+  [system content extension]
+  (case extension
+        :rfc5322 (rfc5322/parse system content)
+        :default {:raw-data content
+                  :error :parser-not-found}))

 (defn parse
   [system file-obj]
   (event/publish system tag/read-source-pre {:file file-obj})
-  (let [file-type (fs/extension file-obj)
+  (let [extension (fs/extension file-obj)
         content (slurp file-obj)]
     (event/publish system tag/read-source-post {:file file-obj})
-    (assoc
-      (case file-type
-        :rfc5322 (rfc5322/parse system content)
-        :default {:raw-data content
-                  :error :parser-not-found})
-     :file-type file-type)))
+    (-> extension
+        ((partial file-extension-dispatch system content))
+        (update-in [:content-type] parse-content-type)
+        (assoc :file-type extension))))


Example of a 500 status response

Example of a 500 status response

Just checking this is working after a conversation with David Smith.

--- dev/src/yada/dev/docsite.clj
+++ dev/src/yada/dev/docsite.clj
@@ -125,6 +125,13 @@

       ["/h1.html" (yada [:h1 "Heading"])]

+      ["/500" (resource
+               {:methods {:get {:produces "text/html"
+                                :response (fn [ctx] (throw (new Exception "Ooh!")))}}
+                :responses {500 {:produces "text/plain"
+                                 :response (fn [ctx] "Error, but I'm OK")}}}
+               )]
+
       ["/404" (resource
                {:properties {:exists? false}
                 :methods {:get nil}


improve cassandra model schema

improve cassandra model schema

--- src/er_cassandra/model/types.clj
+++ src/er_cassandra/model/types.clj
@@ -22,11 +22,13 @@
   (s/conditional

    (fn [k] (-> k first sequential?))
-   [(s/optional [s/Keyword] :compound-parition-key)
+   [(s/one
+     [(s/one s/Keyword :partition-key-component) s/Keyword]
+     :compound-parition-key)
     s/Keyword]

    :else
-   [s/Keyword]))
+   [(s/one s/Keyword :key-component) s/Keyword]))

 (s/defschema KeyValueSchema
   [(s/one s/Any :key-component) s/Any])
@@ -58,7 +60,7 @@

 ;; basic table schema shared by primary, secondary
 ;; unique-key and lookup tables
-(s/defschema TableSchema
+(s/defschema BaseTableSchema
   {:name s/Keyword
    :key KeySchema
    (s/optional-key :relationships) [RelationshipSchema]})
@@ -70,8 +72,9 @@
 ;; delete with a secondary index from seocondary and lookup tables
 ;; TODO use the :entity-key to delete stale secondary and lookup records
 (s/defschema PrimaryTableSchema
-  (merge TableSchema
-         {(s/optional-key :entity-key) SecondaryKeySchema}))
+  (merge BaseTableSchema
+         {(s/optional-key :entity-key) SecondaryKeySchema}
+         {:type (s/eq :primary)}))

 ;; some of the (non-partition) columns in a lookup-table
 ;; key may be collections... these will be expanded to the
@@ -86,28 +89,42 @@
 (s/defschema EntityKeySchema
   {(s/optional-key :has-entity-key?) s/Bool})

+(s/defschema MaterializedViewSchema
+  {(s/optional-key :view?) s/Bool})
+
 ;; unique-key tables are lookup tables with a unique
 ;; constraint on the key, enforced with an LWT
 (s/defschema UniqueKeyTableSchema
-  (merge TableSchema
+  (merge BaseTableSchema
          CollectionKeysSchema
-         EntityKeySchema))
+         EntityKeySchema
+         {:type (s/eq :uniquekey)}))

 ;; secondary tables contain all columns from the primary
 ;; table, with a different primary key.
 ;; secondary and lookup tables may be materialized views,
 ;; which will be used for query but won't be upserted to
 (s/defschema SecondaryTableSchema
-  (merge TableSchema
+  (merge BaseTableSchema
          EntityKeySchema
-         {(s/optional-key :view?) s/Bool}))
+         MaterializedViewSchema
+         {:type (s/eq :secondary)}))

 ;; lookup tables contain columns from the uberkey and
 ;; a lookup key, plus any additional with-columns
 (s/defschema LookupTableSchema
   (merge SecondaryTableSchema
          CollectionKeysSchema
-         {(s/optional-key :with-columns) [s/Keyword]}))
+         MaterializedViewSchema
+         {(s/optional-key :with-columns) [s/Keyword]}
+         {:type (s/eq :lookup)}))
+
+(s/defschema TableSchema
+  (s/conditional
+   #(= (:type %) :primary) PrimaryTableSchema
+   #(= (:type %) :secondary) SecondaryTableSchema
+   #(= (:type %) :uniquekey) UniqueKeyTableSchema
+   #(= (:type %) :lookup) LookupTableSchema))

 (s/defschema EntitySchema
   {:primary-table PrimaryTableSchema
@@ -126,37 +143,42 @@
      callbacks :- CallbacksSchema
      versioned? :- s/Bool])

-(defn ^:private force-key-seq
-  [table]
-  (assoc table :key (v/coerce (:key table))))
-
-(defn ^:private force-key-seqs
-  [entity-schema table-seq-key]
+(defn ^:private conform-table
+  [table-type table]
+  (assoc table
+         :type table-type
+         :key (v/coerce (:key table))))
+
+(defn ^:private conform-tables
+  [entity-schema [table-type table-seq-key]]
   (assoc entity-schema
          table-seq-key
-         (mapv force-key-seq
+         (mapv (partial conform-table table-type)
                (get entity-schema table-seq-key))))

-(defn ^:private force-all-key-seqs
+(defn ^:private conform-all-tables
   "ensure all keys are given as sequences of components"
   [entity-schema]
-  (reduce force-key-seqs
+  (reduce conform-tables
           (assoc entity-schema
                  :primary-table
-                 (force-key-seq (:primary-table entity-schema)))
-          [:unique-key-tables
-           :secondary-tables
-           :lookup-key-tables]))
+                 (conform-table :primary (:primary-table entity-schema)))
+          [[:uniquekey :unique-key-tables]
+           [:secondary :secondary-tables]
+           [:lookup :lookup-key-tables]]))

 (s/defn ^:always-validate create-entity :- Entity
   "create an entity record from a spec"
-  [entity-spec :- EntitySchema]
-  (map->Entity (merge {:unique-key-tables []
-                       :secondary-tables []
-                       :lookup-key-tables []
-                       :callbacks {}
-                       :versioned? false}
-                      (force-all-key-seqs entity-spec))))
+  [entity-spec]
+  (let [spec (conform-all-tables entity-spec)]
+    (s/validate EntitySchema spec)
+    (strict-map->Entity
+     (merge {:unique-key-tables []
+             :secondary-tables []
+             :lookup-key-tables []
+             :callbacks {}
+             :versioned? false}
+            spec))))

 (defmacro defentity
   [name entity-spec]


Whitespace

Whitespace

--- src/foreclojure/problems.clj
+++ src/foreclojure/problems.clj
@@ -138,7 +138,7 @@
          :else (str "You've solved the problem! If you "
                     (login-link "log in" (str "/problem/" _id)) " we can track your progress."))]
     (session/session-put! :code [_id code])
-    [(str message " " gist-link) (str "/problem/" _id)] ))
+    [(str message " " gist-link) (str "/problem/" _id)]))

 (def restricted-list '[use require in-ns future agent send send-off pmap pcalls])


Let emacs reindent this whole mess

Let emacs reindent this whole mess

--- src/foreclojure/problems.clj
+++ src/foreclojure/problems.clj
@@ -23,11 +23,11 @@
 (defn get-problem-list
   ([] (get-problem-list {:approved true}))
   ([criteria]
-    (from-mongo
-    (fetch :problems
-           :only [:_id :title :tags :times-solved :user]
-           :where criteria
-           :sort {:_id 1}))))
+     (from-mongo
+      (fetch :problems
+             :only [:_id :title :tags :times-solved :user]
+             :where criteria
+             :sort {:_id 1}))))

 (defn next-unsolved-problem [solved-problems]
   (when-let [unsolved (->> (get-problem-list)
@@ -208,8 +208,8 @@
        [:span#message-text (session/flash-get :message)]]
       (render-golf-score)]
      (form-to {:id "run-code"} [:post *url*]
-              [:br]
-              [:br]
+       [:br]
+       [:br]
        [:p#instruct "Code which fills in the blank: "]
        (text-area {:id "code-box"
                    :spellcheck "false"}
@@ -221,8 +221,8 @@
        [:button.large {:id "run-button" :type "submit"} "Run"]
        (when-not approved
          [:span [:button.large {:id "reject-button"} "Reject"]
-                [:button.large {:id "edit-button"} "Edit"]
-                [:button.large {:id "approve-button"} "Approve"]]))]))
+          [:button.large {:id "edit-button"} "Edit"]
+          [:button.large {:id "approve-button"} "Approve"]]))]))

 (def-page problem-page []
   [:div.message (session/flash-get :message)]
@@ -285,22 +285,22 @@

 (def-page problem-submission-page []
   [:div.instructions
-    [:p "Thanks for choosing to submit a problem. Please make sure that you own the rights to the code you are submitting and that you wouldn't mind having us use the code as a 4clojure problem."]]
+   [:p "Thanks for choosing to submit a problem. Please make sure that you own the rights to the code you are submitting and that you wouldn't mind having us use the code as a 4clojure problem."]]
   (form-to {:id "problem-submission"} [:post "/problems/submit"]
-           (hidden-field :author (session/flash-get :author))
-           (hidden-field :prob-id (session/flash-get :prob-id))
-           (label :title "Problem Title")
-           (text-field :title  (session/flash-get :title))
-           (label :tags "Tags (space separated)")
-           (text-field :tags  (session/flash-get :tags))
-           (label :description "Problem Description")
-           (text-area {:id "problem-description"} :description  (session/flash-get :description))
-           [:br]
-           (label :code-box "Problem test cases. Use two underscores (__) for user input. Multiple tests ought to be on one line each.")
-           (text-area {:id "code-box" :spellcheck "false"}
-                         :code (session/flash-get :tests))
-           [:p
-             [:button.large {:id "run-button" :type "submit"} "Submit"]]))
+    (hidden-field :author (session/flash-get :author))
+    (hidden-field :prob-id (session/flash-get :prob-id))
+    (label :title "Problem Title")
+    (text-field :title  (session/flash-get :title))
+    (label :tags "Tags (space separated)")
+    (text-field :tags  (session/flash-get :tags))
+    (label :description "Problem Description")
+    (text-area {:id "problem-description"} :description  (session/flash-get :description))
+    [:br]
+    (label :code-box "Problem test cases. Use two underscores (__) for user input. Multiple tests ought to be on one line each.")
+    (text-area {:id "code-box" :spellcheck "false"}
+               :code (session/flash-get :tests))
+    [:p
+     [:button.large {:id "run-button" :type "submit"} "Submit"]]))

 (defn create-problem
   "create a user submitted problem"
@@ -342,8 +342,8 @@
   (if (approver? (session/session-get :user))
     (do
       (update! :problems
-        {:_id id}
-        {:$set {:approved true}})
+               {:_id id}
+               {:$set {:approved true}})
       (flash-msg (str "Problem " id " has been approved!")
                  (str "/problem/" id)))
     (flash-error "You don't have access to this page" "/problems")))
@@ -354,7 +354,7 @@
     (let [{:keys [user title description tags tests]} (get-problem id)
           email (:email (get-user user))]
       (destroy! :problems
-        {:_id id})
+                {:_id id})
       (send-email
        {:from "team@4clojure.com"
         :to [email]
@@ -374,10 +374,10 @@
   (GET "/problem/:id" [id] (code-box id))
   (GET "/problems/submit" [] (problem-submission-page))
   (POST "/problems/submit" [prob-id author title tags description code]
-        (create-problem title tags description code (when (not= "" prob-id) (Integer. prob-id)) author))
+    (create-problem title tags description code (when (not= "" prob-id) (Integer. prob-id)) author))
   (GET "/problems/unapproved" [] (unapproved-problems))
   (POST "/problem/edit" [id]
-        (edit-problem (Integer. id)))
+    (edit-problem (Integer. id)))
   (POST "/problem/approve" [id]
     (approve-problem (Integer. id)))
   (POST "/problem/reject" [id]


Reindent letfn in unnest-dispatch-table

Reindent letfn in unnest-dispatch-table

--- src/io/aviso/rook/dispatcher.clj
+++ src/io/aviso/rook/dispatcher.clj
@@ -142,32 +142,32 @@
   without introducing a separate route."
   [dispatch-table]
   (letfn [(unnest-entry [default-middleware [x :as entry]]
-                        (cond
-                          (keyword? x)
-                          (let [[method pathvec verb-fn middleware & nested-table] entry]
-                            (if nested-table
-                              (let [mw (or middleware default-middleware)]
-                                (into [[method pathvec verb-fn mw]]
-                                      (unnest-table pathvec mw nested-table)))
-                              (cond-> [entry]
-                                      (nil? middleware) (assoc-in [0 3] default-middleware))))
-
-                          (vector? x)
-                          (let [[context-pathvec & maybe-middleware+entries] entry
-                                middleware (if-not (vector?
-                                                     (first maybe-middleware+entries))
-                                             (first maybe-middleware+entries))
-                                entries (if middleware
-                                          (next maybe-middleware+entries)
-                                          maybe-middleware+entries)]
-                            (unnest-table context-pathvec middleware entries))))
+            (cond
+              (keyword? x)
+              (let [[method pathvec verb-fn middleware & nested-table] entry]
+                (if nested-table
+                  (let [mw (or middleware default-middleware)]
+                    (into [[method pathvec verb-fn mw]]
+                      (unnest-table pathvec mw nested-table)))
+                  (cond-> [entry]
+                    (nil? middleware) (assoc-in [0 3] default-middleware))))
+
+              (vector? x)
+              (let [[context-pathvec & maybe-middleware+entries] entry
+                    middleware (if-not (vector?
+                                         (first maybe-middleware+entries))
+                                 (first maybe-middleware+entries))
+                    entries (if middleware
+                              (next maybe-middleware+entries)
+                              maybe-middleware+entries)]
+                (unnest-table context-pathvec middleware entries))))
           (unnest-table [context-pathvec default-middleware entries]
-                        (mapv (fn [[_ pathvec :as unnested-entry]]
-                                (assoc unnested-entry 1
-                                                      (with-meta (into context-pathvec pathvec)
-                                                                 {:context (into context-pathvec
-                                                                                (:context (meta pathvec)))})))
-                              (mapcat (partial unnest-entry default-middleware) entries)))]
+            (mapv (fn [[_ pathvec :as unnested-entry]]
+                    (assoc unnested-entry 1
+                           (with-meta (into context-pathvec pathvec)
+                             {:context (into context-pathvec
+                                         (:context (meta pathvec)))})))
+              (mapcat (partial unnest-entry default-middleware) entries)))]
     (unnest-table [] nil dispatch-table)))

 (defn- keywords->symbols


refactor

refactor

--- src/kbilling/calc/transform.cljs
+++ src/kbilling/calc/transform.cljs
@@ -55,19 +55,21 @@
 (defn transitive-billing-cycles [plan ck]
   (transitive-image #(or (-> plan :$cycles % :$begin) #{}) #{} ck))

+(defn var? [key] (not (contains? #{:$begin :$duration} key)))
+
 (def acc-keys
   (memoize #(into #{} (for [[_ c] (:$cycles %)
-                            [acck _] c :when (not (contains? #{:$begin :$duration} acck))]
+                            [acck _] c :when (var? acck)]
                         acck))))

 (defn init-vars [plan cycles vars]
   (let [acc-vars (into {} (for [acck (acc-keys plan) :when (not (acck vars))]
                             [acck 0]))
         cost-vars (into {} (for [[ck c] (:$cycles plan) :when (contains? cycles ck)
-                                 [acck acc] c :when (and (not (contains? #{:$begin :$duration} acck)) (:$cost acc))]
+                                 [acck acc] c :when (and (var? acck) (:$cost acc))]
                              [(k_ ck acck :$cost) 0]))
         agg-vars (into {} (for [[ck c] (:$cycles plan) :when (contains? cycles ck)
-                                [acck acc] c :when (not (contains? #{:$begin :$duration} acck))
+                                [acck acc] c :when (var? acck)
                                 [aggk agg] acc :let [agg-init (:$init agg)] :when agg-init]
                             [(k_ ck acck aggk) (agg-init)]))]
     (merge vars acc-vars cost-vars agg-vars)))