change midje indenting

change midje indenting

--- test/com/billpiel/mem_tracer/core_test.clj
+++ test/com/billpiel/mem_tracer/core_test.clj
@@ -42,118 +42,118 @@
 (defn remove-iso-ctrl [s]  (apply str (remove #(Character/isISOControl %) s)))

 (fact-group "basic test"
-            (mtt/untrace-ns* 'com.billpiel.mem-tracer.test.ns1)
-            (mt/reset-workspace!)
-            (with-redefs [mtt/now (mock-now-fn)
-                          gensym (mock-gensym-fn)]
-
-              (mt/add-trace-ns! 'com.billpiel.mem-tracer.test.ns1)
-              (com.billpiel.mem-tracer.test.ns1/func1 :a)
-              (let [trace (mt/deref-workspace!)
-                    expected-trace {:id "root10",
-                                    :depth 0,
-                                    :children
-                                    [{:args [:a],
-                                      :children
-                                      [{:args [:a],
-                                        :children [],
-                                        :return :a,
-                                        :started-at #inst "2010-01-01T02:00:00.000-00:00",
-                                        :name "com.billpiel.mem-tracer.test.ns1/func2",
-                                        :id "12",
-                                        :parent-id "11",
-                                        :ended-at #inst "2010-01-01T03:00:00.000-00:00",
-                                        :depth 2}],
-                                      :return :a,
-                                      :started-at #inst "2010-01-01T01:00:00.000-00:00",
-                                      :name "com.billpiel.mem-tracer.test.ns1/func1",
-                                      :id "11",
-                                      :parent-id "root10",
-                                      :ended-at #inst "2010-01-01T04:00:00.000-00:00",
-                                      :depth 1}],
-                                    :traced #{[:ns 'com.billpiel.mem-tracer.test.ns1]}}]
-
-                (fact "log is correct"
-                      trace
-                      => expected-trace)
-
-                (fact "string output is correct"
-                      (->> trace
-                           mt/entry->string
-                           remove-iso-ctrl)
-                      => "[31m [1;37m>[31m[m[33m [33m|[1;37m>[33mcom.billpiel.mem-tracer.test.ns1/func1[m [33m|  [33m:a[0m[m [33m| return =>  [33m|  [33m:a[0m[m[32m [33m|[32m|[1;37m>[32mcom.billpiel.mem-tracer.test.ns1/func2[m [33m|[32m|  [33m:a[0m[m [33m|[32m| return =>  [33m|[32m|  [33m:a[0m[m [33m| return =>  [33m|  [33m:a[0m[m")
-
-                (fact "remove trace"
-                      (mt/remove-trace-ns! 'com.billpiel.mem-tracer.test.ns1)
-                      (com.billpiel.mem-tracer.test.ns1/func1 :b)
-                      (mt/deref-workspace!) => (assoc expected-trace
-                                                      :traced #{})))
-
-              (mtt/untrace-ns* 'com.billpiel.mem-tracer.test.ns1)))
+  (mtt/untrace-ns* 'com.billpiel.mem-tracer.test.ns1)
+  (mt/reset-workspace!)
+  (with-redefs [mtt/now (mock-now-fn)
+                gensym (mock-gensym-fn)]
+
+    (mt/add-trace-ns! 'com.billpiel.mem-tracer.test.ns1)
+    (com.billpiel.mem-tracer.test.ns1/func1 :a)
+    (let [trace (mt/deref-workspace!)
+          expected-trace {:id "root10",
+                          :depth 0,
+                          :children
+                          [{:args [:a],
+                            :children
+                            [{:args [:a],
+                              :children [],
+                              :return :a,
+                              :started-at #inst "2010-01-01T02:00:00.000-00:00",
+                              :name "com.billpiel.mem-tracer.test.ns1/func2",
+                              :id "12",
+                              :parent-id "11",
+                              :ended-at #inst "2010-01-01T03:00:00.000-00:00",
+                              :depth 2}],
+                            :return :a,
+                            :started-at #inst "2010-01-01T01:00:00.000-00:00",
+                            :name "com.billpiel.mem-tracer.test.ns1/func1",
+                            :id "11",
+                            :parent-id "root10",
+                            :ended-at #inst "2010-01-01T04:00:00.000-00:00",
+                            :depth 1}],
+                          :traced #{[:ns 'com.billpiel.mem-tracer.test.ns1]}}]
+
+      (fact "log is correct"
+        trace
+        => expected-trace)
+
+      (fact "string output is correct"
+        (->> trace
+             mt/entry->string
+             remove-iso-ctrl)
+        => "[31m [1;37m>[31m[m[33m [33m|[1;37m>[33mcom.billpiel.mem-tracer.test.ns1/func1[m [33m|  [33m:a[0m[m [33m| return =>  [33m|  [33m:a[0m[m[32m [33m|[32m|[1;37m>[32mcom.billpiel.mem-tracer.test.ns1/func2[m [33m|[32m|  [33m:a[0m[m [33m|[32m| return =>  [33m|[32m|  [33m:a[0m[m [33m| return =>  [33m|  [33m:a[0m[m")
+
+      (fact "remove trace"
+        (mt/remove-trace-ns! 'com.billpiel.mem-tracer.test.ns1)
+        (com.billpiel.mem-tracer.test.ns1/func1 :b)
+        (mt/deref-workspace!) => (assoc expected-trace
+                                        :traced #{})))
+
+    (mtt/untrace-ns* 'com.billpiel.mem-tracer.test.ns1)))

 (fact-group "about enable/disable -all-traces!"
-            (mtt/untrace-ns* 'com.billpiel.mem-tracer.test.ns1)
-            (mt/reset-workspace!)
-            (with-redefs [mtt/now (mock-now-fn)
-                          gensym (mock-gensym-fn)]
-
-              (mt/add-trace-ns! 'com.billpiel.mem-tracer.test.ns1)
-
-              (fact "disable-all-traces! works"
-                    (mt/disable-all-traces!)
-                    (com.billpiel.mem-tracer.test.ns1/func1 :a)
-
-                    (mt/deref-workspace!)
-                    => {:children []
-                        :depth 0
-                        :id "root10"
-                        :traced #{[:ns 'com.billpiel.mem-tracer.test.ns1]}})
-
-              (fact "enable-all-traces! works"
-                    (mt/enable-all-traces!)
-                    (com.billpiel.mem-tracer.test.ns1/func1 :a)
-
-                    (mt/deref-workspace!)
-                    => {:children [{:args [:a]
-                                    :children [{:args [:a]
-                                                :children []
-                                                :depth 2
-                                                :ended-at #inst "2010-01-01T03:00:00.000-00:00"
-                                                :id "12"
-                                                :name "com.billpiel.mem-tracer.test.ns1/func2"
-                                                :parent-id "11"
-                                                :return :a
-                                                :started-at #inst "2010-01-01T02:00:00.000-00:00"}]
-                                    :depth 1
-                                    :ended-at #inst "2010-01-01T04:00:00.000-00:00"
-                                    :id "11"
-                                    :name "com.billpiel.mem-tracer.test.ns1/func1"
-                                    :parent-id "root10"
-                                    :return :a
-                                    :started-at #inst "2010-01-01T01:00:00.000-00:00"}]
-                        :depth 0
-                        :id "root10"
-                        :traced #{[:ns 'com.billpiel.mem-tracer.test.ns1]}})
-
-              (mtt/untrace-ns* 'com.billpiel.mem-tracer.test.ns1)))
+  (mtt/untrace-ns* 'com.billpiel.mem-tracer.test.ns1)
+  (mt/reset-workspace!)
+  (with-redefs [mtt/now (mock-now-fn)
+                gensym (mock-gensym-fn)]
+
+    (mt/add-trace-ns! 'com.billpiel.mem-tracer.test.ns1)
+
+    (fact "disable-all-traces! works"
+      (mt/disable-all-traces!)
+      (com.billpiel.mem-tracer.test.ns1/func1 :a)
+
+      (mt/deref-workspace!)
+      => {:children []
+          :depth 0
+          :id "root10"
+          :traced #{[:ns 'com.billpiel.mem-tracer.test.ns1]}})
+
+    (fact "enable-all-traces! works"
+      (mt/enable-all-traces!)
+      (com.billpiel.mem-tracer.test.ns1/func1 :a)
+
+      (mt/deref-workspace!)
+      => {:children [{:args [:a]
+                      :children [{:args [:a]
+                                  :children []
+                                  :depth 2
+                                  :ended-at #inst "2010-01-01T03:00:00.000-00:00"
+                                  :id "12"
+                                  :name "com.billpiel.mem-tracer.test.ns1/func2"
+                                  :parent-id "11"
+                                  :return :a
+                                  :started-at #inst "2010-01-01T02:00:00.000-00:00"}]
+                      :depth 1
+                      :ended-at #inst "2010-01-01T04:00:00.000-00:00"
+                      :id "11"
+                      :name "com.billpiel.mem-tracer.test.ns1/func1"
+                      :parent-id "root10"
+                      :return :a
+                      :started-at #inst "2010-01-01T01:00:00.000-00:00"}]
+          :depth 0
+          :id "root10"
+          :traced #{[:ns 'com.billpiel.mem-tracer.test.ns1]}})
+
+    (mtt/untrace-ns* 'com.billpiel.mem-tracer.test.ns1)))

 (fact-group "about remove-all-traces!"
-            (mtt/untrace-ns* 'com.billpiel.mem-tracer.test.ns1)
-            (mt/reset-workspace!)
-            (with-redefs [mtt/now (mock-now-fn)
-                          gensym (mock-gensym-fn)]
-
-              (mt/add-trace-ns! 'com.billpiel.mem-tracer.test.ns1)
-
-              (fact "remove-all-traces! works"
-                    (mt/remove-all-traces!)
-                    (com.billpiel.mem-tracer.test.ns1/func1 :a)
-
-                    (mt/deref-workspace!)
-                    => {:children [] :depth 0 :id "root10" :traced #{}})
-
-              (mtt/untrace-ns* 'com.billpiel.mem-tracer.test.ns1)))
+  (mtt/untrace-ns* 'com.billpiel.mem-tracer.test.ns1)
+  (mt/reset-workspace!)
+  (with-redefs [mtt/now (mock-now-fn)
+                gensym (mock-gensym-fn)]
+
+    (mt/add-trace-ns! 'com.billpiel.mem-tracer.test.ns1)
+
+    (fact "remove-all-traces! works"
+      (mt/remove-all-traces!)
+      (com.billpiel.mem-tracer.test.ns1/func1 :a)
+
+      (mt/deref-workspace!)
+      => {:children [] :depth 0 :id "root10" :traced #{}})
+
+    (mtt/untrace-ns* 'com.billpiel.mem-tracer.test.ns1)))

 (def mock-log {:children
                [{:args [:a],


fixed test

fixed test

--- test/iwaswhere_web/questionnaires_test.clj
+++ test/iwaswhere_web/questionnaires_test.clj
@@ -109,14 +109,13 @@
                               current-state
                               stats-test-entries)]
         (testing "correct scores for filled forms"
-          (let [stats (sq/questionnaires new-state)]
-            (is (= {:cfq11 {}
-                    :fs    {}
-                    :fss   {}
-                    :panas {1450999000001 {:neg 10
+          (let [stats (sq/questionnaires new-state)
+                with-results (into {} (filter #(seq (second %)) stats))
+                ]
+            (is (= {:panas {1450999000001 {:neg 10
                                            :pos 10}
                             1450999000002 {:neg 29
                                            :pos 31}
                             1450999000003 {}
                             1450999000004 {:pos 31}}}
-                   stats))))))))
+                   with-results))))))))


fixing the styling for the anonymous-home function

--- src-cljs/bitfondue/core.cljs
+++ src-cljs/bitfondue/core.cljs
@@ -131,10 +131,11 @@

 (defn home-anonymous []
   [layout [:div.jumbotron
-           [:h1 "Save all the pages!"]
-           [:p.lead "Saving things without the hassle of tagging."]
-           [:p.lead
-            [:a.btn.btn-primary.btn-lg (nav-helper "/register") "Register"]]]])
+           [:div.container
+            [:h1 "Save all the pages!"]
+            [:p.lead "Saving things without the hassle of tagging."]
+            [:p.lead
+             [:a.btn.btn-primary.btn-lg (nav-helper "/register") "Register"]]]]])

 (defn home-authenticated []
   [layout


Add ^:private flag to private lense on canvas ns.

--- frontend/uxbox/ui/workspace/canvas.cljs
+++ frontend/uxbox/ui/workspace/canvas.cljs
@@ -24,7 +24,7 @@
 ;; Lenses
 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

-(def ^:static shapes-by-id
+(def ^:static ^:private shapes-by-id
   (as-> (l/key :shapes-by-id) $
     (l/focus-atom $ st/state)))


Add radio buttons to select entities

Add radio buttons to select entities

--- src/cljs/org/broadinstitute/firecloud_ui/page/workspace/method_config_editor.cljs
+++ src/cljs/org/broadinstitute/firecloud_ui/page/workspace/method_config_editor.cljs
@@ -163,18 +163,16 @@
           {:style {:width "50%" :minWidth 50 :maxWidth 200} :ref "filter"
            :onChange #(let [value (-> (@refs "filter") .getDOMNode .-value)]
                        (when-not (= value "Select...")
-                         (utils/ajax-orch
+                         (utils/call-ajax-orch
                            (paths/list-all-entities-path workspace value)
-                           {:on-done
-                            (fn [{:keys [success? xhr]}]
-                              (if success?
-                                (swap! state assoc :entities (utils/parse-json-string (.-responseText xhr)))
-                                (utils/rlog "Error: " (.-responseText xhr))))
-                            :canned-response {:responseText (utils/->json-string
-                                                              [{"entityType" value
-                                                               "name" "A mock entity"
-                                                               "attributes" {}}])
-                                              :status 200 :delay-ms (rand-int 1000)}})))}
+                           {:on-success (fn [{:keys [parsed-response]}]
+                                          (swap! state assoc :entities parsed-response
+                                            :selected-entity (first parsed-response)))
+                            :on-failure (fn [{:keys [status-text]}]
+                                          (utils/rlog "Error: " status-text))
+                            :mock-data [{"entityType" value
+                                         "name" "A mock entity"
+                                         "attributes" {}}]})))}
           (:entity-types @state))
         (style/create-form-label "Select Entity")
         (if (zero? (count (:entities @state)))
@@ -182,11 +180,17 @@
           [:div {:style {:backgroundColor "#fff" :border (str "1px solid " (:line-gray style/colors))
                          :padding "1em" :marginBottom "0.5em"}}
            [table/Table
-            {:columns [{:header "Entity Type" :starting-width 100}
+            {:columns [{:header "" :starting-width 40 :resizable? false
+                        :content-renderer (fn [row-index data]
+                                            [:input {:type "radio"
+                                                     :checked (identical? data (:selected-entity @state))
+                                                     :onChange #(swap! state assoc :selected-entity data)}])}
+                       {:header "Entity Type" :starting-width 100}
                        {:header "Entity Name" :starting-width 100}
                        {:header "Attributes" :starting-width 400}]
              :data (map (fn [m]
-                          [(m "entityType")
+                          [m
+                           (m "entityType")
                            (m "name")
                            (m "attributes")])
                      (:entities @state))}]])


annotate mixpanel events with whether the user is logged in

--- src-cljs/frontend/analytics.cljs
+++ src-cljs/frontend/analytics.cljs
@@ -45,6 +45,7 @@
     (mixpanel/track (str event) (merge
                                  (:analytics-data data)
                                  (dissoc (get-in state state/browser-settings-path) :document-settings)
+                                 {:logged-in? (boolean (get-in state [:cust :cust/email]))}
                                  (when (:document/id state)
                                    {:doc-id (:document/id state)
                                     :subscriber-count (count (get-in state [:subscribers :info]))})))))


moved the .container class into the individual views rather than the main layout function

--- src-cljs/bitfondue/core.cljs
+++ src-cljs/bitfondue/core.cljs
@@ -125,7 +125,7 @@
   [:div
    [header]
    [:br]
-   [:div.container content]
+   content
    [:br]
    [footer]])

@@ -137,16 +137,23 @@
             [:a.btn.btn-primary.btn-lg (nav-helper "/register") "Register"]]]])

 (defn home-authenticated []
-  [layout [chunks]])
+  [layout
+   [:div.container [chunks]]])

 (defn features []
-  [layout [:h1 "Features"]])
+  [layout
+   [:div.container
+    [:h1 "Features"]]])

 (defn pricing []
-  [layout [:h1 "Pricing"]])
+  [layout
+   [:div.container
+    [:h1 "Pricing"]]])

 (defn about []
-  [layout [:h1 "About"]])
+  [layout
+   [:div.container [:h1 "About"]]])
+

 (def login-form
   [:div.col-md-offset-3.col-md-6
@@ -178,10 +185,14 @@
     [:button.btn.btn-primary {:type "submit"} "Login"]]])

 (defn login []
-  [layout [:div.row login-form]])
+  [layout
+   [:div.container
+    [:div.row login-form]]])

 (defn register []
-  [layout [:div.row register-form]])
+  [layout
+   [:div.container
+    [:div.row register-form]]])

 (defn not-found []
   [layout [:h1 "404 - Page not found"]])


[#1949] Refine lib.auth/ids internals

[#1949] Refine lib.auth/ids internals

--- backend/src/akvo/lumen/lib/auth.clj
+++ backend/src/akvo/lumen/lib/auth.clj
@@ -3,6 +3,7 @@
    [akvo.commons.jwt :as jwt]
    [akvo.lumen.component.flow :as c.flow]
    [akvo.lumen.component.tenant-manager :as tenant-manager]
+   [akvo.lumen.specs :as lumen.s]
    [akvo.lumen.specs.dataset :as dataset.s]
    [akvo.lumen.specs.visualisation :as visualisation.s]
    [akvo.lumen.protocols :as p]
@@ -91,10 +92,15 @@
                    :visualisation-ids #{}})
         ds-fun (fn [id]
                  (swap! ids update-in [:dataset-ids] conj id)
-                 true)
+                 (try
+                   (lumen.s/str-uuid? id)
+                   (catch Exception e false)))
         vis-fun (fn [id]
                   (swap! ids update-in [:visualisation-ids] conj id)
-                  true)]
+                  (try
+                    (lumen.s/str-uuid? id)
+                    (catch Exception e false)
+                    ))]
     (binding [visualisation.s/*id?* vis-fun
               dataset.s/*id?* ds-fun]
       (let [explain (s/explain-str spec data)]


Diffing takes infinitely long

Diffing takes infinitely long

--- src/atom_finder/ast_diff.clj
+++ src/atom_finder/ast_diff.clj
@@ -105,7 +105,7 @@

  (.maxMemory (Runtime/getRuntime))

-(.computeEditDistance apted (diff-nodify ast-a) (diff-nodify ast-b))
+(def edit-distance (.computeEditDistance apted (diff-nodify ast-a) (diff-nodify ast-b)))

 (.computeEditDistance apted ast-before ast-after)
 (added-nodes apted ast-before ast-after)


add TODO

add TODO

--- src/babel/english/writer.clj
+++ src/babel/english/writer.clj
@@ -34,7 +34,9 @@
                                                    :model small-plus-vp-pronoun
                                                    }}]
                                                 source-language-short-name)]
-                                   (log/info (str "process result:" result)))
+                                   ;; TODO: 'result' is currently returning nil: should return something more indicative
+                                   ;; of what the (process) command did.
+                                   (log/debug (str "process result:" result)))
                                 (catch Exception e
                                   true
                                   (throw e)))))))))


don't catch exceptions so I can catch Spanish generation problems

--- src/babel/espanol/writer.clj
+++ src/babel/espanol/writer.clj
@@ -9,7 +9,7 @@
 (require '[babel.espanol.pos :refer :all])
 (require '[babel.lexiconfn :refer (compile-lex map-function-on-map-vals unify)])
 (require '[babel.espanol.lexicon :refer [lexicon]])
-(require '[babel.espanol.morphology :as morph :refer [fo]])
+(require '[babel.espanol.morphology :as morph :refer [fo morph-walk-tree]])
 (require '[babel.parse :as parse])
 (require '[babel.ug :refer :all])
 (require '[babel.writer :refer [process write-lexicon]])
@@ -81,10 +81,10 @@
                                                                         ;; subject), but we're trying to generate with
                                                                         ;; {:agr {:person :1st or :2nd}}, for which the only lexemes
                                                                         ;; are human.
-                                                                        true
+                                                                        false

                                                                         (log/warn (str "ignoring exception: " e))
-                                                                        false
+                                                                        true
                                                                        (throw e))))
                                                                    ))
                                                                [:sing :plur]))))


Make user-set-preference-txn compose properly

Because it now may be running in a transaction with other datoms, it
needs to have a unique tempid

--- src/braid/server/db/user.clj
+++ src/braid/server/db/user.clj
@@ -175,4 +175,4 @@
     [{:user.preference/key k
       :user.preference/value (pr-str v)
       :user/_preferences [:user/id user-id]
-      :db/id #db/id [:entities]}]))
+      :db/id (d/tempid :entities)}]))


remove unused run-forever function

remove unused run-forever function

--- src/brainbot/nozzle/misc.clj
+++ src/brainbot/nozzle/misc.clj
@@ -58,16 +58,3 @@

   (doseq [name ["org.apache.pdfbox" "com.coremedia"]]
     (log-config/set-logger! name :level :off)))
-
-
-(defn run-forever
-  "run function forever, i.e. run function, catch exception, wait a
- bit and restart it"
-  [sleeptime function & args]
-  (while true
-    (try
-      (apply function args)
-      (catch Throwable err
-        (logging/error "got exception" err "while running" function "with" args)
-        (trace/print-stack-trace err)
-        (Thread/sleep sleeptime)))))


add reverse lookup from id number to keyword for the points

--- src/clj/ephemeris/points.clj
+++ src/clj/ephemeris/points.clj
@@ -1,13 +1,16 @@
 (ns ephemeris.points
   (:import (swisseph SweConst)))

-(def ^:private db (atom {}))
+(def ^:private dat (atom {}))
+(def ^:private rev (atom {}))

 (defn- a
   ([id idn] (a id idn nil))
-  ([id idn greek] (swap! db conj {id {:id idn
-                                      :en (name id)
-                                      :gr greek}})))
+  ([id idn greek]
+   (do (swap! dat conj {id {:id idn
+                            :en (name id)
+                            :gr greek}})
+       (swap! rev conj {idn id}))))

 (a :Sun (. SweConst SE_SUN) "Helios")
 (a :Moon (. SweConst SE_MOON) "Selene")
@@ -20,7 +23,7 @@
 (a :Neptune (. SweConst SE_NEPTUNE))
 (a :Pluto (. SweConst SE_PLUTO))

-(deref db)
-
 (defn lookup [what]
-  (get (get (deref db) what) :id))
+  (if (keyword? what)
+    (get (get (deref dat) what) :id)
+    (get (deref rev) what)))


Some more friendly error handling in embedded.

--- src/clj/fleetdb/embedded.clj
+++ src/clj/fleetdb/embedded.clj
@@ -1,5 +1,5 @@
 (ns fleetdb.embedded
-  (:use [fleetdb.util :only (def- ? spawn)]
+  (:use [fleetdb.util :only (def- ? spawn rassert raise)]
         [clojure.contrib.seq-utils :only (partition-all)])
   (:require (fleetdb [core :as core] [fair-lock :as fair-lock]
                      [io :as io] [file :as file] [lint :as lint]))
@@ -61,19 +61,19 @@
   true)

 (defn fork [dba]
-  (assert (ephemeral? dba))
+  (rassert (ephemeral? dba) "cannot fork persistent databases")
   (init* @dba))

 (defn snapshot [dba snapshot-path]
-  (assert (ephemeral? dba))
+  (rassert (ephemeral? dba) "cannot snapshot persistent databases")
   (let [tmp-path  (file/tmp-path "/tmp" "snapshot")]
     (write-to @dba tmp-path)
     (file/mv tmp-path snapshot-path)
     true))

 (defn compact [dba]
-  (assert (persistent? dba))
-  (assert (not (compacting? dba)))
+  (rassert (persistent? dba) "cannot compact ephemeral database")
+  (rassert (not (compacting? dba)) "already compacting database")
   (fair-lock/fair-locking (:write-lock (meta dba))
     (let [tmp-path      (file/tmp-path "/tmp" "compact")
           db-comp-start @dba]


add test-connection

add test-connection

--- src/clj/lesezeichen/core.clj
+++ src/clj/lesezeichen/core.clj
@@ -42,9 +42,9 @@
   (case topic
     :get-user-bookmarks {:topic topic
                          :data (get-user-bookmarks (:conn @server-state) data)}
-    :register {:topic topic
+    :sign-up  {:topic topic
                :data (add-user (:conn @server-state) data)}
-    :sign-in {:topic topic
+    :log-in {:topic topic
               :data (verify-user (:conn @server-state) data)}
     :add-bookmark {:topic topic
                    :data (add-bookmark (:conn @server-state)
@@ -66,6 +66,7 @@
                           (swap! server-state update-in [:out-chans] (fn [old new] (vec (remove #(= new %) old))) out-ch)
                           (close! out-ch)))
       (on-receive channel (fn [msg] (let [data (str (dispatch (read-string msg)))]
+                                     (println data)
                                      (send! channel data)
                                      (doall
                                       (map #(put! % data) (remove #{out-ch} (:out-chans @server-state))))))))))
@@ -86,7 +87,9 @@

 (defn init-db [state]
-  (swap! state #(assoc %1 :conn %2) (db-conn))
+  (let [conn (scratch-conn)]
+    (swap! state #(assoc %1 :conn %2) conn))
+  (init-schema (:conn @state) (:schema @state))
   state)

@@ -117,4 +120,7 @@
   ;; on first startup initialize datomic schema
   (init-schema (:schema @server-state))

+
+  (get-all-users (:conn @server-state))
+
 )


Fix comments.

Fix comments.

--- src/cljam/util/intervals.clj
+++ src/cljam/util/intervals.clj
@@ -18,14 +18,14 @@
        (->SortedMapIntervals)))

 (defn index-intervals
-  "Make index for intervals to find overlaps."
+  "Make indexes for intervals to find overlaps."
   [intervals]
   (->> intervals
        (group-by :chr)
        (into {} (map (fn [[k vs]] [k (make-sorted-map-intervals vs)])))))

 (defn find-overlap-intervals
-  "Find intervals that is overlap query : chr and [start end]
-  from index data created by index-intervals."
+  "Find intervals that are on the given `chr` and overlap the given interval
+  [`start` `end`] using indexes created by `index-intervals`."
   [indexed-intervals chr start end]
   (find-overlap-intervals* (get indexed-intervals chr) start end))


Make crushing walls impassable

Make crushing walls impassable

--- src/cljc/robinson/world.cljc
+++ src/cljc/robinson/world.cljc
@@ -406,6 +406,8 @@
                :dry-hole
                :freshwater-hole
                :saltwater-hole
+               ;; traps
+               :crushing-wall
                ;; pirate ship types
                :bulkhead
                :wheel
@@ -482,6 +484,19 @@
   [t]
   (contains? #{:sand :surf} t))

+(defn collide-trap?
+   [state x y]
+   (when-let [place-id (current-place-id state)]
+     (some (fn [trap]
+             (case (get trap :type)
+               :crushing-wall
+                 (some (fn [[trap-x trap-y]]
+                         (and (= x trap-x)
+                              (= y trap-y)))
+                       (first (get trap :locations)))
+               false))
+          (get-in state [:world :places place-id :traps] []))))
+
 (defn collide?
   "Return `true` if the cell at `[x y]` is non-traverable. Ie: a wall, closed door or simply does
    not exist. Cells occupied by npcs are considered non-traversable."
@@ -502,6 +517,8 @@
         ;; water collides?
         (and collide-water?
              (= (cell :type) :water))
+        ;; trap collides?
+        (collide-trap? state x y)
         ;; player collides?
         (and collide-player?
              (= [x y] (rp/player-xy state)))


Try to figure out how to speed up next-state and add button for random cell gen

--- src/cljs/cljs_life/core.cljs
+++ src/cljs/cljs_life/core.cljs
@@ -3,6 +3,15 @@
             [om.dom :as dom :include-macros true]
             [cljs.core.async :refer (timeout <!)])
   (:require-macros [cljs.core.async.macros :refer (go)]))
+
+(defn add-timer
+  [f prefix]
+  (fn [& args]
+    (let [t (js/Date.)
+          r (apply f args)
+          t2 (js/Date.)]
+      (js/console.log prefix (- t2 t))
+      r)))

 (defn neighbors
   "Given a set of cells returns a seq of adjacent cells. If n cells share a
@@ -11,6 +20,7 @@
   (for [[x y] cells dx [-1 0 1] dy [-1 0 1]
         :when (not (and (zero? dx) (zero? dy)))]
     [(+ x dx) (+ y dy)]))
+

 (defn in-bounds?
   "Given bounds [width height] and a cell returns true if the cell is inside
@@ -33,20 +43,13 @@
           (hash-set)
           (frequencies (neighbors cells))))

+
 (defn update-state
   [{:keys [cells bounds] :as state}]
   (assoc state :cells (next-state cells bounds)))

-(defn add-timer
-  [f prefix]
-  (fn [& args]
-    (let [t (js/Date.)
-          r (apply f args)
-          t2 (js/Date.)]
-      (js/console.log prefix (- t2 t))
-      r)))

-(def update-state (add-timer update-state "update-state"))
+#_(def update-state (add-timer update-state "update-state"))

 (defn live!
@@ -90,6 +93,22 @@
                       (disj cells cell)
                       (conj cells cell))))))

+(defn random-cells
+  [[width height]]
+  (set (filter #(> (Math/random) 0.5)
+               (for [x (range 0 width)
+                     y (range 0 width)]
+                 (vector x y)))))
+
+(defonce app-state (atom {:cells #{}
+                          :bounds [50 20]
+                          :playing? false
+                          :cell-size 20
+                          :speed 5}))
+
+(defn reset-random!
+  []
+  (swap! app-state (fn [{b :bounds :as s}] (assoc s :cells (random-cells b)))))

 (defn world
   [app owner]
@@ -101,7 +120,10 @@
                  (dom/div nil
                           (dom/button
                             #js {:onClick (partial toggle-play-state app)}
-                            (if (:playing? app) "stop" "play")))
+                            (if (:playing? app) "stop" "play"))
+                          (dom/button
+                            #js {:onClick #(reset-random!)}
+                            "random"))
                  (apply dom/svg #js {:height (* height cell-size)
                                      :width (* width cell-size)
                                      :onClick (partial handle-world-click
@@ -115,18 +137,7 @@
            app-state
            {:target (. js/document (getElementById "app"))}))

-(defn random-cells
-  [[width height]]
-  (set (filter #(> (Math/random) 0.5)
-               (for [x (range 0 width)
-                     y (range 0 width)]
-                 (vector x y)))))

-(defonce app-state (atom {:cells (random-cells [50 20])
-                          :bounds [50 20]
-                          :playing? false
-                          :cell-size 20
-                          :speed 50}))
 (defn main []
   (draw! app-state)
   (live! app-state))


clean up ai code

clean up ai code

--- src/cljs/triboard/ai/ai.cljs
+++ src/cljs/triboard/ai/ai.cljs
@@ -3,7 +3,6 @@
     [cljs.spec :as s :include-macros true]
     [triboard.ai.scoring :as scoring]
     [triboard.logic.game :as game]
-    [triboard.logic.player :as player]
     [triboard.logic.scores :as scores]
     [triboard.logic.turn :as turn]
     ))
@@ -16,68 +15,10 @@
 (defn- make-ai
   [board player]
   {:player player
-   :other-players (remove #{player} player/all)
-   :cell-weights (scoring/get-weighting board)
+   :cell-weights (scoring/get-weighting board)              ;; TODO
    })

-(defn- score-move
-  "Compute the strength of a move, based on the converted cells"
-  [{:keys [player cell-weights]} transition]
-  (reduce                                                   ;; TODO - Factor in move
-    #(scores/update-scores-with %1 %2 cell-weights)
-    scores/null-scores
-    transition))
-
-;; -----------------------------------------
-;; Attempts game - tree (later minimax decoupled)
-;; -----------------------------------------
-
-(defn build-game-tree
-  [game depth]
-  (if (= 0 depth)
-    game
-    (let [transitions (turn/player-transitions (game/current-turn game))
-          next-games (map #(game/play-move game (first %)) transitions)]
-      (map vector
-        transitions
-        (map #(build-game-tree % (dec depth)) next-games)))
-    ))
-
-(defn test-build-game-tree
-  []
-  (let [init-game (game/new-game)]
-    (build-game-tree init-game 1)))
-
-;; -----------------------------------------
-;; Attempts minimax
-;; -----------------------------------------
-
-;; TODO - How to add the custom scoring? How to keep the game? (use keys)
-;; TODO - Use mapmin from http://worrydream.com/refs/Hughes-WhyFunctionalProgrammingMatters.pdf
-;; TODO - Sort by scores as well
-
-
-(defn contains-lower-value?
-  [coll pot]
-  (cond
-    (empty? coll) false
-    (<= (first coll) pot) true
-    :else (recur (rest coll) pot)
-    ))
-
-(defn map-min-impl
-  [max-min-val coll]
-  (cond
-    (empty? coll) max-min-val
-    (contains-lower-value? (first coll) max-min-val) max-min-val ;; Will depend on player
-    :else (recur
-            (max max-min-val (apply min (first coll)))      ;; Will depend on player
-            (rest coll))
-    ))
-
-(defn map-min
-  [coll]
-  (map-min-impl (min (first coll)) (rest coll)))
+(defn- max-by [key-fn coll] (apply max-key key-fn coll))

 ;; -----------------------------------------

@@ -110,45 +51,6 @@
     ))

 ;; -----------------------------------------
-
-(defn test-on-game
-  [g]
-  (let [turn (game/current-turn g)
-        ai (make-ai (:board turn) (:player turn))]
-    (tree-score ai (game/current-turn g) 2)))
-
-(defn test-score-tree [] (test-on-game (game/new-game)))
-
-(defn benchmark []
-  (time (dotimes [i 10]
-          (time (test-score-tree))
-          )))
-
-;; -----------------------------------------
-
-(defn- worst-possible-score-from
-  [{:keys [player other-players] :as ai} moves]
-  (transduce
-    (comp
-      (mapcat #(get moves %))
-      (map #(score-move ai (second %)))
-      (map #(get % player)))
-    min
-    other-players))
-
-(defn- move-best-outcome
-  [ai game [coord transition]]
-  (let [new-game (game/play-move game coord)
-        move-diff (get (score-move ai transition) (:player ai))
-        new-moves (:transitions (game/current-turn new-game))
-        next-diff (worst-possible-score-from ai new-moves)]
-    {:scoring (+ move-diff next-diff)
-     :game new-game}))
-
-(defn- max-by [key-fn coll] (apply max-key key-fn coll))
-
-
-;; -----------------------------------------
 ;; Public API
 ;; -----------------------------------------

@@ -171,16 +73,20 @@
           (turn/player-transitions turn)))
       )))

-#_(defn- play-best-move
-    "[SIMPLISTIC] Play the best move for a player based on:
-     * The immediate gain
-     * The worse immediate lost afterwards"
-    [game]
-    (let [turn (game/current-turn game)
-          ai (make-ai (:board turn) (:player turn))]
-      (:game
-        (max-by :scoring
-          (map
-            #(move-best-outcome ai game %)
-            (turn/player-transitions turn)))
-        )))
+
+;; -----------------------------------------
+;; TESTS
+;; -----------------------------------------
+
+(defn test-on-game
+  [g]
+  (let [turn (game/current-turn g)
+        ai (make-ai (:board turn) (:player turn))]
+    (tree-score ai (game/current-turn g) 2)))
+
+(defn test-score-tree [] (test-on-game (game/new-game)))
+
+(defn benchmark []
+  (time (dotimes [i 10]
+          (time (test-score-tree))
+          )))


move the minimax counter

move the minimax counter

--- src/cljs/triboard/ai/ai.cljs
+++ src/cljs/triboard/ai/ai.cljs
@@ -38,6 +38,7 @@
   [ai turn on-transition
    & {:keys [max-fn min-fn]
       :or {max-fn max, min-fn min}}]
+  (swap! eval-counter inc)
   (apply
     (if (maximizing? ai turn) max-fn min-fn)
     (map
@@ -56,7 +57,6 @@

 (defn- leaf-score
   [ai {:keys [scores] :as turn}]
-  (swap! eval-counter inc)
   (min-max-step ai turn
     (fn [_ transition]
       (eval-score ai (scores/update-scores scores transition))


Add data normalization with reducers

Add data normalization with reducers

--- src/cyanite_fetcher/core.clj
+++ src/cyanite_fetcher/core.clj
@@ -302,6 +302,26 @@
     (newline)
     ndata))

+(defn r-norm
+  "Normalization with reducers."
+  [data rollup to]
+  (println "Running normalization with reducers...")
+  (let [ndata
+        (time (doall (let [min-point  (:time (first data))
+                           max-point  (-> to (quot rollup) (* rollup))
+                           nil-points (->> (range min-point (inc max-point) rollup)
+                                           (r/map (fn [time] {time [{:time time}]}))
+                                           (r/reduce merge {}))
+                           by-path    (->> (group-by :path data)
+                                           (r/map (partial fill-in nil-points))
+                                           (r/reduce merge {}))]
+                       {:from min-point
+                        :to   max-point
+                        :step rollup
+                        :series by-path})))]
+    (newline)
+    ndata))
+
 ;;------------------------------------------------------------------------------
 ;; Benchmark
 ;;------------------------------------------------------------------------------
@@ -329,12 +349,14 @@
     (newline)
     (let [paths (es-get-paths eshost path tenant)
           data (c-get-data chost paths tenant rollup period from to)
-          reduce-fdata (flatter data (fn [data] (reduce into data)) "reduce")]
+          fdata (flatter data (fn [data] (r/reduce into [] data)) "warming r/reduce")]
       (flatter data (fn [data] (r/reduce into [] data)) "r/reduce")
-      (cleaner reduce-fdata (fn [data] (remove nil? data))  "remove")
-      (cleaner reduce-fdata (fn [data] (into [] (r/remove nil? data))) "r/remove")
+      (flatter data (fn [data] (reduce into data)) "reduce")
+      (cleaner fdata (fn [data] (into [] (r/remove nil? data))) "r/remove")
+      (cleaner fdata (fn [data] (remove nil? data))  "remove")
       (let [fcdata (r-flatter-cleaner data)]
-        (norm fcdata rollup to))))
+        (norm fcdata rollup to)
+        (r-norm fcdata rollup to))))
   (println "Finish time:" (tl/format-local-time (tl/local-now) :rfc822)))

 ;;------------------------------------------------------------------------------


Fix the 'remove-paths' function

Fix the 'remove-paths' function

--- src/cyanite_remover/core.clj
+++ src/cyanite_remover/core.clj
@@ -206,8 +206,9 @@
     (dry-mode-warn options)
     (process-paths tenant paths es-url options
                    (fn [pstore options tenant paths]
-                     (swap! stats-processed inc)
-                     (pstore/delete pstore tenant false false paths))
+                     (dorun (map #(do (swap! stats-processed inc)
+                                      (pstore/delete pstore tenant false false %))
+                                 paths)))
                    "Removing paths" true)
     (catch Exception e
       (clog/unhandled-error e))))


Add filter items wip

Add filter items wip

--- src/day8/re_frame/trace.cljs
+++ src/day8/re_frame/trace.cljs
@@ -132,20 +132,20 @@
                                nil)}])))

 (defn render-traces []
-  (let [filter-items     (r/atom "")
+  (let [filter-input     (r/atom "")
+        filter-items     (r/atom []) ;; [{:id (random-uuid) :query "showing" :filter-type "contains"} {:id (random-uuid) :query "Reagent" :filter-type "contains"}
         slower-than-ms   (r/atom "")
         slower-than-bold (r/atom "")]
     (fn []
       (let [slower-than-ms-int   (js/parseInt @slower-than-ms)
             slower-than-bold-int (js/parseInt @slower-than-bold)
-            op-filter            (when-not (str/blank? @filter-items)
-                                   (filter #(str/includes? (str/lower-case (str (:operation %) " " (:op-type %))) @filter-items)))
+            op-filter            (when-not (str/blank? @filter-input)
+                                   (filter #(str/includes? (str/lower-case (str (:operation %) " " (:op-type %))) @filter-input)))
             ms-filter            (when-not (str/blank? @slower-than-ms)
                                    (filter #(< slower-than-ms-int (:duration %))))
             transducers          (apply comp (remove nil? [ms-filter op-filter]))
             showing-traces       (sequence transducers @traces)
-
-            filter-msg           (if (and (str/blank? @filter-items) (str/blank? @slower-than-ms))
+            filter-msg           (if (and (str/blank? @filter-input) (str/blank? @slower-than-ms))
                                    (str "Filter " (count @traces) " events: ")
                                    (str "Filtering " (count showing-traces) " of " (count @traces) " events:"))
             padding              {:padding "0px 5px 0px 5px"}]
@@ -153,13 +153,26 @@
          {:style {:padding "10px"}}
          [:h1 "TRACES"]
          [:span filter-msg [:button {:on-click #(do (trace/reset-tracing!) (reset! traces []))} " Clear traces"]] [:br]
-         [:span "Filter events " [search-input {:on-save #(reset! filter-items (str/lower-case %))}]
+         [:span "Filter events " [search-input {:value @filter-input
+                                                :on-save (fn [query]
+                                                           (do
+                                                             (reset! filter-input "")
+                                                             (swap! filter-items conj {:id (random-uuid)
+                                                                                :query (str/lower-case query)
+                                                                                :filter-type "contains"})))}]
           [:button "+"]
           ;; [:button {:style {:background "#aae0ec"
           ;;                   :padding 7
           ;;                   :margin 5}}
           ;;  "-"]]
           [:br]]
+         [:div.filter-items
+          (for [item @filter-items]
+            ^{:key (:id item)}
+            [:span [:div.filter-item {:style {:paddingLeft 90}} (:query item)
+                    [:button {:on-click (fn [event] (swap! filter-items #(remove (comp (partial = (:query item)) :query) %)))}
+                     "-"]]])]
+
          [:table
           {:cell-spacing "0" :width "100%"}
           [:thead>tr


Move tables to common

Move tables to common

--- test/clojure/clojurewerkz/cassaforte/test_helper.clj
+++ test/clojure/clojurewerkz/cassaforte/test_helper.clj
@@ -43,6 +43,17 @@
                                          :user_count  :counter
                                          :primary-key [:name]}))

+      (create-table session :events
+                    (column-definitions {:message      :varchar
+                                         :created_at   :timeuuid
+                                         :primary-key  [:created_at]}))
+
+      (create-table session :events_for_in_and_range_query
+                    (column-definitions {:message      :varchar
+                                         :city         :varchar
+                                         :created_at   :timeuuid
+                                         :primary-key  [:message :created_at]}))
+
       (create-table session :events_by_device_id_and_date
                     (column-definitions {:date        :varchar
                                          :device_id   :varchar


Implemente get-bookmark api.

Implemente get-bookmark api.

--- src/clj/bookmarx/handler.clj
+++ src/clj/bookmarx/handler.clj
@@ -58,11 +58,29 @@
        :headers (if (= (:csrf-token params) "true")
                   (assoc headers "csrf-token" *anti-forgery-token*)
                   headers)
-       :body (str bookmarks)})
+       :body (pr-str bookmarks)})
+    (catch Exception e (errorf "Error %s" (.toString e)))))
+
+(defn get-bookmark "Get a bookmark in an HTTP response."
+  [id params & [status]]
+  (try
+    (infof "get-bookmark %s %s" id params)
+    (let [conn (d/connect (env :database-uri))
+          bookmark (d/q '[:find (pull ?e [:db/id :bookmark/id :bookmark/title :bookmark/url
+                                           :bookmark/rating :bookmark/icon :bookmark/icon-color
+                                          :bookmark/parent {:bookmark/_parent 1}])
+                          :in $ ?uuid
+                          :where [?e :bookmark/id ?uuid]] (d/db conn)
+                         (java.util.UUID/fromString (:id params)))
+          headers {"content-type" "application/edn"}]
+      {:status (or status 200)
+       :headers (if (= (:csrf-token params) "true")
+                  (assoc headers "csrf-token" *anti-forgery-token*)
+                  headers)
+       :body (pr-str (first bookmark))})
   (catch Exception e (errorf "Error %s" (.toString e)))))

-(defn post-bookmark
-  "Add a bookmark into the database for an HTTP request."
+(defn post-bookmark "Add a bookmark into the database for an HTTP request."
   [params & [status]]
   (try
     (infof "post-bookmark %s" params)
@@ -78,8 +96,7 @@
                       :bookmark/id id})})
   (catch Exception e (errorf "Error %s" (.toString e)))))

-(defn put-bookmark
-  "Upsert a bookmark in the database for an HTTP request."
+(defn put-bookmark "Upsert a bookmark in the database for an HTTP request."
   [id params & [status]]
   (try
     (infof "put-bookmark %s %s" id params)
@@ -88,8 +105,7 @@
       {:status (or status 200)})
   (catch Exception e (errorf "Error %s" (.toString e)))))

-(defn delete-bookmark
-  "Retract a bookmark in the database."
+(defn delete-bookmark "Retract a bookmark in the database."
   [id & [status]]
   (try
     (infof "delete-bookmark %s" id)
@@ -101,24 +117,23 @@
     (catch Exception e (errorf "Error %s" (.toString e)))))

 (defroutes routes
-           ;; Views
-           (GET "/" [] loading-page)
-           (GET "/add" [] loading-page)
-           (GET "/about" [] loading-page)
-           (GET "/cards" [] cards-page)
-           (GET "/select" [] loading-page)
-           (GET "/search" [] loading-page)
+  ;; Views
+  (GET "/" [] loading-page)
+  (GET "/add" [] loading-page)
+  (GET "/about" [] loading-page)
+  (GET "/cards" [] cards-page)
+  (GET "/select" [] loading-page)
+  (GET "/search" [] loading-page)

-           ;; API
-           (GET "/api/bookmarks" {params :params} [] (get-bookmarks params))
-           (POST "/api/bookmarks" {params :edn-params} (post-bookmark params))
-           (PUT "/api/bookmarks/:id" {id :id params :edn-params} [] (put-bookmark id params))
-           (DELETE "/api/bookmarks/:id" [id] (delete-bookmark id))
+  ;; API
+  (GET "/api/bookmarks" {params :params} [] (get-bookmarks params))
+  (GET "/api/bookmarks/:id" {id :id params :params} [] (get-bookmark id params))
+  (POST "/api/bookmarks" {params :edn-params} (post-bookmark params))
+  (PUT "/api/bookmarks/:id" {id :id params :edn-params} [] (put-bookmark id params))
+  (DELETE "/api/bookmarks/:id" [id] (delete-bookmark id))

-           (resources "/")
-           (not-found "Not Found"))
-
-;(def app (wrap-middleware #'routes))
+  (resources "/")
+  (not-found "Not Found"))

 (def app
   (-> #'routes


Fixed log messages

Fixed log messages

--- src/clj/bookmarx/handler.clj
+++ src/clj/bookmarx/handler.clj
@@ -45,7 +45,7 @@
 (defn get-bookmarks-since "Get bookmarks greater than a revision number in an HTTP request."
   [rev]
   (try
-    (infof "get-bookmarks-since %s" rev)
+    (t/infof "get-bookmarks-since %s" rev)
     (let [rev-num (when-not (empty? rev) (read-string rev))
           rev-num (if (integer? rev-num) rev-num 0)
           changed-bookmarks
@@ -240,7 +240,7 @@
 (defn delete-trash "Delete bookmarks from the trash in the database."
   []
   (try
-    (t/infof "delete-trash")
+    (t/info "delete-trash")
     (let [{:keys [:bookmark/parent-id]} (get @bookmarks trash-id)
           changed-ids [parent-id trash-id]
           deleted-ids (get-in @bookmarks [trash-id :bookmark/children])]
@@ -268,7 +268,7 @@
 (defn get-settings "Get all settings and return them in an HTTP response."
   []
   (try
-    (info "get-settings")
+    (t/info "get-settings")
     {:status 200
      :headers {"content-type" "application/edn"}
      :body (ds/get-settings)}


fix race condition relating to retrieving path from cache and aot compilation

--- src/clj/com/rpl/specter.cljc
+++ src/clj/com/rpl/specter.cljc
@@ -232,8 +232,13 @@
              get-cache-code (if (= platform :clj)
                               `(try (i/get-cell ~cache-sym)
                                     (catch ClassCastException e#
+                                      ;; With AOT compilation it's possible for:
+                                      ;; Thread 1: unbound, so throw exception
+                                      ;; Thread 2: unbound, so throw exception
+                                      ;; Thread 1: do alter-var-root
+                                      ;; Thread 2: it's bound, so retrieve the current value
                                       (if (bound? (var ~cache-sym))
-                                        (throw e#)
+                                        (i/get-cell ~cache-sym)
                                         (do
                                           (alter-var-root
                                            (var ~cache-sym)


Added vec2 constructor

Added vec2 constructor

--- src/cljs/cloj/math/vec2.cljs
+++ src/cljs/cloj/math/vec2.cljs
@@ -7,3 +7,4 @@
 (mk-vec-op div / :x :y)

 (defn v2 [x y] {:x x :y y})
+(defn vec2 [x y] {:x x :y y})


Auto-reconnect workers to missing master

--- src/engulf/worker_client.clj
+++ src/engulf/worker_client.clj
@@ -69,14 +69,19 @@
     (let [conn @(nc/client-connect host port)]
       (log/info "Connected to relay!")

-      (on-closed conn (fn [] (log/warn "Connection to master closed!")))
+      (on-closed conn (fn []
+                        (log/warn "Connection to master closed! Reconnecting in 5s")
+                        (Thread/sleep 5000)
+                        (client-connect host port)))
       (on-error conn (fn [e] (log/warn e "Server Channel Error!") ))
       (receive-all conn (partial handle-message conn))
       ;; Send identity immediately
       (enqueue conn {"name" "uuid" "body" uuid})
       conn)
     (catch java.net.ConnectException e
-      (log/warn e "Could not connect to control server!"))))
+      (log/warn e "Could not connect to control server! Reconnecting in 5s")
+      (Thread/sleep 5000)
+      (client-connect host port))))

 (defn start
   "Starts the worker client. Should be done once per process max."


Added happy number problem

Added happy number problem

--- src/foreclojure/data_set.clj
+++ src/foreclojure/data_set.clj
@@ -1001,4 +1001,16 @@

       ))

+(insert! :problems
+          {:_id 87
+           :title "Happy numbers"
+           :times-solved 0
+           :description "Happy numbers are positive integers that follow a particular formula: take each individual digit, square it, and then sum the squares to get a new number. Repeat with the new number and eventually, you might get to 1 whose squared sum is 1. This is a happy number. An unhappy number (or sad number) is one that loops endlessly. Write a function that determines if a number is happy or not. See http://en.wikipedia.org/wiki/Happy_number for more information."
+           :tags ["easy" "math" "recursion"]
+           :approved true
+           :tests ["(= (__ 7) true)"
+                   "(= (__ 986543210) true)"
+                   "(= (__ 2) false)"
+                   "(= (__ 3) false)"]})
+
 (load-problems)


Test case fixed

Test case fixed

--- src/foreclojure/data_set.clj
+++ src/foreclojure/data_set.clj
@@ -734,7 +734,7 @@
            :tags ["medium" "sorting"]
            :tests ["(= (__  \"Have a nice day.\")\n   [\"a\" \"day\" \"Have\" \"nice\"])"
                    "(= (__  \"Clojure is a fun language!\")\n   [\"a\" \"Clojure\" \"fun\" \"is\" \"language\"])"
-                   "(= (__  \"Fools fall for foolish follies.\")\n   [\"fall\" \"follies\" \"foolish\" \"fools\" \"for\"])"]})
+                   "(= (__  \"Fools fall for foolish follies.\")\n   [\"fall\" \"follies\" \"foolish\" \"Fools\" \"for\"])"]})

       (insert! :problems
            {:_id 71


Make run-code and mark-completed return maps instead of vectors, since the structure is getting complicated.

--- 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)]))
+    {:message (str message " " gist-link), :url (str "/problem/" _id)}))

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

@@ -158,7 +158,7 @@
   "Run the specified code-string against the test cases for the problem with the
 specified id.

-Return a vector of [message-to-display url-to-display-at num-tests-passed]."
+Return a map, {:message, :url, :num-tests-passed}."
   [id raw-code]
   (try
     (let [code (.trim raw-code)
@@ -177,16 +177,18 @@
                           "You failed the unit tests")
                         (catch Throwable t (.getMessage t)))))
           [passed [fail-msg]] (split-with nil? results)]
-      (conj (if fail-msg
-              [fail-msg *url*]
-              (mark-completed problem code))
-            (count passed)))
-    (catch Throwable t [(.getMessage t), *url*, 0])))
+      (assoc (if fail-msg
+               {:message fail-msg :url *url*}
+               (mark-completed problem code))
+        :num-tests-passed (count passed)))
+    (catch Throwable t {:message (.getMessage t), :url *url*
+                        :num-tests-passed 0})))

 (defn static-run-code [id raw-code]
-  (let [[message url failure-index] (binding [*url* (str *url* "#prob-desc")]
-                                      (run-code id raw-code))]
-    (session/flash-put! :failing-test failure-index)
+  (let [{:keys [message url num-tests-passed]}
+        (binding [*url* (str *url* "#prob-desc")]
+          (run-code id raw-code))]
+    (session/flash-put! :failing-test num-tests-passed)
     (flash-msg message url)))

 (defn render-test-cases [tests]
@@ -223,8 +225,8 @@
         [:span#graph-link "View Chart"]]])))

 (defn rest-run-code [id raw-code]
-  (let [[message url failure-index] (run-code id raw-code)]
-    (json-str {:failingTest failure-index
+  (let [{:keys [message url num-tests-passed]} (run-code id raw-code)]
+    (json-str {:failingTest num-tests-passed
                :message message
                :golfScore (html (render-golf-score))
                :golfChart (html (render-golf-chart))})))


Fix execute-content -> execute_input

Fix execute-content -> execute_input

--- src/ipython_clojure/core.clj
+++ src/ipython_clojure/core.clj
@@ -1,5 +1,5 @@
 (ns ipython-clojure.core
-  (:require
+  (:require
             [ipython-clojure.middleware.pprint]
             [ipython-clojure.middleware.stacktrace]
             [clojure.data.json :as json]
@@ -21,7 +21,7 @@
 ;;; Map of sockets used; useful for debug shutdown
 (defonce jup-sockets  (atom {}))

-(defn get-free-port!
+(defn get-free-port!
   "Get a free port. Problem?: might be taken before I use it."
   []
   (let [socket (ServerSocket. 0)
@@ -214,18 +214,18 @@
           parent-header (:header message)]
       (send-message iopub-socket "status" (status-content "busy")
                     parent-header {} session-id signer)
-      (send-message iopub-socket "execute-content"
+      (send-message iopub-socket "execute_input"
                     (pyin-content @execution-count message)
                     parent-header {} session-id signer))))

 (def nrepl-session (atom nil))

-(defn set-session!
+(defn set-session!
   "All interaction will occur in one session; this sets atom nrepl-session to it."
   []
   (reset! nrepl-session
           (with-open [conn (repl/connect :port (:port @the-nrepl))]
-            (-> (repl/client conn 10000)
+            (-> (repl/client conn 10000)
                 (repl/message {:op :clone})
                 doall
                 repl/combine-responses
@@ -252,18 +252,18 @@
           max-name (apply max (map count (map :name clean)))]
       (str (format "%s (%s)\n\n" (:message msg) (:class msg))
            (apply str
-                  (map #(format (str "%" max-file "s: %5d %-" max-name "s  \n")
-                                (:file %) (:line %) (:name %))
+                  (map #(format (str "%" max-file "s: %5d %-" max-name "s  \n")
+                                (:file %) (:line %) (:name %))

                        clean))))))

 (defn nrepl-eval
   "Send message to nrepl and process response."
-  [code transport]
-  (let [result (-> (repl/client transport 3000) ; timeout=3sec.
+  [code transport]
+  (let [result (-> (repl/client transport 3000) ; timeout=3sec.
                    (repl/message {:op :eval :session @nrepl-session :code code})
                    repl/combine-responses)]
-    (cond (empty? result) "Clojure: Unbalanced parentheses or kernel timed-out while processing form.",
+    (cond (empty? result) "Clojure: Unbalanced parentheses or kernel timed-out while processing form.",
           (seq (:ex result)) (stacktrace-string (request-trace transport))
           :else (if-let [vals (:value result)]
                   (apply str (interpose " " vals)) ; could have sent multiple forms
@@ -277,8 +277,8 @@
             parent-header (:header message)]
         (swap! execution-count inc)
         (busy-handler message signer execution-count)
-        (let [s# (new java.io.StringWriter)
-              [output result]
+        (let [s# (new java.io.StringWriter)
+              [output result]
               (binding [*out* s#]
                 (let [result (nrepl-eval (get-in message [:content :code]) transport)
                       output (str s#)]
@@ -354,13 +354,13 @@
   "Clojupyters nREPL handler."
   (apply nrepl-server/default-handler (map resolve clojupyter-middleware)))

-(defn start-nrepl
+(defn start-nrepl
   "Start an nrepl server. Stop the existing one, if any (only possible when debugging)."
   []
   (when-let [server @the-nrepl]
     (nrepl-server/stop-server server))
   (reset! the-nrepl
-          (nrepl-server/start-server
+          (nrepl-server/start-server
            :port (get-free-port!)
            :handler clojupyer-nrepl-handler))
   (set-session!))


Make core more robust

Make core more robust

--- src/dungeon_crusade/core.clj
+++ src/dungeon_crusade/core.clj
@@ -43,6 +43,6 @@
             ; setup function changed? stop ticking
             (when (= (:souce (meta (var-get (get-setup-fn)))) (:source (meta setup-fn-var)))
               ; tick the old state through the tick-fn to get the new state
-              (recur ((get-tick-fn) state)))))
+              (recur (try ((get-tick-fn) state) (catch Exception e state))))))
           ; setup function changed, start outer loop over again
         (recur (get-setup-fn))))))


Revised layout of app state. Support for rendering.

--- src/fm/simrunner/gui/app.clj
+++ src/fm/simrunner/gui/app.clj
@@ -29,12 +29,18 @@
 (defn- app [config view]
   {:config config
    :worker (agent nil)
-   :state  (atom {:ui {:view      view
-                       :updating? false}})})
+   :state  (atom {:ui    {:view       view
+                          :model      {}
+                          :dirty?     false
+                          :rendering? false}
+                  :model {}})})
+
+(defn- rendering? [app]
+  (-> app :state deref :ui :rendering?))

 (defn- event-handler [app]
   (fn [& args]
-    (when-not (-> app :state deref :ui :updating?)
+    (when-not (rendering? app)
       (apply on-event app args))))

 (defn start [config]
@@ -47,3 +53,22 @@
       (.setTitle frame "SimRunner (c) 2014 DEINC")
       (.show frame))))

+(defn- start-rendering! [app-state]
+  (when (-> @app-state :ui :dirty?)
+    (swap! app-state #(assoc-in % [:ui :rendering?] true))))
+
+(defn- stop-rendering! [app-state]
+  (when (-> @app-state :ui :rendering?)
+    (swap! app-state #(-> %
+                          (assoc-in [:ui :rendering?] false)
+                          (assoc-in [:ui :dirty?] false)))))
+
+(defn render [{:keys [state] :as app}]
+  (gui/gui-do
+    (when (start-rendering! state)
+      (try
+        ;; TODO: render the view model!
+        (io! "Do not update the ui in a transaction!")
+        (finally
+          (stop-rendering! state))))))
+


update executor

update executor

--- src/graphql_clj/executor.clj
+++ src/graphql_clj/executor.clj
@@ -234,10 +234,10 @@
                                parser/parse-schema
                                sv/validate-schema))

-(def test-validated-document (-> test-query-1
-                                  parser/parse-query-document
-                                  ((fn [s]
-                                     [nil s]))))
+(defn validate-document [query-str]
+  (->> query-str
+       parser/parse-query-document
+       (qv/validate-query (second test-validated-schema))))

 (defn test-resolver-fn [type-name field-name]
   (let [f (get-in {"QueryRoot" {"dog" (fn [& args]
@@ -247,7 +247,7 @@
       (println (f)))
     f))

-;; (execute nil test-validated-schema test-resolver-fn test-validated-document nil)
+;; (execute nil test-validated-schema test-resolver-fn (validate-document test-query-1) nil)

 (def test-intro-str
   "


CMR-1589: Changed the size of the user id column to 30 for small provider collections table

--- metadata-db-app/src/migrations/018_add_user_id_collection_tables.clj
+++ metadata-db-app/src/migrations/018_add_user_id_collection_tables.clj
@@ -7,7 +7,7 @@
   "Migrates the database up to version 18."
   []
   (println "migrations.018-add-user-id-collection-tables up...")
-  (h/sql "alter table small_prov_collections add user_id VARCHAR(50)")
+  (h/sql "alter table small_prov_collections add user_id VARCHAR(30)")
   (doseq [t (h/get-collection-tablenames)]
     (h/sql (format "alter table %s add user_id VARCHAR(30)" t))))


Fix a misplaced docstring

Fix a misplaced docstring

--- src/caesium/crypto/shorthash.clj
+++ src/caesium/crypto/shorthash.clj
@@ -19,9 +19,10 @@
   [out in inlen k]
   (b/call! shorthash out in inlen k))

-(defn shorthash [in k]
+(defn shorthash
   "Computes a fixed-size fingerprint for the message `in`,
   using the key `k`."
+  [in k]
   (let [out (bb/alloc bytes)]
     (shorthash-to-buf!
      out


hello, linus ach fixed

hello, linus ach fixed

--- src-clj/acha/achievement.clj
+++ src-clj/acha/achievement.clj
@@ -70,9 +70,9 @@
   [:hello-linus
   (fn [commit-info]
     (when-let [bad-acha ((second bad-motherfucker) commit-info)]
-    (when (>= (:level bad-acha) 10))
-    {:username (:author commit-info)
-          :time (:time commit-info)}))])
+      (when (>= (:level bad-acha) 10)
+        {:username (:author commit-info)
+         :time     (:time commit-info)})))])

 (def borat
   (make-word-counting-scanner [:borat spellings/table]))


disable the developer console since it's currently not needed

--- src-cljs/bitfondue/core.cljs
+++ src-cljs/bitfondue/core.cljs
@@ -2,10 +2,6 @@
     (:require
      [reagent.core :as reagent :refer [atom]]
      [ajax.core :refer [GET]]))
-
-(enable-console-print!)
-
-(println "Edits to this text should show up in your developer console.")

 ;; define your app data so that it doesn't get over-written on reload


Changed graph display to a component for consistency

--- src-cljs/tropology/core.cljs
+++ src-cljs/tropology/core.cljs
@@ -186,6 +186,16 @@
     ))

+
+(defn graph-display [form-data class]
+  [:div {:class class}
+   [bind-fields trope-code-form form-data]
+   [:div
+    [:input {:type     "button"
+             :value    "Graph!"
+             :on-click #(graph/redraw-graph (:trope-code @form-data))}]
+    [:div {:id "graph-container"}]]]
+  )

 (defn article-display [form-data class]
   (let [current-article (re-frame/subscribe [:article-data :current-article])
@@ -237,13 +247,7 @@
         ]
     (fn []
       [:div
-       [:div {:class (when (not= @ui-state :home) "hidden")}
-        [bind-fields trope-code-form form-data]
-        [:div
-         [:input {:type     "button"
-                  :value    "Graph!"
-                  :on-click #(graph/redraw-graph (:trope-code @form-data))}]
-         [:div {:id "graph-container"}]]]
+       [graph-display form-data (when (not= @ui-state :home) "hidden")]
        [article-display form-data (when (not= @ui-state :tropes) "hidden")]
        [about-page (when (not= @ui-state :about) "hidden")]]
       )))


delete list links

delete list links

--- src/checkmate/views/overview.clj
+++ src/checkmate/views/overview.clj
@@ -10,7 +10,11 @@
        [:div
         [:h4 letter]
         (for [i items]
-          [:div (elm/link-to (str "/show/" (:_id i)) (:name i))])])]))
+          [:div.row
+           [:div.col-md-4
+            [:strong (elm/link-to (str "/show/" (:_id i)) (:name i))]]
+           [:div.col-md-8
+            [:small (elm/link-to "#" "Delete")]]])])]))

 (defn render [lists]
   (let [grouped (group-by (comp first string/upper-case :name) lists)]


s/msg/getMessage/

s/msg/getMessage/

--- src/clj/shale/node_providers.clj
+++ src/clj/shale/node_providers.clj
@@ -130,7 +130,7 @@
   (let [api-url (try
                   (str (url api-url))
                   (catch MalformedURLException e
-                    (if (.contains (.msg e) "no protocol")
+                    (if (.contains (.getMessage e) "no protocol")
                       (str (url (str "https://" api-url))))))
         options (assoc options :api-url api-url)]
     (map->KubeNodeProvider options)))


prepare items for return on preparing budget

--- src/clj_money/models/budgets.clj
+++ src/clj_money/models/budgets.clj
@@ -38,11 +38,20 @@
    :account-id schema/Int
    :periods [BudgetItemPeriod]})

+(defn- prepare-item-for-return
+  [item]
+  (update-in item [:periods] read-string))
+
+(defn- select-items-by-budget-id
+  [storage budget-id]
+  (map prepare-item-for-return
+       (select-budget-items-by-budget-id storage budget-id)))
+
 (defn- prepare-for-return
   [storage budget]
   (-> budget
       (update-in [:start-date] tc/to-local-date)
-      (assoc :items (select-budget-items-by-budget-id storage (:id budget)))))
+      (assoc :items (select-items-by-budget-id storage (:id budget)))))

 (defn select-by-entity-id
   "Returns the budgets for the specified entity"
@@ -78,15 +87,6 @@
   (-> budget
       before-validation
       (validation/validate-model (validation-rules schema))))
-
-(defn- prepare-item-for-return
-  [item]
-  (update-in item [:periods] read-string))
-
-(defn- select-items-by-budget-id
-  [storage budget-id]
-  (map prepare-item-for-return
-       (select-budget-items-by-budget-id storage budget-id)))

 (defn create
   "Creates a new budget"


Slight refactoring of components

Slight refactoring of components

--- src/cljs/db_quiz/components.cljs
+++ src/cljs/db_quiz/components.cljs
@@ -93,20 +93,65 @@
 ; ----- Common components -----

 (defn menu
+  "Fixed information & navigazion menu"
   []
   [:div#info-menu.btn-group {:role "group"}
-   [:a.btn.btn-default {:href "#"}
-    [:span.glyphicon.glyphicon-home.glyphicon-start]
-    (t :labels/home)]
-   [:button.btn.btn-default {:on-click #(reagent-modals/modal! (modals/game-info)
-                                                               {:size :lg})}
-    [:span.glyphicon.glyphicon-info-sign.glyphicon-start]
-    (t :labels/about)]])
+   [:a.btn.btn-default {:href "#"} [:span.glyphicon.glyphicon-home.glyphicon-start] (t :labels/home)]
+   [:button.btn.btn-default {:on-click #(reagent-modals/modal! (modals/game-info) {:size :lg})}
+    [:span.glyphicon.glyphicon-info-sign.glyphicon-start] (t :labels/about)]])

 (defn label-element
   "Label with text for input identified with for-id"
   [for-id text]
   [:label.col-sm-4.control-label {:for for-id} text])
+
+(defn single-select
+  "Single-select button group. Associates selected value into given id path in app-state.
+  The group is labelled with label-key's value from the translation map.
+  Values of the available buttons are given in options as a collection of [value label] pairs.
+  Label can be either a string or a keyword that will be looked up in the translation map."
+  [id label-key options]
+  (let [id-str (string/join "." (map name id))
+        click (fn [e] (swap! app-state #(assoc-in % id (keyword (.. e -target -dataset -key)))))
+        btn-class (partial join-by-space "btn" "btn-default")
+        button (fn [current-id [id label]]
+                 [:button {:class (btn-class (when (= id current-id) "active"))
+                           :data-key id
+                           :key id}
+                  (if (keyword? label) (t label) label)])]
+    (fn []
+      (let [current (get-in @app-state id)]
+        [:div.form-group
+         [label-element id-str (t label-key)]
+         [:div.btn-group.col-sm-8 {:id id-str
+                                   :on-click click
+                                   :role "group"}
+          (doall (for [option options]
+                   (button current option)))]]))))
+
+(defn multi-select
+  "Multi-select button group.Associates selected values into given id path in app-state.
+  The group is labelled with label-key's value from the translation map.
+  Values of the available buttons are given in options as a collection of [value label] pairs.
+  Label can be either a string or a keyword that will be looked up in the translation map."
+  [id label-key options]
+  (let [id-str (string/join "." (map name id))
+        click (fn [current-id update-fn]
+                (swap! app-state (fn [state] (update-in state id #(update-fn % current-id)))))
+        btn-class (fn [active?] (join-by-space "btn" "btn-default" (when active? "active")))]
+    (fn []
+      (let [current-value (get-in @app-state id)]
+        [:div.form-group
+         [label-element id-str (t label-key)]
+         [:div.col-sm-8.btn-group-vertical {:id id-str
+                                            :role "group"}
+          (doall (for [[current-id label] options
+                       :let [active? (current-value current-id)
+                             update-fn (if active? disj conj)]]
+                   [:button {:class (btn-class active?)
+                             :key label
+                             :on-click (partial click current-id update-fn)}
+                    (t label)]))]]))))

 ; ----- Home page -----

@@ -163,25 +208,10 @@

 (defn field-labelling
   []
-  (let [id [:options :labels]
-        options [[:numeric "0-9"]
-                 [:alphabetic "A-Z"]]
-        click-fn (fn [e]
-                   (swap! app-state
-                          #(assoc-in % id (keyword (.. e -target -dataset -key)))))
-        btn-class-fn (partial join-by-space "btn" "btn-default")
-        button-fn (fn [current-id [id label]]
-                    [:button {:class (btn-class-fn (when (= id current-id) "active"))
-                              :data-key id
-                              :key id}
-                     label])]
-    (fn []
-      (let [current (get-in @app-state id)]
-        [:div.form-group {:on-click click-fn}
-         [:label.col-sm-4.control-label (t :home/field-labelling)]
-         [:div.btn-group.col-sm-8 {:role "group"}
-          (doall (for [option options]
-                   (button-fn current option)))]]))))
+  (single-select [:options :labels]
+                 :home/field-labelling
+                 [[:numeric "0-9"]
+                  [:alphabetic "A-Z"]]))

 (defn language-picker
   []
@@ -204,53 +234,26 @@

 (defn difficulty-picker
   []
-  (let [id [:options :difficulty]
-        click-fn (fn [e]
-                   (swap! app-state
-                          #(assoc-in % id (keyword (.. e -target -dataset -key)))))
-        btn-class-fn (partial join-by-space "btn" "btn-default")
-        options [[:easy :home.difficulty/easy]
-                 [:normal :home.difficulty/normal]
-                 [:hard :home.difficulty/hard]]
-        button-fn (fn [current-id [id translate-id]]
-                    [:button {:class (btn-class-fn (when (= id current-id) "active"))
-                              :data-key id
-                              :key id}
-                     (t translate-id)])]
-    (fn []
-      (let [difficulty (get-in @app-state id)]
-        [:div.form-group {:on-click click-fn}
-         [:label.col-sm-4.control-label (t :home.difficulty/label)]
-         [:div.btn-group.col-sm-8 {:role "group"}
-          (doall (for [option options]
-                   (button-fn difficulty option)))]]))))
+  (single-select [:options :difficulty]
+                 :home.difficulty/label
+                 [[:easy :home.difficulty/easy]
+                  [:normal :home.difficulty/normal]
+                  [:hard :home.difficulty/hard]]))

 (defn selector-picker
   []
-  (let [active-selectors (get-in @app-state [:options :selectors])
-        selectors [[:persons (t :home.domains/persons)]
-                   [:places (t :home.domains/places)]
-                   [:works (t :home.domains/works)]
-                   [:born-in-brno (t :home.domains/born-in-brno)]
-                   [:ksc-members (t :home.domains/ksc-members)]
-                   [:uncertain-death (t :home.domains/uncertain-death)]
-                   [:artists (t :home.domains/artists)]
-                   [:politicians (t :home.domains/politicians)]
-                   [:musicians (t :home.domains/musicians)]
-                   [:films (t :home.domains/films)]]]
-        [:div.form-group
-         [label-element "options.selectors" (t :home.domains/label)]
-         [:div.col-sm-8.btn-group-vertical {:role "group"}
-          (for [[id label] selectors
-                :let [active? (active-selectors id)
-                      update-fn (if active? disj conj)]]
-            [:button {:class (join-by-space "btn" "btn-default" (when active? "active"))
-                      :key label
-                      :on-click (fn [_] (swap! app-state
-                                               (fn [state] (update-in state
-                                                                      [:options :selectors]
-                                                                      #(update-fn % id)))))}
-             label])]]))
+  (multi-select [:options :selectors]
+                :home.domains/label
+                [[:persons :home.domains/persons]
+                 [:places :home.domains/places]
+                 [:works :home.domains/works]
+                 [:born-in-brno :home.domains/born-in-brno]
+                 [:ksc-members :home.domains/ksc-members]
+                 [:uncertain-death :home.domains/uncertain-death]
+                 [:artists :home.domains/artists]
+                 [:politicians :home.domains/politicians]
+                 [:musicians :home.domains/musicians]
+                 [:films :home.domains/films]]))

 (defn google-spreadsheet-options
   []
@@ -421,7 +424,8 @@
   []
   (let [{:keys [board current-field]} @app-state]
     (if (empty? board)
-      (redirect "#") ; If no data is loaded, redirect to home page.
+      (do (redirect "#") ; If no data is loaded, redirect to home page.
+          [:div]) ; Return empty div as a valid Reagent component.
       [:div.container-fluid
        [menu]
        [:div.row


Adding sorting for tokens

Adding sorting for tokens

--- src/com/okl/tokenmgr/handler.clj
+++ src/com/okl/tokenmgr/handler.clj
@@ -42,10 +42,18 @@
     (get-apps ""))
   (GET "/api/applications/:app" [app]
     (get-apps app))
-  (GET "/api/tokens/:app" [app]
-    (denormalize-tokens (get-tokens (url-decode app))))
-  (GET "/api/tokens/" []
-    (denormalize-tokens (get-tokens "")))
+  (GET "/api/tokens/:app" [app sort-col sort-dir]
+    (let [tokens (denormalize-tokens (get-tokens (url-decode app)))
+          sort-dir (or sort-dir "asc")
+          sort-col (or sort-col "name")
+          sorted-data (sort-by #(get % (keyword sort-col)) tokens)]
+      (if (= "asc" sort-dir)
+        sorted-data
+        (reverse sorted-data))))
+  (GET "/api/tokens/" [sort-dir sort-col]
+    (let [tokens (denormalize-tokens (get-tokens ""))]
+      (println "Sorting by " sort-col)
+      (sort-by (symbol sort-col) tokens)))
   (DELETE "/api/applications/:delimited-app" [delimited-app]
     (try
       (let [app (str/replace delimited-app (delimiter) "/")]


Simplify views

Simplify views

--- src/discuss/references/main.cljs
+++ src/discuss/references/main.cljs
@@ -108,17 +108,34 @@
   (reify om/IRender
     (render [_]
       (let [issue (:issue data)
+            reference (:reference data)
             statement (:statement data)
             author (:author data)]
-        (dom/div nil
-                 (dom/div #js {:className "bs-callout bs-callout-info"}
-                          (dom/div #js {:className "pull-right"}
-                                   (bs/button-default-sm #(save-statement-change-view data) (vlib/fa-icon "fa-check") " Auswählen"))
-                          (dom/a #js {:href    "javascript:void(0)"
-                                      :onClick #(save-statement-change-view data)}
-                                 (dom/strong nil (:text statement)))
-                          (dom/div nil "Issue: " (:title issue))
-                          (dom/div nil "Autor: " (:nickname author))))))))
+        (bs/callout-info
+          (dom/strong nil (:text statement))
+          (dom/div nil
+                   "Reference:"
+                   (dom/br nil)
+                   (dom/i nil "\"" (:title reference) "\""))
+          (dom/div nil "Issue: " (:title issue))
+          (dom/div nil "Autor: " (:nickname author)))))))
+
+(defn usage-list-view
+  "List single usages of reference."
+  [data _owner]
+  (reify om/IRender
+    (render [_]
+      (let [issue (:issue data)
+            statement (:statement data)
+            author (:author data)]
+        (bs/callout-info
+          (dom/div #js {:className "pull-right"}
+                   (bs/button-default-sm #(save-statement-change-view data) (vlib/fa-icon "fa-check") " Auswählen"))
+          (dom/a #js {:href    "javascript:void(0)"
+                      :onClick #(save-statement-change-view data)}
+                 (dom/strong nil (:text statement)))
+          (dom/div nil "Issue: " (:title issue))
+          (dom/div nil "Autor: " (:nickname author)))))))

 (defn usages-view
   "List with details showing the usages of the given reference."
@@ -129,9 +146,8 @@
         (dom/div nil
                  (dom/h5 nil "Wo wird diese Referenz verwendet?")
                  (rlib/current-reference-component)
-                 (dom/div nil
-                          (apply dom/div nil
-                                 (map #(om/build usage-view (lib/merge-react-key %)) usages))))))))
+                 (apply dom/div nil
+                        (map #(om/build usage-list-view (lib/merge-react-key %)) usages)))))))

 (defn agree-disagree-view
   "Agree or disagree with the selected reference."


as with Italian, support _count_ and _no_older_than_ params to (defn todos)

--- src/babel/espanol/writer.clj
+++ src/babel/espanol/writer.clj
@@ -40,8 +40,10 @@
     (zipmap (map first verbs)
             (map second verbs))))

-(defn todos [ & [count lexeme]]
-  (let [count (if count (Integer. count) 10)
+(defn todos [ & [count lexeme no-older-than]]
+  (let [count (cond (nil? count) 10
+                    (= "all" count) 10
+                    true (Integer. count))
         model (-> ((-> models :es)) deref)
         type-of-model (type model)
         lexicon (:lexicon model)
@@ -74,5 +76,6 @@
                 (vals babel.espanol.grammar/tenses)
                 [{:gender :masc} {:gender :fem}]
                 [:1st :2nd :3rd]
-                [:sing :plur]))))))))
-
+                [:sing :plur]
+                count
+                no-older-than))))))))


Changed one key in error response: job-name -> jobName

--- src/emender_jenkins/rest_api.clj
+++ src/emender_jenkins/rest_api.clj
@@ -7,7 +7,7 @@
 ;  http://www.eclipse.org/legal/epl-v10.html
 ;
 ;  Contributors:
-;      Pavel Tisnovsky
+;      Pavel Tisnovsky
 ;

 (ns emender-jenkins.rest-api
@@ -139,7 +139,7 @@
 (defn create-error-response
     [job-name command message]
     {:status "error"
-     :job-name job-name
+     :jobName job-name
      :command command
      :message message})


Adding foods to swarm.

Adding foods to swarm.

--- src/brevis/example/swarm.clj
+++ src/brevis/example/swarm.clj
@@ -17,6 +17,7 @@
 (def num-initial-birds 25)
 (def minimum-num-birds num-initial-birds)
 (def num-initial-foods 20)
+(def minimum-num-foods num-initial-foods)

 ;; Energies
 (def child-bird-energy-cost 0.15)
@@ -88,7 +89,7 @@

 (defn make-bird
   "Make a new bird with the specified program. At the specified location."
-  [friendliness position]
+  [genome position]
   (-> {}
       (make-real)
       (make-box)
@@ -96,14 +97,30 @@
              :color [1 0 0]
              :energy child-bird-energy-cost
              :position position
-             :friendliness friendliness)
+             :genome genome)
       (make-collision-shape)))

+(defn random-bird-genome
+  "Returns a random bird genome. Genome is [ friend_weight food_weight ]"
+  []
+  [ (- (* 2 (lrand)) 1) (lrand) ])
+
+(defn mutate-bird-genome
+  "Returns a mutant bird genome. "
+  [genome]
+  (let [g1 (+ (first genome) (* 0.02 (lrand)) -0.01)
+        g2 (+ (second genome) (* 0.02 (lrand)) -0.01)]
+	  [(cond (> g1 1) 1
+	         (< g1 -1) -1
+	         :else g1)
+	   (cond (> g2 1) 1
+	         (< g2 0) 0
+	         :else g2)]))
+
 (defn random-bird
   "Make a new random bird."
   []
-  (let [friendliness (lrand)]
-    (make-bird friendliness (random-bird-position))))
+  (make-bird (random-bird-genome) (random-bird-position)))

 (defn bound-acceleration
   "Keeps the acceleration within a reasonable range."
@@ -115,10 +132,14 @@
 (defn eval-bird
   "Evaluate a bird to decide what to do."
   [bird nbrs]
-  (let [dir-to-nbr (sub (:position (first nbrs)) (:position bird))]
+  (let [nbr-bird (some #(when (bird? %) %) nbrs)
+        nbr-food (some #(when (food? %) %) nbrs)
+        dir-to-bird (sub (:position nbr-bird) (:position bird))
+        dir-to-food (sub (:position nbr-food) (:position bird))]
     (assoc bird
            :acceleration (add (:acceleration bird)
-                              (mul dir-to-nbr (:friendliness bird))))))
+                              (mul dir-to-bird (first (:genome bird)))
+                              (mul dir-to-food (second (:genome bird)))))))

 (defn fly
   "Change the acceleration of a bird."
@@ -144,7 +165,7 @@
                :energy (- (:energy bird) bird-cost-of-living))]
     (when (pos? (:energy bird))
       (if (> (:energy bird) child-bird-energy-cost)
-        (list (make-bird (:friendliness bird) (offset-position (:position bird) 2))
+        (list (make-bird (mutate-bird-genome (:genome bird)) (offset-position (:position bird) 2))
               (assoc bird
                 :energy (- (:energy bird) child-bird-energy-cost child-birth-energy-loss)))
         bird))))
@@ -209,7 +230,6 @@
         (assoc state
                :last-report-time (:simulation-time state)))
     state))
-

 (defn update
   "Update the world."
@@ -217,12 +237,16 @@
   (let [state (report state)
         objects (handle-collisions (:objects state) collision-handlers)
         updated-objects (doall (filter inside-boundary? (update-objects objects (:iteration-step-size state))))
+        num-foods-to-add (- minimum-num-foods
+                            (count (filter food? updated-objects)))
         num-birds-to-add (- minimum-num-birds
                             (count (filter bird? updated-objects)))]
     (assoc state
       :simulation-time (+ (:simulation-time state) (:iteration-step-size state))
       :objects (concat updated-objects
                        (when (pos? num-birds-to-add)
-                         (repeatedly num-birds-to-add random-bird))))))
+                         (repeatedly num-birds-to-add random-bird))
+                       (when (pos? num-foods-to-add)
+                         (repeatedly num-foods-to-add random-food))))))

 (start-gui 0.01 update)


Null guards and better filtering.

Null guards and better filtering.

--- src/kixi/hecuba/api/entities.clj
+++ src/kixi/hecuba/api/entities.clj
@@ -95,17 +95,22 @@
   {:term {k v}})

 (defn search-filter [must should must-not]
-  (let [shoulds (conj (or should []) must)]
+  (let [shoulds (if must (conj (or should []) must) should)]
     {:bool {:must (or must {})
             :should shoulds
             :must_not (or must-not {})}}))

 (defn filter-entities
-  ([params store]
-     (let [query-string   (or (:q params) "*")
-           page-number    (or (:page params) 0)
-           page-size      (or (:size params) 20)]
-       (search/search-entities query-string page-number page-size (:search-session store))))
+  ([params roles store]
+     (let [query-string    (or (:q params) "*")
+           page-number     (or (:page params) 0)
+           page-size       (or (:size params) 20)
+           results         (search/search-entities query-string page-number page-size (:search-session store))
+           total_hits      (esr/total-hits results)
+           parsed-results (parse-entities results nil nil roles)]
+       {:entities {:total_hits total_hits
+                   :page       page-number
+                   :entities   parsed-results}}))
   ([params allowed-programmes allowed-projects roles store]
      (let [query-string   (or (:q params) "*")
            page-number    (or (:page params) 0)
@@ -142,7 +147,7 @@
           (has-user? roles)
           request-method]

-         [true _ _ _ :get] [true (filter-entities params store)]
+         [true _ _ _ :get] [true (filter-entities params roles store)]
          [_ _ _ _ :get] [true (filter-entities params programmes projects roles store)]
          :else false))


less colours and nicer style

less colours and nicer style

--- src/clj/just_married/css.clj
+++ src/clj/just_married/css.clj
@@ -93,12 +93,11 @@
 (def main-page
   [[:.container (:desktop grid-config)]

-   [:h3 {:color (:gold COLOR-PALLETTE)
-         :background-color (:dark-red COLOR-PALLETTE)}]
-
-   [:.countdown {:grid-column "span 2"
+   [:h3 {:color (:dark-red COLOR-PALLETTE)}]
+
+   [:.countdown {:grid-column 1
                  :grid-row 1
-                 :color (:marsala COLOR-PALLETTE)
+                 ;; :color (:marsala COLOR-PALLETTE)
                  :font-weight "bold"
                  ;; might be nice to shrink this in theory??
                  ;; :width "50%"
@@ -144,17 +143,15 @@
    [:app {:background-color (:marsala COLOR-PALLETTE)}]
    ;; maybe the image containing the rest should actually be an element
    ;; by itself?
-   [:.countdown__internal {;;:background (:quote-background COLOR-PALLETTE)
-                           ;;:background-repeat "no-repeat"
-                           :text-align "center"}]
+   [:.countdown__internal {:text-align "center"}]

    ;; countdown settings
    [:.timer {;:background-color (:marsala COLOR-PALLETTE)
              :border-width "1px"
              :border-style "solid"
-             :border-color (:dark-red COLOR-PALLETTE)
-             :font-weight "bolder"
-             :color (:deep-blue COLOR-PALLETTE)}]
+             :font-size "2em"
+             :font-family (:alex-brush FONT-FAMILIES)
+             :border-color (:dark-red COLOR-PALLETTE)}]

    ;; find us settings
    [:#map {:width map-width
@@ -202,7 +199,7 @@
    [:.language__detector__english {:grid-column "1"
                                    :grid-row "3"
                                    :padding-left "150px"}]
-
+
    [:.monogram {:width "400px"}]
    [:.language__detector__italian {:grid-column "2"
                                    :grid-row "3"


Fix page/edit get ajax call

Fix page/edit get ajax call

--- src/clj/salava/page/main.clj
+++ src/clj/salava/page/main.clj
@@ -115,7 +115,7 @@
           blocks (page-blocks-for-edit ctx page-id)
           owner (:user_id page)
           badges (map #(select-keys % [:id :name :image_file :tags]) (b/user-badges-all ctx owner))
-          files (map #(select-keys % [:id :name :path :mime_type :size]) (f/user-files-all ctx owner))
+          files (map #(select-keys % [:id :name :path :mime_type :size]) (:files (f/user-files-all ctx owner)))
           tags (distinct (flatten (map :tags badges)))]
       {:page (assoc page :blocks blocks) :badges badges :tags tags :files files})))

@@ -179,7 +179,7 @@
     (let [{:keys [name description blocks]} page-content
           page-owner-id (page-owner ctx page-id)
           user-files (if (some #(= "file" (:type %)) blocks)
-                       (f/user-files-all ctx page-owner-id))
+                       (:files (f/user-files-all ctx page-owner-id)))
           file-ids (map :id user-files)
           user-badges (if (some #(= "badge" (:type %)) blocks)
                         (b/user-badges-all ctx page-owner-id))


apply authorization rules to web/prices

apply authorization rules to web/prices

--- src/clj_money/web/prices.clj
+++ src/clj_money/web/prices.clj
@@ -54,10 +54,12 @@
          "Back"]]])))

 (defn new-price
-  ([{params :params :as req}]
-   (new-price req {:commodity-id (Integer. (:commodity-id params))}))
-  ([{params :params} price]
-   (let [commodity (commodities/find-by-id (env :db) (Integer. (:commodity-id params)))]
+  ([{{commodity-id :commodity-id} :params :as req}]
+   (new-price req (-> {:commodity-id commodity-id}
+                      (tag-resource :price)
+                      (authorize :new))))
+  ([{{commodity-id :commodity-id} :params} price]
+   (let [commodity (commodities/find-by-id (env :db) commodity-id)]
      (with-layout (format "New price for %s" (:symbol commodity)) {}
        [:div.row
         [:div.col-md-6
@@ -73,17 +75,21 @@

 (defn create
   [{params :params}]
-  (let [result (prices/create (env :db)
-                              (select-keys params [:commodity-id
-                                                   :trade-date
-                                                   :price]))]
+  (let [price (-> params
+                  (select-keys [:commodity-id
+                                :trade-date
+                                :price])
+                  (tag-resource :price)
+                  (authorize :create))
+        result (prices/create (env :db) price)]
     (if (validation/has-error? result)
       (new-price {:params params} result)
       (redirect (format "/commodities/%s/prices" (:commodity-id result))))))

 (defn delete
   [{params :params}]
-  (let [price (prices/find-by-id (env :db) (Integer. (:id params)))]
+  (let [price (authorize (prices/find-by-id (env :db) (Integer. (:id params)))
+                         :delete)]
     (prices/delete (env :db) (:id price))
     (redirect (format "/commodities/%s/prices" (:commodity-id price)))))


Fully spell out card names.

Fully spell out card names.

--- src/cljs-blackjack/core.cljs
+++ src/cljs-blackjack/core.cljs
@@ -175,7 +175,7 @@
   [event]
   (swap! game assoc :current-bet 10 :player-money 1000))

-(def cardnames ["ace", "2", "3", "4", "5", "6", "7", "8", "9" "10" "J" "Q" "K"])
+(def cardnames ["Ace", "2", "3", "4", "5", "6", "7", "8", "9" "10" "Jack" "Queen" "King"])
 (def suits ["clubs" "diamonds" "hearts" "spades"])

 (defn english


Fix artifact creatures being shown as both an artifact and a creature

--- src/cljs/decktouch/core.cljs
+++ src/cljs/decktouch/core.cljs
@@ -65,13 +65,13 @@
       [:div.col-md-2
         [card-type-list cards "Creature"]
         [card-type-list cards "Land"]]
-      [:div.col-md-2
-        [card-type-list cards "Planeswalker"]
-        [card-type-list cards "Instant"]
-        [card-type-list cards "Sorcery"]
-        (let [noncreature-cards (remove-cards-by-type cards "Creature")]
-          [card-type-list noncreature-cards "Enchantment" {:not "Creature"}])
-        [card-type-list cards "Artifact"]]]))
+      (let [noncreature-cards (remove-cards-by-type cards "Creature")]
+        [:div.col-md-2
+          [card-type-list cards "Planeswalker"]
+          [card-type-list cards "Instant"]
+          [card-type-list cards "Sorcery"]
+          [card-type-list noncreature-cards "Enchantment"]
+          [card-type-list noncreature-cards "Artifact"]])]))

 (defn record-mana-freq [mana-map mana]
   (if (contains? mana-map mana)


refactor ai

refactor ai

--- src/cljs/triboard/ai/ai.cljs
+++ src/cljs/triboard/ai/ai.cljs
@@ -15,21 +15,21 @@
 (def eval-counter (atom 0))

 (defprotocol AIStrategy
-  (optimized-score [this scores] "Extract data from the score to compare")
-  (maximizing-turn? [this turn] "Indicates whether we are in min or max"))
+  (eval-score [this scores] "Heuristic to score the value of a turn")
+  (maximizing? [this turn] "Tell whether we are in min or max step"))

 (defn- make-ai
   [player]
   (reify AIStrategy
-    (optimized-score [_ scores] (get scores player))
-    (maximizing-turn? [_ turn] (= (:player turn) player))
+    (eval-score [_ scores] (get scores player))
+    (maximizing? [_ turn] (= (:player turn) player))
     ))

 (defn- make-cheating-ai
   [player]
   (reify AIStrategy
-    (optimized-score [_ scores] (+ (:red scores) (:green scores)))
-    (maximizing-turn? [_ turn] (not= (:player turn) :blue))
+    (eval-score [_ scores] (+ (:red scores) (:green scores)))
+    (maximizing? [_ turn] (not= (:player turn) :blue))
     ))

 ;; -----------------------------------------
@@ -39,7 +39,7 @@
    & {:keys [max-fn min-fn]
       :or {max-fn max, min-fn min}}]
   (apply
-    (if (maximizing-turn? ai turn) max-fn min-fn)
+    (if (maximizing? ai turn) max-fn min-fn)
     (map
       (fn [[coord transition]] (on-transition coord transition))
       (turn/transitions turn))))
@@ -58,16 +58,16 @@
   [ai {:keys [scores] :as turn}]
   (swap! eval-counter inc)
   (min-max-step ai turn
-    (fn look-ahead [_ transition]
-      (optimized-score ai (scores/update-scores scores transition))
+    (fn [_ transition]
+      (eval-score ai (scores/update-scores scores transition))
       )))

 (defn- tree-score
   [ai turn depth]
-  (if (= 0 depth)
+  (if (zero? depth)
     (leaf-score ai turn)
     (min-max-step ai turn
-      (fn look-lower [_ transition]
+      (fn [_ transition]
         (tree-score ai
           (turn/next-turn turn transition)
           (dec depth))))


Work on island-fn

Work on island-fn

--- src/cljx/robinson/noise.cljx
+++ src/cljx/robinson/noise.cljx
@@ -146,17 +146,19 @@
 ;;(def n (create-noise))

 (defn print-fn
-  [f width height]
+  ([f width height]
+  (print-fn (fn [v]
+              (let [idx (if (zero? v)
+                            (dec (count ascii-chars))
+                            (- (count ascii-chars)
+                               (* v (count ascii-chars))))]
+                (nth ascii-chars (min (max idx 0) (dec (count ascii-chars))))))
+            f width height))
+  ([map-f f width height]
   (let [px (partition height (for [x (range (- (/ width 2)) (/ width 2))
                                    y (range (- (/ height 2)) (/ height 2))]
                                (f (/ x 10) (/ y 10))))]
     (doseq [line px]
       (println
-        (apply str (map (fn [c]
-                          (let [idx (if (zero? c)
-                                        (dec (count ascii-chars))
-                                        (- (count ascii-chars)
-                                           (* c (count ascii-chars))))]
-                            (nth ascii-chars (min (max idx 0) (dec (count ascii-chars))))))
-                        line))))))
+        (apply str (map map-f line)))))))