WIP.  starting to add results endpoint tests

--- test/lcmap/clownfish/endpoints_test.clj
+++ test/lcmap/clownfish/endpoints_test.clj
@@ -11,6 +11,20 @@

 (def json-header {"Accept" "application/json"
                   "Content-Type" "application/json"})
+
+(defn upsert-algorithm
+  [http-host {:keys [algorithm enabled inputs_url_template] :as all}]
+  (req :put (str http-host "/algorithm/" algorithm)
+       :body (json/encode all)
+       :headers json-header))
+
+(defn get-algorithm
+  [http-host algorithm]
+  (req :get (str http-host "/algorithm/" algorithm)))
+
+(defn get-algorithms
+  [http-host]
+  (req :get (str http-host "/algorithms")))

 (deftest changes-health-resource
   (with-system
@@ -43,23 +57,23 @@
                 (is (contains? #{403 500} status)))))

     (testing "add good algorithm"
-      (let [body   {:enabled false :inputs_url_template "http://host"}
-            resp   (req :put (str http-host "/algorithm/good")
-                        :body (json/encode body)
-                        :headers json-header)
+      (let [body   {:algorithm "good"
+                    :enabled false
+                    :inputs_url_template "http://host"}
+            resp   (upsert-algorithm http-host body)
             status (:status resp)]
           (is (= 202 status))))

     (testing "update algorithm")
-    (let [body     {:enabled true :inputs_url_template "http://anotherhost"}
-          response (req :put (str http-host "/algorithm/good")
-                        :body (json/encode body)
-                        :headers json-header)
+    (let [body     {:algorithm "good"
+                    :enabled true
+                    :inputs_url_template "http://anotherhost"}
+          response (upsert-algorithm http-host body)
           status   (:status response)]
         (is (= 202 status)))

     (testing "get algorithm"
-      (let [resp     (req :get (str http-host "/algorithm/good"))
+      (let [resp     (get-algorithm http-host "good")
             status   (:status resp)
             body     (:body resp)
             expected {:algorithm "good"
@@ -69,7 +83,7 @@
         (is (= (json/decode body true) expected))))

     (testing "get algorithms"
-      (let [resp   (req :get (str http-host "/algorithms"))
+      (let [resp   (get-algorithms http-host)
             status (:status resp)
             body   (:body resp)
             expected [{:algorithm "good"
@@ -80,6 +94,12 @@

 (deftest results
   (with-system
+    ;; put a good alg in the system
+    (upsert-algorithm http-host {:algorithm "test-alg"
+                                 :enabled true
+                                 :inputs_url_template
+                                 "http://host/{algorithm}/{x}/{y}/{now}"})
+
     (testing "run non-existent algorithm")
     (testing "schedule existing algorithm")
     (testing "schedule same algorithm, get ticket")


Remove most of querier/commander from measurements api.

--- src/kixi/hecuba/api/measurements.clj
+++ src/kixi/hecuba/api/measurements.clj
@@ -69,14 +69,16 @@

 (defn retrieve-measurements
   "Iterate over a sequence of months and concatanate measurements retrieved from the database."
-  [querier start-date end-date device-id reading-type]
+  [session start-date end-date device-id reading-type]
   (let [range  (time-range start-date end-date (t/months 1))
         months (map #(util/get-month-partition-key (tc/to-date %)) range)
         where  [[= :device_id device-id]
                 [= :type reading-type]
                 [>= :timestamp (tc/to-date start-date)]
                 [<= :timestamp (tc/to-date end-date)]]]
-    (mapcat (fn [month] (hecuba/items querier :measurement (conj where [= :month month]))) months)))
+    (mapcat (fn [month] (dbnew/execute session
+                          (hayt/select :measurements
+                                       (hayt/where (conj where [= :month month]))))) months)))

 (defn- parse-measurements [measurements]
   (map (fn [m]
@@ -97,7 +99,7 @@

 (defn measurements-slice-handle-ok [store store-new ctx]
   (let [request                (:request ctx)
-        querier                (:querier store)
+        session                (:hecuba-session store-new)
         {:keys [route-params
                 query-string]} request
         {:keys [device_id
@@ -105,7 +107,7 @@
         decoded-params         (util/decode-query-params query-string)
         start-date             (util/to-db-format (string/replace (get decoded-params "startDate") "%20" " "))
         end-date               (util/to-db-format (string/replace (get decoded-params "endDate") "%20" " "))
-        measurements           (retrieve-measurements querier start-date end-date device_id reading-type)]
+        measurements           (retrieve-measurements session start-date end-date device_id reading-type)]

     (format-measurements ctx measurements)))

@@ -125,9 +127,11 @@
                                (hayt/where [[= :device_id device_id]
                                             [= :type type]])))))

-(defn index-post! [store store-new queue ctx]
-  (let [{:keys [commander querier]} store
-        request       (:request ctx)
+(defn- insert-measurement [session m]
+  (dbnew/execute session (hayt/insert :measurements (hayt/values m))))
+
+(defn index-post! [store-new queue ctx]
+  (let [request       (:request ctx)
         route-params  (:route-params request)
         device_id     (:device_id route-params)
         topic         (get-in queue ["measurements"])
@@ -149,43 +153,49 @@
                       :metadata  {}}]
               (->> m2
                    (v/validate store-new)
-                   (hecuba/upsert! commander :measurement))
+                   (insert-measurement session))

               (update-bounds! t)
               (q/put-on-queue topic m2)))
-          (hecuba/upsert! commander :sensor_metadata {:device_id device_id
-                                                      :type type
-                                                      :lower_ts @lower
-                                                      :upper_ts @upper})
-
-          (hecuba/upsert! commander :sensor_metadata {:device_id device_id
-                                                      :type type
-                                                      :lower_ts @lower
-                                                      :upper_ts @upper})
+          (dbnew/execute session
+                         (hayt/insert :sensor_metadata
+                                      (hayt/values {:device_id device_id
+                                                    :type type
+                                                    :lower_ts @lower
+                                                    :upper_ts @upper})))
+
+          (dbnew/execute session
+                         (hayt/insert :sensor_metadata
+                                      (hayt/values {:device_id device_id
+                                                    :type type
+                                                    :lower_ts @lower
+                                                    :upper_ts @upper})))
           {:response {:status 202 :body "Accepted"}})
         {:response {:status 400 :body "Provide valid device_id and type."}}))))

-(defn index-handle-ok [store store-new ctx]
-  (let [{:keys [querier]} store
-        request (:request ctx)
-        route-params (:route-params request)
-        device_id (:device_id route-params)
-        where [[= :device_id device_id]]
-        measurements (hecuba/items querier :measurement where)]
-    {:measurements (->> measurements
-                        (map #(-> %
-                                  util/parse-value
-                                  (update-in [:timestamp] util/db-to-iso)
-                                  (dissoc :metadata :device_id :month))))}))
+(defn index-handle-ok [store-new ctx]
+  (dbnew/with-session [session (:hecuba-session store-new)]
+    (let [request (:request ctx)
+          route-params (:route-params request)
+          device_id (:device_id route-params)
+          where [[= :device_id device_id]]
+          measurements (dbnew/execute session
+                                      (hayt/select :measurements
+                                                   (hayt/where where)))]
+      {:measurements (->> measurements
+                          (map #(-> %
+                                    util/parse-value
+                                    (update-in [:timestamp] util/db-to-iso)
+                                    (dissoc :metadata :device_id :month))))})))

 (defn index-handle-created [ctx]
   (ring-response (:response ctx)))

-(defn measurements-by-reading-handle-ok [store store-new ctx]
+(defn measurements-by-reading-handle-ok [store-new ctx]
   (let [{:keys [request]} ctx
         {:keys [route-params]} request
         {:keys [device_id sensor-type timestamp]} route-params
-        measurement (dbnew/with-session [session (:hecuba-session store)]
+        measurement (dbnew/with-session [session (:hecuba-session store-new)]
                       (dbnew/execute session
                                      (hayt/select :measurements
                                                   (hayt/where [[= :device_id device_id]
@@ -199,19 +209,19 @@
   :available-media-types #{"application/json" "text/csv"}
   :known-content-type? #{"application/json" "text/csv"}
   :authorized? (authorized? (:querier store) :measurement)
-  :handle-ok (partial measurements-slice-handle-ok store store-new))
+  :handle-ok (partial measurements-slice-handle-ok store-new))

 (defresource index [store store-new queue handlers]
   :allowed-methods #{:post :get}
   :available-media-types #{"application/json"}
   :known-content-type? #{"application/json"}
   :authorized? (authorized? (:querier store) :measurement)
-  :post! (partial index-post! store store-new queue)
-  :handle-ok (partial index-handle-ok store store-new )
+  :post! (partial index-post! store-new queue)
+  :handle-ok (partial index-handle-ok store-new)
   :handle-created index-handle-created)

 (defresource measurements-by-reading [store store-new handlers]
   :allowed-methods #{:get}
   :available-media-types #{"application/json"}
   :authorized? (authorized? (:querier store) :measurement)
-  :handle-ok (partial measurements-by-reading-handle-ok store store-new))
+  :handle-ok (partial measurements-by-reading-handle-ok store-new))


finished first draft of deseasonalize function

--- src/clj/forma/bangfunc.clj
+++ src/clj/forma/bangfunc.clj
@@ -27,12 +27,12 @@
   [x]
   (i/matrix (repeat x 1)))

-; De-seasonalize time-series
+;De-seasonalize time-series

 (defn seasonal-rows [n]
   "lazy sequence of monthly dummy vectors"
   (vec
-    (take n (partition 11 1 (cycle (cons 1 (repeat 11 0)))))))
+   (take n (partition 11 1 (cycle (cons 1 (repeat 11 0)))))))

 (defn seasonal-matrix
   "create a matrix of [num-months]x11 of monthly dummies, where
@@ -40,6 +40,7 @@
   [num-months]
   (i/bind-columns (ones-column num-months)
                   (seasonal-rows num-months)))
+

 (defn deseasonalize
   "deseasonalize a time-series [ts] using monthly dummies. returns
@@ -49,20 +50,19 @@
   (let [avg-seq (repeat (count ts) (average ts))
         X    (seasonal-matrix (count ts))
         fix  (i/mmult (variance-matrix X) (i/trans X) ts)
-        adj  (i/mmult (i/sel X :except-cols 0) (i/sel fix :except-rows 0))
-        ats  (i/plus avg-seq (i/minus ts adj))]
-  ats))
+        adj  (i/mmult (i/sel X :except-cols 0) (i/sel fix :except-rows 0))]
+     (i/plus avg-seq (i/minus ts adj))))

-;
-(def plot1 (c/line-chart (range (count test-ts)) (deseasonalize test-ts)))
-; (c/add-lines plot1 (range 50) (range 50))
+
+(def plot1 (c/scatter-plot (i/matrix (range (count test-ts))) (deseasonalize test-ts)))
+(add-lines plot1 (i/matrix (range (count test-ts))) test-ts)

 ; WHOOPBANG
-
+
 (defn whoop-cofactor
-  "construct a matrix of cofactors; first column is comprised
-  of ones, second column is a range from 1 to [num-months].  The
-  result is a [num-months]x2 incanter matrix."
+  "construct a matrix of cofactors; first column is comprised of ones,
+  second column is a range from 1 to [num-months].  The result is a
+  [num-months]x2 incanter matrix."
   [num-months]
   (i/trans (i/bind-rows (repeat num-months 1) (range 1 (inc num-months)))))

@@ -102,4 +102,4 @@
 ; (defn matrix-map
 ;   [m func]
 ;   "Apply a function to every element in a matrix"
-;   (map (fn [x] (map func x)) m))+;   (map (fn [x] (map func x)) m))


Add Turnpike

Add Turnpike

--- src/clj/game/cards-ice.clj
+++ src/clj/game/cards-ice.clj
@@ -578,7 +578,13 @@
    "Turing"
    {:abilities [end-the-run]
     :strength-bonus (req (if (= (second (:zone card)) :remote) 3 0))}
-
+
+   "Turnpike"
+   {:abilities [{:msg "force the Runner to lose 1 [Credits]"
+                 :effect (effect (lose :runner :credit 1))}
+                {:label "Trace 5 - Give the Runner 1 tag"
+                 :trace {:base 5 :msg "give the Runner 1 tag" :effect (effect (gain :runner :tag 1))}}]}
+
    "Tyrant"
    {:advanceable :while-rezzed :abilities [end-the-run]}


fix datomic address

fix datomic address

--- src/clj/lesezeichen/db.clj
+++ src/clj/lesezeichen/db.clj
@@ -6,7 +6,7 @@
             [lesezeichen.io :refer [transact-all]]))

-(def db-uri-base "datomic:dev://0.0.0.0:4334")
+(def db-uri-base "datomic:free://0.0.0.0:4334")

 (defn- scratch-conn
   "Create a connection to an anonymous, in-memory database."
@@ -135,28 +135,29 @@

   (def conn (db-conn))

-  (init-schema "schema.edn")
+  (init-schema conn "schema.edn")

-  (add-user {:email "eve@topiq.es"})
+  (add-user conn {:email "eve@topiq.es"})

-  (add-user {:email "adam@topiq.es"})
+  (add-user conn {:email "adam@topiq.es"})

-  (do
-   (add-bookmark {:url "https://topiq.es" :title "TOPIQ" :email "eve@topiq.es"})
-   (add-bookmark {:url "https://google.com" :title "the kraken" :email "eve@topiq.es"})
-   (add-bookmark {:url "https://sup.com" :title "the void 2" :email "adam@topiq.es"})
-   (add-bookmark {:url "http://boo.far" :title "foobar" :email "eve@topiq.es"})
-   (add-bookmark {:url "http://boo.far" :title "foobar" :email "adam@topiq.es"}))
+  (doall
+      [(add-bookmark conn {:url "https://topiq.es" :title "TOPIQ" :email "eve@topiq.es"})
+       (add-bookmark conn {:url "https://google.com" :title "the kraken" :email "eve@topiq.es"})
+       (add-bookmark conn {:url "https://sup.com" :title "the void 2" :email "adam@topiq.es"})
+       (add-bookmark conn {:url "http://boo.far" :title "foobar" :email "eve@topiq.es"})
+       (add-bookmark conn {:url "http://boo.far" :title "foobar" :email "adam@topiq.es"})])
+
   ;; -------

   ;; some queries
-  (-> (get-user-bookmarks "eve@topiq.es")
+  (-> (get-user-bookmarks conn "eve@topiq.es")
       aprint)

-  (let [users (get-all-users)]
+  (let [users (get-all-users conn)]
     (->> users
-         (map get-user-bookmarks)
+         (map #(get-user-bookmarks conn %))
          (zipmap users)
          aprint))


fixes for currency amounts

fixes for currency amounts

--- src/clj/stripe/balance.clj
+++ src/clj/stripe/balance.clj
@@ -10,7 +10,7 @@
 ;; ### Schema

 (def BalanceAmount
-  {:amount ss/NonNegativeInt
+  {:amount s/Int
    :currency ss/CurrencyID})

 (def BalanceTxID
@@ -74,15 +74,19 @@
 ;; ### Helpers

 (s/defn available-amount :- ss/NonNegativeInt
-  "Returns the current amount in USD currently available in our
-  account."
-  [balance :- Balance]
-  (-> balance :available first :amount))
+  "Returns the current amount in the given currency or USD currently
+  available in our account."
+  [{:keys [available]} :- Balance
+   & opts]
+  (let [currency (:currency (first opts) "usd")]
+    (:amount (first (filter (comp #{currency} :currency) available)))))

 (s/defn pending-amount :- ss/NonNegativeInt
-  "Returns the current amount in USD pending in our account."
-  [balance :- Balance]
-  (-> balance :pending first :amount))
+  "Returns the current amount in the given currency or USD pending in our account."
+  [{:keys [pending]} :- Balance
+   & opts]
+  (let [currency (:currency (first opts) "usd")]
+    (:amount (first (filter (comp #{currency} :currency) pending)))))

 (s/defn tx-fee :- s/Int
   [tx :- BalanceTx]


Trying to nest queries.. a little hard

Trying to nest queries.. a little hard

--- src/cljs/conedit/main.cljs
+++ src/cljs/conedit/main.cljs
@@ -2,6 +2,8 @@
   (:require [goog.dom :as gdom]
             [om.next :as om :refer-macros [defui]]
             [om.dom :as dom]))
+
+(enable-console-print!)

 (def app-state
@@ -11,21 +13,24 @@
           {:name "pivnet-develop"}
           ]}))

-(declare reconciler)
-
-
 (defui ResourceItem
+  static om/IQuery
+  (query [this]
+    [:name])
   Object
   (render [this]
-    (dom/li nil (:name (om/props this)))))
+    (dom/li nil (str (:name (om/props this)) " " (:foo (om/props this))))))

 (def resource-item (om/factory ResourceItem {:keyfn :name}))

 (defui ResourceList
+  static om/IQuery
+  (query [this]
+    [{:resources (om/get-query ResourceItem)}])
   Object
   (render [this]
     (dom/ul nil
-      (map resource-item (om/props this))
+      (map resource-item (:resources (om/props this)))
       (dom/button
         #js {:onClick #(om/transact! reconciler '[(add-resource)])}
         "Add"))))
@@ -35,17 +40,23 @@
 (defui App
   static om/IQuery
   (query [this]
-    [:resources])
+    [{:root-resources (om/get-query ResourceList)}])
   Object
   (render [this]
-    (dom/div nil (resource-list (:resources (om/props this))))))
+    (dom/div nil (resource-list (:root-resources (om/props this))))))

-; env is more than just the app-atom
-(defn read [{:keys [state] :as env} key params]
+
+(defmulti read (fn [env key params] key))
+
+(defmethod read :default [{:keys [state] :as env} key params]
   (let [data @state]
-    (if-let [[_ resources] (find data key)]
-      {:value resources}
+    (if-let [[_ value] (find data key)]
+      {:value value}
       {:value :not-found})))
+
+(defmethod read :root-resources [{:keys [state] :as env} key params]
+  {:value {:resources (:value (read env :resources params))}})
+

 (defn mutate [{:keys [state] :as env} key params]
   {:action #(swap! state update-in [:resources] conj {:name "New!"})}


one param to cb

one param to cb

--- src/cljs/html2om/core.cljs
+++ src/cljs/html2om/core.cljs
@@ -113,9 +113,7 @@
                  :url "/api"
                  :data data
                  :on-complete (fn [x]
-                                (cb x
-                                    (:remote data)
-                                    )
+                                (cb x)
                                 )
      }
     )


Cosmetic fixes (#78)

Cosmetic fixes (#78)

- Was having trouble clicking the Reminder window close, added Z-index.
- Renamed Thread -> Context, Memories -> Thoughts. They gives a better
  idea of what's going on.

--- src/cljs/memento/core.cljs
+++ src/cljs/memento/core.cljs
@@ -186,9 +186,9 @@
           [:i {:style {:top       "0px"
                        :right     "5px"
                        :font-size "24px"
+                       :z-index   999
                        :position  "absolute"}
-               :class "fa fa-window-close"}
-           ]]
+               :class "fa fa-window-close"}]]
          (for [item (sort-by :created @reminders)]
            ;; Need to figure out if the reminder has a day-idx in its schedule,
            ;; since legacy reminders will not.  See #73.
@@ -226,7 +226,7 @@
                 (if (:root_id thought)
                   [:a {:class "btn btn-primary btn-xs"
                        :href  (str "/thread/" (:root_id thought))}
-                   [:i {:class "fa fa-list-ul icon-margin-both"}] "Thread"])
+                   [:i {:class "fa fa-list-ul icon-margin-both"}] "Context"])
                 [:a {:class    "btn btn-primary btn-xs"
                      :on-click #(do
                                   (.scrollIntoView top-div-target)
@@ -345,7 +345,7 @@
          (if (and show-thread-btn? (:root_id memory))
            [:a {:class "btn btn-primary btn-xs"
                 :href  (str "/thread/" (:root_id memory))}
-            [:i {:class "fa fa-list-ul icon-margin-both"}] "Thread"])
+            [:i {:class "fa fa-list-ul icon-margin-both"}] "Context"])
          [:a {:class    "btn btn-primary btn-xs"
               :on-click #(do
                            (.scrollIntoView top-div-target)
@@ -415,7 +415,7 @@
     (fn []
       [panel (if @busy?
                [:span "Loading..." [:i {:class "fa fa-spin fa-space fa-circle-o-notch"}]]
-               "Memories")
+               "Thoughts")
        [:span
         (if (empty? @results)
           [:p "Nothing."]


Fix validation

Fix validation

--- src/cljs/re_form/core.cljs
+++ src/cljs/re_form/core.cljs
@@ -27,9 +27,10 @@

 (rf/reg-sub-raw
  :re-form/input-errors
- (fn [db [_ form-name path]]
-   (let [cur (reagent/cursor db [:re-form form-name :errors path])]
-     (reaction @cur))))
+ (fn [db [_ form-name paths]]
+   (let [cur (reagent/cursor db [:re-form form-name :errors])
+         path-set (set paths)]
+     (reaction (vec (mapcat second (filterv (fn [[k _]] (path-set k)) @cur)))))))

 (rf/reg-sub-raw
  :re-form/form-value
@@ -116,7 +117,7 @@
   (when-not (empty? validators)
     (let [errors
           (reduce (fn [acc validator]
-                    (when-let [res (validator val path)]
+                    (if-let [res (validator val path)]
                       (if (or (vector? res) (list? res))
                         (into acc res)

@@ -127,7 +128,8 @@
                                 (rf/dispatch [:re-form/add-validation-errors form-name e-path e])))
                             acc)

-                          (conj acc res)))))
+                          (conj acc res)))
+                      acc))
                   []
                   validators)]
       (rf/dispatch [:re-form/validation-errors form-name {path errors}]))))
@@ -193,10 +195,10 @@
         (update-binding (second new-props)))

       :reagent-render
-      (fn [{:keys [on-change form-name path on-blur] :as props}]
+      (fn [{:keys [on-change form-name path on-blur error-paths] :as props}]
         (let [flags @(rf/subscribe [:re-form/input-flags form-name path])
               is-form-submitting @(rf/subscribe [:re-form/is-form-submitting form-name])
-              errors @(rf/subscribe [:re-form/input-errors form-name path])]
+              errors @(rf/subscribe [:re-form/input-errors form-name (into [path] error-paths)])]
           [:div.re-form-field {:class (->> flags
                                            (filter second)
                                            (map #(name (first %)))


Fix typo and remove markdown from repl.cljs docstrings

--- src/cljs/replumb/repl.cljs
+++ src/cljs/replumb/repl.cljs
@@ -467,7 +467,7 @@

   Call-back! supports the following opts:

-  * :verbose will enable the the evaluation logging, defaults to false.
+  * :verbose will enable the evaluation logging, defaults to false.
   * :no-pr-str-on-value avoids wrapping successful value in a pr-str
   * :warning-as-error will consider a warning like an error

@@ -903,14 +903,14 @@
   file is found). It is mutually exclusive with :load-fn! and will be
   ignored in case both are present

-  * `:write-file-fn!` a synchronous 2-arity function with signature
-  `[file-path data]` that accepts a file-path and data to write.
+  * :write-file-fn! a synchronous 2-arity function with signature
+  [file-path data] that accepts a file-path and data to write.

   * :src-paths - a vector of paths containing source files

   * :cache - a map containing two optional values: the first, :path, indicates
   the path of the cached files. The second, :src-paths-lookup?, indicates
-  if look for cached files in :src-paths. If both present, `:path` will have
+  if look for cached files in :src-paths. If both present, :path will have
   the priority but both will be inspected.

   * :no-pr-str-on-value - in case of :success? avoid converting the
@@ -919,7 +919,7 @@
   * :context - indicates the evaluation context that will be passed to
   cljs/eval-str. Defaults to :expr.

-  * `:foreign-libs` - a way to include foreign libraries. The format is analogous
+  * :foreign-libs - a way to include foreign libraries. The format is analogous
   to the compiler option. For more info visit https://github.com/clojure/clojurescript/wiki/Compiler-Options#foreign-libs

   The second parameter cb, is a 1-arity function which receives the
@@ -939,7 +939,7 @@

   It initializes the repl harness either on first execution or if an
   option in #{:src-paths :init-fn!} changes from the previous
-  `read-eval-call`."
+  read-eval-call."
   [opts cb source]
   (try
     (let [expression-form (repl-read-string source)


Fixed table refresh issue

Fixed table refresh issue

--- src/cljs/org/broadinstitute/firecloud_ui/common/table.cljs
+++ src/cljs/org/broadinstitute/firecloud_ui/common/table.cljs
@@ -189,7 +189,8 @@
        [:div {}
         (when (:filterable? props)
           (let [apply-filter #(swap! state assoc :filtered-data
-                               (react/call :filter-data this (-> (@refs "filter-field") .getDOMNode .-value trim)))]
+                               (react/call :filter-data this props
+                                 (-> (@refs "filter-field") .getDOMNode .-value trim)))]
             [:div {:style {:padding "0 0 1em 1em"}}
              (style/create-text-field {:ref "filter-field" :placeholder "Filter"
                                        :onKeyDown (common/create-key-handler
@@ -233,7 +234,7 @@
                        (case (:sort-order @state)
                          :asc (swap! state assoc :sort-order :desc)
                          :desc (swap! state dissoc :sort-column :sort-order :key-fn)
-                         :else (assert false "bad state"))
+                         (assert false "bad state"))
                        (swap! state assoc :sort-column i :sort-order :asc
                          :key-fn (if (= :value sorter)
                                    (fn [row] (nth row i))
@@ -257,7 +258,7 @@
            ordered-data (if (= :desc (:sort-order @state)) (reverse sorted-data) sorted-data)]
        (take c (drop (* (dec n) c) ordered-data))))
    :filter-data
-   (fn [{:keys [props]} & [filter-text]]
+   (fn [{:keys []} & [props filter-text]]
      (if (empty? filter-text)
        (:data props)
        (filter
@@ -274,4 +275,8 @@
          (:data props))))
    :handle-pagination-change
    (fn [{:keys [this refs]}]
-     (react/call :set-rows (@refs "body") (react/call :get-sliced-data this)))})
+     (react/call :set-rows (@refs "body") (react/call :get-sliced-data this)))
+   :component-will-receive-props
+   (fn [{:keys [this state next-props refs]}]
+     (swap! state assoc :filtered-data
+       (react/call :filter-data this next-props (-> (@refs "filter-field") .getDOMNode .-value trim))))})


Fix new-meta value.

Fix new-meta value.

--- src/geschichte/synch.clj
+++ src/geschichte/synch.clj
@@ -30,11 +30,12 @@
   IPeer
   (-update [this user repo new-meta]
     (let [old @state ;; eventual consistent, race condition ignorable
-          new (swap! state update-in [user repo] update new-meta)]
+          new (swap! state update-in [user repo] update new-meta)
+          new-meta* (get-in new [user repo])]
       (when (not= new old) ;; notify peers
         (doseq [peer (get-in old [:peers user repo])]
-          (-update (network peer) user repo new-meta)))
-      {:new (get-in new [user repo])
+          (-update (network peer) user repo new-meta*)))
+      {:new new-meta*
        :new-revs (set/difference (set (keys new-meta))
                                  (set (keys (get-in old [user repo]))))}))
   (-subscribe [this address subs]


grep 0.2 DONE // still needs tests

grep 0.2 DONE // still needs tests

--- src/grafter/tabular.clj
+++ src/grafter/tabular.clj
@@ -251,12 +251,11 @@
                                  (some f
                                        (cells-from-columns col-set row))))))))

-
-(defmethod grep java.lang.String [dataset s cols]
-  (grep dataset #(.contains % s) cols))
+(defmethod grep java.lang.String [dataset s & cols]
+  (apply grep dataset #(.contains % s) cols))

 (defmethod grep java.util.regex.Pattern [dataset p & cols]
-  (grep dataset #(re-find p %) cols))
+  (apply grep dataset #(re-find p %) cols))

 (defn- remove-indices [col & idxs]
   "Removes the values at the supplied indexes from the given vector."


Added change-goal to API

Added change-goal to API

--- src/kmg/core.clj
+++ src/kmg/core.clj
@@ -41,16 +41,23 @@
   (model/mark-as-completed user recommendation)
   (response nil))

+(defn change-goal [user specialization]
+  (log/info "user: " user "change goal to specialization: " specialization)
+  (model/change-goal user specialization)
+  (response nil))

 (defroutes recommendation-routes
   (GET "/list/:user" [user] (recommendations user))
   (GET "/list/:user/:spec" [user spec] (recommendations user spec))
   (GET "/completed/:user" [user] (recommendations-completed user))
-  (POST "/mark-as-completed/:user/:recommendation" [user recommendation] (mark-as-completed user recommendation)))
+  (POST "/mark-as-completed/:user/:recommendation" [user recommendation]
+        (mark-as-completed user recommendation)))

 (defroutes specialization-routes
   (GET "/completed/:user" [user] (specializations-completed user))
-  (GET "/available/:user" [user] (specializations-available user)))
+  (GET "/available/:user" [user] (specializations-available user))
+  (GET "/change-goal/:user/:specialization" [user specialization]
+       (change-goal user specialization)))

 (defroutes user-routes
   (GET "/list" [] (user-list)))


leeres sql

leeres sql

--- src/hello_world/core.clj
+++ src/hello_world/core.clj
@@ -27,11 +27,10 @@
 ;(jdbc/execute! mysql-db ["UPDATE konten SET Kontostand = Kontostand + 1 WHERE NurZahlen = 0 AND Name = ?" empfaenger]))
 ;(jdbc/update! mysql-db :konten {:Kontostand 99} ["Name = ?" name]))
 ; maybe this sets the guthaben to 99
-(jdbc/execute! mysql-db ["insert into transaktionen_geberkonten2nehmerkonten (betrag) select MIN(geberkonten.stand) from geberkonten where geberkonten.nr in ('?', '00000000-0000-0000-0000-00000025')" name])
-
-(jdbc/execute! mysql-db ["update transaktionen_geberkonten2nehmerkonten set sender='?', empfaenger='?'  where transaktions_id = last_insert_id()" name empfaenger])
-
-(jdbc/execute! mysql-db ["update geberkonten set stand = stand - 25 where geberkonten.nr = '?' AND stand > 0" name]))
+;(jdbc/execute! mysql-db ["insert into transaktionen_geberkonten2nehmerkonten (betrag) select MIN(geberkonten.stand) from geberkonten where geberkonten.nr in ('?', '00000000-0000-0000-0000-00000025')" name])
+;(jdbc/execute! mysql-db ["update transaktionen_geberkonten2nehmerkonten set sender='?', empfaenger='?'  where transaktions_id = last_insert_id()" name empfaenger])
+;(jdbc/execute! mysql-db ["update geberkonten set stand = stand - 25 where geberkonten.nr = '?' AND stand > 0" name])
+)


ououou - schlecht geraten, wie man json bastelt

--- src/hello_world/core.clj
+++ src/hello_world/core.clj
@@ -4,7 +4,8 @@
   (:require [ring.middleware.params :as p]
         [ring.util.response :as r]
         [ring.adapter.jetty :as j]
-            [clojure.java.jdbc :as jdbc])
+        [clojure.java.jdbc :as jdbc]
+        [ring.middleware.json :as wrap-json-response])
   (:gen-class))

 (let [db-host "localhost"
@@ -42,7 +43,7 @@
       (r/content-type "application/json")))

 (def app
-  (-> handler p/wrap-params))
+  (-> wrap-json-response handler p/wrap-params))

 (defn -main
  "Kommentar."


Remove debug.

Remove debug.

--- src/onyx/log/commands/complete_task.clj
+++ src/onyx/log/commands/complete_task.clj
@@ -1,11 +1,9 @@
 (ns onyx.log.commands.complete-task
   (:require [com.stuartsierra.component :as component]
-            [onyx.extensions :as extensions]
-            [taoensso.timbre :refer [info]]))
+            [onyx.extensions :as extensions]))

 (defmethod extensions/apply-log-entry :complete-task
   [{:keys [args message-id]} replica]
-  (taoensso.timbre/info (format "Completing task %s" (:task args)))
   (let [peers (get-in replica [:allocations (:job args) (:task args)])]
     (-> replica
         (update-in [:completions (:job args)] conj (:task args))


Tiniest tweak for sync error logging :shower:

--- src/metabase/task/sync_databases.clj
+++ src/metabase/task/sync_databases.clj
@@ -28,7 +28,7 @@
         ;; at midnight we run the full sync
         (sync-database/sync-database! database :full-sync? true))
       (catch Throwable e
-        (log/error "Error syncing database: " (:id database) e)))))
+        (log/error (format "Error syncing database %d: " (:id database)) e)))))

 (defn task-init
   "Automatically called during startup; start the job for syncing databases."


clicking on other baskets loads them

clicking on other baskets loads them

--- src/eatme/client/main.cljs
+++ src/eatme/client/main.cljs
@@ -10,16 +10,12 @@
             [domina.css :as css]
             [domina.xpath :as x]
             [eatme.client.render :as render]
-            [clojure.string :as string])
+            [clojure.string :as string]
+            [one.browser.history :as history])
   (:require-macros [shoreleave.remotes.macros :as srm]))

 (def query-args (common/query-args-map))
 (def hash-args (common/hash-args-map))
-
-;; Integrate history/back-button to the search
-;For example:
-;    (history/navigate-callback #(process-search (subs (:token %) 4) false))
-;Where process-search is the main action to take when processing the page/url

 ;; ### Browser REPL
 ;; If you add a `repl` as a query-string arg, even on the live site,
@@ -37,11 +33,10 @@
 ;;    :on-success (js/alert "You should never see this")
 ;;    :on-error (js/alert "Remotes correctly handle error conditions"))

-(defn- basket-id
-  ([] (when-let [matches (re-matches #".*/#([1-9]*)"
-                                     (.-href (.-location js/window)))]
-        (last matches)))
-  ([id] (.assign (.-location js/window) (str "#" id))))
+(defn- basket-id []
+  (when-let [matches (re-matches #".*/#([1-9]*)"
+                                 (.-href (.-location js/window)))]
+    (last matches)))

 (defn to-int [s]
   (js/parseInt s))
@@ -81,19 +76,6 @@
            :on-success (d/set-html! (d/by-id "userBaskets") (render/user-baskets baskets))
            :on-error (js/alert (str "Error loading user baskets"))))

-(defn save-basket []
-    (srm/rpc
-     (api/save-basket (serialise-basket)) [response]
-     :on-success (do (js/alert (str "Basket saved! Id: " (:id response)))
-                     (basket-id (:id response)) (set-basket-saved!)
-                     (load-user-baskets))
-     :on-error (js/alert (str "Error saving basket"))))
-
-
-(def item-added (pubsub/publishize
-                 (fn [] {:item-name (d/value item-name-field)
-                         :qty (to-int (d/value item-qty-field))}) bus))
-
 (def item-deleted (pubsub/publishize (fn [e] {:item e}) bus))

 (def quantity-changed (pubsub/publishize
@@ -103,27 +85,6 @@
                           :item e}) bus))

 (def completed-item (pubsub/publishize (fn [e] {:item e}) bus))
-
-(defn on-enter [e f]
-  (when (= 13 (:keyCode e)) (event/prevent-default e) (f)))
-
-(defn on-plus [e f]
-  (when (= 43 (:charCode e)) (event/prevent-default e) (f)))
-
-(defn on-minus [e f]
-  (when (= 45 (:charCode e)) (event/prevent-default e) (f)))
-
-(event/listen! item-name-field :keypress
-               #(on-plus % (partial quantity-changed :inc false item-name-field)))
-
-(event/listen! item-name-field :keypress
-               #(on-minus % (partial quantity-changed :dec false item-name-field)))
-
-(event/listen! add-item-button :click #(item-added))
-(event/listen! item-name-field :keypress #(on-enter % item-added))
-(event/listen! item-qty-field :keypress #(on-enter % item-added))
-(event/listen! save-basket-button :click #(save-basket))
-

 (defn add-item-to-list [item]
   (when (and (< 0 (:qty item)) (not-empty (:item-name item)))
@@ -134,6 +95,57 @@
       (event/listen! (css/sel new-item "button[rel=decrement]") :click #(quantity-changed :dec true (event/target %)))
       (event/listen-once! (css/sel new-item "button[rel=complete]") :click #(completed-item (event/target %))))))

+(defn load-basket []
+  (when-let [basket-id (basket-id)]
+    (srm/rpc
+     (api/load-basket basket-id) [basket]
+     :on-success (do
+                   (d/destroy-children! items-list)
+                   (doseq [item (:items basket)]
+                     (add-item-to-list item)))
+     :on-error (js/alert (str "Error loading basket: " basket-id)))))
+
+
+(defn nav-handler [{:keys [token navigation?]}]
+  (when navigation?
+    (load-basket)))
+
+(def session-history (history/history nav-handler))
+
+(defn save-basket []
+    (srm/rpc
+     (api/save-basket (serialise-basket)) [response]
+     :on-success (do (js/alert (str "Basket saved! Id: " (:id response)))
+                     (history/set-token (str (:id response)))
+                     (set-basket-saved!)
+                     (load-user-baskets))
+     :on-error (js/alert (str "Error saving basket"))))
+
+
+(def item-added (pubsub/publishize
+                 (fn [] {:item-name (d/value item-name-field)
+                         :qty (to-int (d/value item-qty-field))}) bus))
+
+(defn on-enter [e f]
+  (when (= 13 (:keyCode e)) (event/prevent-default e) (f)))
+
+(defn on-plus [e f]
+  (when (= 43 (:charCode e)) (event/prevent-default e) (f)))
+
+(defn on-minus [e f]
+  (when (= 45 (:charCode e)) (event/prevent-default e) (f)))
+
+(event/listen! item-name-field :keypress
+               #(on-plus % (partial quantity-changed :inc false item-name-field)))
+
+(event/listen! item-name-field :keypress
+               #(on-minus % (partial quantity-changed :dec false item-name-field)))
+
+(event/listen! add-item-button :click #(item-added))
+(event/listen! item-name-field :keypress #(on-enter % item-added))
+(event/listen! item-qty-field :keypress #(on-enter % item-added))
+(event/listen! save-basket-button :click #(save-basket))
+
 (defn item-completed [{:keys [item]}]
   (d/add-class! item "btn-success")
   (d/append! completed-items-list (d/detach! (x/xpath item "../.."))))
@@ -165,14 +177,6 @@
 (defn log-to-console [o]
   (js/console.log "event: " o))

-(defn load-basket []
-  (when-let [basket-id (basket-id)]
-    (srm/rpc
-     (api/load-basket basket-id) [basket]
-     :on-success (doseq [item (:items basket)]
-                   (add-item-to-list item))
-     :on-error (js/alert (str "Error loading basket: " basket-id)))))
-
 (defn display-user-details []
   (srm/rpc
      (api/user-details) [details]


Fix a rather stupid bug

Fix a rather stupid bug

--- src/ecregister/avatars.clj
+++ src/ecregister/avatars.clj
@@ -40,8 +40,9 @@
                            (= BufferedImage/TYPE_INT_ARGB_PRE (.getType image))
                            (= BufferedImage/TYPE_4BYTE_ABGR_PRE (.getType image))
                            )))
+
 (defn ext-for [image]
-  (if has-alpha? "png" "jpg"))
+  (if (has-alpha? image) "png" "jpg"))

 (defn write-image [output-dir image-name image]
   "Writes an image to a file, returns a saved image file name"


Start using "error" instead of "warn" for bad things

--- src/re_frame/subs.cljs
+++ src/re_frame/subs.cljs
@@ -2,7 +2,7 @@
  (:require
    [reagent.ratom  :refer [make-reaction]]
    [re-frame.db    :refer [app-db]]
-   [re-frame.utils :refer [first-in-vector warn group groupEnd]]))
+   [re-frame.utils :refer [first-in-vector warn error]]))

 ;; maps from handler-id to handler-fn
@@ -29,6 +29,6 @@
   (let [key-v       (first-in-vector v)
         handler-fn  (get @key->fn key-v)]
     (if (nil? handler-fn)
-      (warn "re-frame: no subscription handler registered for: \"" key-v "\".  Returning a nil subscription.")
+      (error "re-frame: no subscription handler registered for: \"" key-v "\".  Returning a nil subscription.")
       (handler-fn app-db v))))


stable core

stable core

--- src/egyptian_gods/core.clj
+++ src/egyptian_gods/core.clj
@@ -5,8 +5,7 @@

 (defroutes app-routes
   (GET "/" [] (resp/file-response "index.html" {:root "resources/public"}))
-  (GET "/list-of-gods" [] (resp/file-response "index.html" {:root "resources/public"}))
-  (route/resources "/"))
+  (GET "/list-of-gods" [] (resp/file-response "index.html" {:root "resources/public"})))

 (defn -main []
   (run-server app-routes {:port 3000}))


add test for error reporting in defspec

add test for error reporting in defspec

I have some other changes that broke this, but the tests didn't
catch it. So here's a test that does.

--- src/test/clojure/clojure/test/check/clojure_test_test.cljc
+++ src/test/clojure/clojure/test/check/clojure_test_test.cljc
@@ -9,7 +9,11 @@

 (ns clojure.test.check.clojure-test-test
   (:require #?@(:cljs
-                [[cljs.test :as test :refer [test-var] :refer-macros [is]]
+                [[cljs.test
+                  :as test
+                  :include-macros true
+                  :refer [test-var]
+                  :refer-macros [is]]
                  [cljs.reader :refer [read-string]]])
             #?(:clj
                [clojure.test :as test :refer :all])
@@ -49,10 +53,25 @@

 (defspec this-is-supposed-to-fail 100 vector-elements-are-unique)

-(defn- capture-test-var
+(defspec this-throws-an-exception
+  (prop/for-all [x gen/nat]
+    (throw (ex-info "this property is terrible" {}))))
+
+(defn ^:private capture-test-var
+  "Returns [report-counters out-str]."
   [v]
-  (with-out-str #?(:clj  (binding [*test-out* *out*] (test-var v))
-                   :cljs (test-var v))))
+  #?(:clj
+     (binding [*report-counters* (ref *initial-report-counters*)]
+       (let [out (with-out-str (binding [*test-out* *out*] (test-var v)))]
+         [@*report-counters* out]))
+
+     :cljs
+     (let [restore-env    (test/get-current-env)
+           _              (test/set-env! (test/empty-env))
+           out            (with-out-str (test-var v))
+           env            (test/get-current-env)]
+       (test/set-env! restore-env)
+       [(:report-counters env) out])))

 (defn ^:private capture-clojure-test-reports
   [func]
@@ -64,17 +83,19 @@
 (defn test-ns-hook
   []
   (is (-> (capture-test-var #'default-trial-counts)
+          second
           read-string
           :num-tests
           (= ct/*default-test-count*)))

   (is (-> (capture-test-var #'trial-counts)
+          second
           read-string
           (select-keys [:test-var :result :num-tests])
           (= {:test-var "trial-counts", :result true, :num-tests 5000})))

   (binding [ct/*report-trials* true]
-    (let [output (capture-test-var #'trial-counts)]
+    (let [output (second (capture-test-var #'trial-counts))]
       (is (re-matches #?(:clj  (java.util.regex.Pattern/compile "(?s)\\.{5}.+")
                          :cljs #"\.{5}[\s\S]+")
                       output))))
@@ -92,29 +113,14 @@
           "calling with other :type keeps last-trial-report constant")
       (is (re-seq
            #"(Passing trial \d{3} / 1000 for .+\n)+"
-           (capture-test-var #'long-running-spec)))
+           (second
+            (capture-test-var #'long-running-spec))))
       (is (> @last-trial-report trial-report-1)
           "running the test makes last-trial-report to increment")))

   (let [[report-counters stdout]
-        #?(:clj
-           (binding [ct/*report-shrinking* true
-                     ;; need to keep the failure of this-is-supposed-to-fail from
-                     ;; affecting the clojure.test.check test run
-                     *report-counters* (ref *initial-report-counters*)]
-             (let [out (capture-test-var #'this-is-supposed-to-fail)]
-               [@*report-counters* out]))
-
-           :cljs
-           (binding [ct/*report-shrinking* true]
-             ;; need to keep the failure of this-is-supposed-to-fail from
-             ;; affecting the clojure.test.check test run
-             (let [restore-env    (test/get-current-env)
-                   _              (test/set-env! (test/empty-env))
-                   report-str     (capture-test-var #'this-is-supposed-to-fail)
-                   env            (test/get-current-env)]
-               (test/set-env! restore-env)
-               [(:report-counters env) report-str])))]
+        (binding [ct/*report-shrinking* true]
+          (capture-test-var #'this-is-supposed-to-fail))]
     (is (== 1 (:fail report-counters)))
     (is (re-seq
          #?(:clj
@@ -123,6 +129,12 @@
             :cljs
             #"Shrinking vector-elements-are-unique starting with parameters \[\[[\s\S]+")
          stdout)))
+
+  (test/testing "exceptions in properties are re-thrown to clojure.test"
+    (let [[report-counters stdout]
+          (capture-test-var #'this-throws-an-exception)]
+      (is (= report-counters {:test 1, :pass 0, :fail 0, :error 1}))
+      (is (re-find #"ERROR in \(this-throws-an-exception\)" stdout))))

   ;;
   ;; Test for TCHECK-118


solved

solved

--- src/4clojure/distinct.clj
+++ src/4clojure/distinct.clj
@@ -8,8 +8,29 @@
 ;; Write a function which removes the duplicates from a sequence. Order of the items must be maintained.

+;; (defn __ [coll]
+;;   (sort (vec (set coll))))
+
+
+;; (defn __ [coll]
+;;   (reduce #(if-not (some (zipmap [%2] (repeat true)) %1) (conj %1 %2) nil) [] coll))
+
+
+;; (defn __ [coll]
+;;   (reduce #(do
+;;              (println "%1 =" %1 "%2 =" %2)
+;;              (if (some (fn [e] (= %2 e)) %1) %1 (conj %1 %2))) [] coll))
+
 (defn __ [coll]
-  coll)
+  (reduce #(if (some (fn [e] (= %2 e)) %1) %1 (conj %1 %2)) [] coll))
+
+
+(if-not (boolean (some (fn [e] (= :a e)) [:a])) 'a)
+;; == (if-not (some (fn [e] (= :b e)) [:b]) 'a)
+(false? nil)
+(boolean nil)
+
+(conj [:a] :b)

 ;; use reduce to aggregate, some to find if element is in agregated coll
 ;; if not - conj, else: do nothing
@@ -20,4 +41,35 @@

 (= (__ '([2 4] [1 2] [1 3] [1 3])) '([2 4] [1 2] [1 3]))

-(= (__ (range 50)) (range 50))+(= (__ (range 50)) (range 50))
+
+
+;; 4clojure copy paste
+(fn [coll] (reduce #(if (some (fn [e] (= %2 e)) %1) %1 (conj %1 %2)) [] coll))
+;; my is one of the best
+
+;; _artem_uv's solution:
+(fn f
+   ([s] (f s []))
+   ([s r]
+    (if (empty? s)
+      r
+      (if (contains? (apply hash-map (interleave  r (repeat (count r) 0))) (first s))
+        (recur (rest s) r)
+        (recur (rest s) (into r ((comp vector first) s)))))))
+
+;; _pcl's solution:
+#(sort-by (fn [i] (.indexOf % i)) (map first (group-by identity %)))
+
+;; aceeca1's solution:
+(comp keys (partial sort-by (comp first first last)) (partial group-by last) (partial map-indexed list))
+
+;; adereth's solution:
+#(loop [seen #{}
+        remaining %
+        result []]
+   (if (empty? remaining) result
+     (recur (conj seen (first remaining))
+            (rest remaining)
+            (if (seen (first remaining)) result
+              (conj result (first remaining))))))


chat: auto capitalize first letter of each sentence

--- src/status_im/chat/views/message_input.cljs
+++ src/status_im/chat/views/message_input.cljs
@@ -47,6 +47,7 @@
                  :auto-focus             false
                  :blur-on-submit         true
                  :multiline              true
+                 :auto-capitalize        "sentences"
                  :on-content-size-change #(let [size (-> (.-nativeEvent %)
                                                          (.-contentSize)
                                                          (.-height))]


Fixed cryptokitties loading/ordering

Fixed cryptokitties loading/ordering

Signed-off-by: Andrey Shovkoplyas <b713972e59b8e606e23253c4a13e948139fea4d1@gmail.com>

--- src/status_im/wallet/collectibles/core.cljs
+++ src/status_im/wallet/collectibles/core.cljs
@@ -54,7 +54,7 @@
 (handlers/register-handler-fx
  :load-kitties
  (fn [{db :db} [_ ids]]
-   {:db db
+   {:db (update-in db [:collectibles] merge {ck (sorted-map-by >)})
     :http-get-n (mapv (fn [id]
                         {:url (str "https://api.cryptokitties.co/kitties/" id)
                          :success-event-creator (fn [o]
@@ -63,18 +63,19 @@
                                                   [:load-collectible-failure ck {id (http/parse-payload o)}])})
                       ids)}))

-;; TODO(andrey) Each HTTP call will return up to 100 kitties. Maybe we need to implement some kind of paging later
 (defmethod load-collectibles-fx ck [_ _ items-number address _]
-  {:http-get {:url                   (str "https://api.cryptokitties.co/kitties?offset=0&limit="
-                                          items-number
-                                          "&owner_wallet_address="
-                                          address
-                                          "&parents=false")
-              :success-event-creator (fn [o]
-                                       [:load-kitties (map :id (:kitties (http/parse-payload o)))])
-              :failure-event-creator (fn [o]
-                                       [:load-collectibles-failure (http/parse-payload o)])
-              :timeout-ms            10000}})
+  {:http-get-n (mapv (fn [offset]
+                       {:url (str "https://api.cryptokitties.co/kitties?limit=20&offset="
+                                  offset
+                                  "&owner_wallet_address="
+                                  address
+                                  "&parents=false")
+                        :success-event-creator (fn [o]
+                                                 [:load-kitties (map :id (:kitties (http/parse-payload o)))])
+                        :failure-event-creator (fn [o]
+                                                 [:load-collectibles-failure (http/parse-payload o)])
+                        :timeout-ms            10000})
+                     (range 0 items-number 20))}) ;; Cryptokitties API limited to 20 items per request

 ;; Crypto Strikers
 (def strikers :STRK)


add scaling layer constructor function

add scaling layer constructor function

--- src/cortex/layers.clj
+++ src/cortex/layers.clj
@@ -44,6 +44,11 @@
       (m/ensure-mutable (m/new-array :vectorz shape))
       (double probability)
       (m/ensure-mutable (m/new-array :vectorz shape)))))
+
+(defn scale
+  "Creates a scaling layer with the specified shape and multiplication factor"
+  [shape factor]
+  (cortex.impl.layers.Scale. (util/empty-array shape) (util/empty-array shape) (double factor)))

 (defn softmax
   "Creates a softmax module of the given shape."


add simple db actions. NOTE: i don't need use many try-catch, 'couze interface limit input variants

--- src/ombs/db.clj
+++ src/ombs/db.clj
@@ -19,10 +19,21 @@
                (sql/belongs-to events {:fk :eid})
                (sql/belongs-to users {:fk :uid}))

-(sql/select participants
-            (sql/fields ) ;don't select fields from participants
-            (sql/with events (sql/fields [:name :event]))
-            (sql/with users  (sql/fields [:name :user]))
-            (sql/group :user))
+(defn add-user [uname birthdate rate]
+  (sql/insert users (sql/values {:name uname :bdate birthdate :rate rate})))

+(defn add-event [name price & date]
+  (if-not (nil? date)
+    (sql/insert events (sql/values {:name name :price price :date date}))
+    (sql/insert events (sql/values {:name name :price price }))))

+(defn get-user [uname] (sql/select users (sql/where (= :name uname))))
+(defn get-event [ename] (sql/select events (sql/where (= :name ename))))
+(defn get-user-list   [] (sql/select users))
+(defn get-events-list [] (sql/select events))
+
+(defn get-user-events [uname]
+  (sql/select participants (sql/fields)
+              (sql/with users (sql/where (= :name uname)) (sql/fields))
+              (sql/with events)))
+


Minor fix on `slurp-bytes` function.

Minor fix on `slurp-bytes` function.

--- src/datoteka/core.clj
+++ src/datoteka/core.clj
@@ -334,11 +334,10 @@

 (defn slurp-bytes
   [input]
-  (with-open [input (io/input-stream input)
+  (with-open [input (io/input-stream (path input))
               output (java.io.ByteArrayOutputStream. (.available input))]
     (io/copy input output)
     (.toByteArray output)))
-

 ;; --- Implementation


Memoize clauses->rule

Memoize clauses->rule

--- src/aurora/language/denotation.cljs
+++ src/aurora/language/denotation.cljs
@@ -91,6 +91,8 @@
         RetractMany (+retract rule (->mapcat body (:expr clause)))
         nil))
     rule))
+
+(def clauses->rule (memoize clauses->rule))

 ;; TESTS


[#10077] Can't accept agreement on ENS registration when app translated into French

Signed-off-by: Andrey Shovkoplyas <b713972e59b8e606e23253c4a13e948139fea4d1@gmail.com>

--- src/status_im/ui/screens/ens/views.cljs
+++ src/status_im/ui/screens/ens/views.cljs
@@ -258,23 +258,22 @@
 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

 (defn- agreement [checked contract]
-  [react/view {:flex-direction :row
-               :margin-left 26 ;; 10 for checkbox + 16
-               :margin-right 16
-               :margin-top 14
-               :align-items :flex-start
+  [react/view {:flex-direction  :row
+               :margin-left     26                          ;; 10 for checkbox + 16
+               :margin-right    16
+               :margin-top      14
+               :align-items     :flex-start
                :justify-content :center}
    [checkbox/checkbox {:checked?        @checked
                        :style           {:padding 0}
                        :on-value-change #(reset! checked %)}]
-   [react/view {:style {:padding-left 10}}
-    [react/view {:style {:flex-direction :row}}
-     [react/text
-      (i18n/label :t/ens-agree-to)]
-     [link {:on-press #(re-frame/dispatch [:navigate-to :ens-terms {:contract contract}])}
-      (i18n/label :t/ens-terms-registration)]]
-    [react/text
-     (i18n/label :t/ens-understand)]]])
+   [react/nested-text {:style {:margin-left 10}}
+    (i18n/label :t/ens-agree-to)
+    [{:style    {:color colors/blue}
+      :on-press #(re-frame/dispatch [:navigate-to :ens-terms {:contract contract}])}
+     (i18n/label :t/ens-terms-registration)]
+    "\n"
+    (i18n/label :t/ens-understand)]])

 (defn- registration-bottom-bar
   [checked? amount-label]


Removing TODO we don't need to do now.

Removing TODO we don't need to do now.

--- system-int-test/src/cmr/system_int_test/utils/tag_util.clj
+++ system-int-test/src/cmr/system_int_test/utils/tag_util.clj
@@ -90,7 +90,6 @@
    (let [saved-tag (save-tag token tag)
          ;; Associate the tag with the collections using a query by concept id
          condition {:or (map #(hash-map :concept_id (:concept-id %)) associated-collections)}
-         ;; TODO change this to use the POST /associations endpoint
          response (associate-by-query token (:concept-id saved-tag) condition)]
      (assert (= 200 (:status response)) (pr-str condition))
      (assoc saved-tag :revision-id (:revision-id response)))))


add transformer

add transformer

--- src/graphql_clj/parser.clj
+++ src/graphql_clj/parser.clj
@@ -10,6 +10,13 @@
   [stmt]
   (let [parser (insta/parser (io/resource "graphql.bnf"))]
     (parser stmt)))
+
+(defn transformer
+  [parse-tree]
+  (insta/transform
+   {:Document (fn [document] [:Document document])
+    :Ignored (fn [& args] nil)}
+   parse-tree))

 (def statements
   [


Use shortcuts.

Use shortcuts.

Signed-off-by: Njagi Mwaniki <b6a4ba60ad861b9c9afb6daea7294be4be68f44c@urbanslug.com>

--- src/hatti/views/table.cljs
+++ src/hatti/views/table.cljs
@@ -333,10 +333,9 @@
         (html
          [:div.label-changer
           [:span.label-changer-label "Show:"]
-          [:div {:class "drop-hover" :id "header-display-dropdown"}
+          [:div#header-display-dropdown.drop-hover
            [:span (options name-or-label) [:i.fa.fa-angle-down]]
-           [:ul {:class "submenu no-dot"}
-            (render-options options owner colset!)]]])))))
+           [:ul.submenu.no-dot (render-options options owner colset!)]]])))))

 (defn delayed-search
   "Delayed search fires a query-event on event-chan if the value of the input


single articles need to be wrapped in coll

--- src/sdos_site/core.clj
+++ src/sdos_site/core.clj
@@ -50,7 +50,7 @@
         db (:db req)]
     (if-let [article (find-article db id)]
       (let [settings (get-settings req)]
-        (main-template settings article))
+        (main-template settings [article]))
       {:status 404 :headers {} :body "Sorry, article not found."})))

 (defroutes admin-routes


Add docstrings to the ->>asserts

Add docstrings to the ->>asserts

--- src/detritus/pred.clj
+++ src/detritus/pred.clj
@@ -1,6 +1,17 @@
 (ns detritus.pred)

-(defn ->ensure
+(defn ->assert
+  "(λ T → ((λ T) → Bool)) → T
+  (λ T → ((λ T) → Bool) → String) → T
+
+  Function of a value, a predicate and optionally a string. If the
+  predicate is not true of the value, this function will assert false
+  giving the optional string or \"->assert failed!\" as the failure
+  message. Otherwise returns the argument value.
+
+  Example:
+    (-> 1 inc inc dec
+       (->assert number? \"oh god the types\"))"
   ([v pred]
      (->ensure v pred "->assert failed!"))

@@ -9,7 +20,18 @@
          (assert false error))))

-(defn ->>ensure
+(defn ->>assert
+  "(λ ((λ T) → Bool) → T) → T
+  (λ ((λ T) → Bool) → T → String) → T
+
+  Function of a predicate, optionally a string and a value. If the
+  predicate is not true of the value, this function will assert false
+  giving the optional string or \"->assert failed!\" as the failure
+  message. Otherwise returns the argument value.
+
+  Example:
+    (->> 1 inc inc dec
+      (->>assert number? \"oh god the types\"))"
   ([pred v]
      (->>ensure pred "->>assert failed!" v))


Dumb bugs

Dumb bugs

--- src/detritus/pred.clj
+++ src/detritus/pred.clj
@@ -13,7 +13,7 @@
     (-> 1 inc inc dec
        (->assert number? \"oh god the types\"))"
   ([v pred]
-     (->ensure v pred "->assert failed!"))
+     (->assert v pred "->assert failed!"))

   ([v pred error]
      (if (pred v) v
@@ -33,7 +33,7 @@
     (->> 1 inc inc dec
       (->>assert number? \"oh god the types\"))"
   ([pred v]
-     (->>ensure pred "->>assert failed!" v))
+     (->>assert pred "->>assert failed!" v))

   ([pred error v]
      (if (pred v) v


Register om.next root when starting the application

--- src/discuss/core.cljs
+++ src/discuss/core.cljs
@@ -1,35 +1,25 @@
 (ns discuss.core
   "Entrypoint to this application. Loads all requirements, and bootstraps the application."
-  (:require [goog.dom :as gdom]
+  (:require [om.next :as om]
+            [goog.dom :as gdom]
             [discuss.communication.main :as com]
             [discuss.components.sidebar :as sidebar]
+            [discuss.parser :as parser]
             [discuss.components.bubbles]
             [discuss.config :as config]
             [discuss.references.integration]
             [discuss.utils.common :as lib]
             [discuss.components.tooltip :as tooltip]
-            [discuss.views :as views]
-            [om.core :as om]))
+            [discuss.views :as views]))

 (enable-console-print!)

 ;; Initialization
 (defn ^:export main []
   (lib/log (str "Loaded " config/project " " config/version))
+  (om/add-root! parser/reconciler views/MainView (gdom/getElement (lib/prefix-name "main")))
   (com/init-with-references!))
 (main)
-
-;; Register
-#_(defn register-view
-  "Register view in the current DOM."
-  [[div-name view]]
-  (when-let [div (gdom/getElement (lib/prefix-name div-name))]
-    (om/root view lib/app-state {:target div})
-    #_(nom/add-root! parser/reconciler view div)))
-
-#_(doall (map register-view [["main" views/main-view]
-                           ["sidebar" sidebar/view]
-                           ["tooltip" tooltip/view]]))

 (defn on-js-reload []
   ;; optionally touch your app-state to force rerendering depending on


Run tests on js-reload

Run tests on js-reload

--- src/discuss/core.cljs
+++ src/discuss/core.cljs
@@ -5,6 +5,7 @@
             [discuss.extensions]
             [discuss.integration]
             [discuss.lib :as lib]
+            [discuss.test :as test]
             [discuss.views :as views]))

 ;; Initialization
@@ -37,4 +38,5 @@
   ;; optionally touch your app-state to force rerendering depending on
   ;; your application
   ;; (swap! app-state update-in [:__figwheel_counter] inc)
+  (test/run)
   )


use thread-last in session filtering

use thread-last in session filtering

--- src/shale/sessions.clj
+++ src/shale/sessions.clj
@@ -208,12 +208,13 @@
     (with-car*
       (car/return
         (or
-          (and force-create (create-session
-                              (rename-keys requirements
-                                           {:reserve-after-create :reserved})))
-          (if-let [candidate (-> #(matches-requirements % requirements)
-                                 (filter (view-models nil))
-                                 first)]
+          (if force-create
+            (create-session
+              (rename-keys requirements
+                           {:reserve-after-create :reserved})))
+          (if-let [candidate (->> (view-models nil)
+                                  (filter #(matches-requirements % requirements))
+                                  first)]
             (if (or reserve-after-create current-url)
               (modify-session (get candidate :id)
                               (rename-keys


disable statsd for now

disable statsd for now

--- src/pc/init.clj
+++ src/pc/init.clj
@@ -30,7 +30,7 @@
   [#'pc.nrepl/init
    #'pc.profile/init
    #'pc.logging/init
-   #'pc.statsd/init
+   ;; #'pc.statsd/init
    #'pc.datomic/init
    #'pc.datomic.schema/init
    #'pc.datomic.migrations/init


Greatly improve MIDI clock sync stability.

--- src/afterglow/midi.clj
+++ src/afterglow/midi.clj
@@ -2,6 +2,7 @@
   "Handles MIDI communication, including syncing a show metronome to MIDI clock pulses."
   (:require [afterglow.rhythm :as rhythm]
             [amalloy.ring-buffer :refer [ring-buffer]]
+            [clojure.math.numeric-tower :as math]
             [overtone.at-at :refer [now]]
             [overtone.midi :as midi]
             [taoensso.timbre :as timbre])
@@ -10,7 +11,7 @@

 (def ^:private max-clock-intervals
   "How many MIDI clock pulses should be kept around for averaging?"
-  12)
+  30)

 (def ^:private max-tempo-taps
   "How many tempo taps should be kept around for averaging?"
@@ -360,18 +361,24 @@
   If it is a clock pulse, update the ring buffer in which we are
   collecting timestamps, and if we have enough, calculate a BPM value
   and update the associated metronome."
-  [msg buffer metronome traktor-info]
+  [msg timestamps means metronome traktor-info]
   (dosync
    (ensure traktor-info)
    (case (:status msg)
      :timing-clock (let [timestamp (now)]  ; Ordinary clock pulse
-                     (alter buffer conj timestamp)
-                     (when (> (count @buffer) 2)
-                       (let [passed (- timestamp (peek @buffer))
-                             intervals (dec (count @buffer))
+                     (alter timestamps conj timestamp)
+                     (when (> (count @timestamps) 1)
+                       (let [passed (- timestamp (peek @timestamps))
+                             intervals (dec (count @timestamps))
                              mean (/ passed intervals)]
-                         (rhythm/metro-bpm metronome (double (/ 60000 (* mean 24)))))))
-     (:start :stop) (ref-set buffer (ring-buffer max-clock-intervals))  ; Clock is being reset!
+                         (alter means conj mean)
+                         (when (= (count @means) max-clock-intervals)
+                           (let [mean-mean (/ (apply + @means) max-clock-intervals)
+                                 new-bpm (/ (math/round (double (/ 6000000 (* mean-mean 24)))) 100)]
+                             (when (>= (math/abs (- new-bpm (rhythm/metro-bpm metronome))) 0.1)
+                               (rhythm/metro-bpm metronome new-bpm)))))))
+     (:start :stop) (do (ref-set timestamps (ring-buffer max-clock-intervals)) ; Clock is being reset
+                        (ref-set means (ring-buffer max-clock-intervals)))
      :control-change (when (and (some? @traktor-info) (< (:note msg) 5))  ; Traktor beat phase update
                        (when (zero? (:note msg))  ; Switching the current master deck
                          (alter traktor-info assoc :master (:velocity msg)))
@@ -402,18 +409,19 @@

 ;; A simple object which holds the values necessary to establish a link between an external
 ;; source of MIDI clock messages and the metronome driving the timing of a light show.
-(defrecord ClockSync [metronome midi-clock-source buffer traktor-info]
+(defrecord ClockSync [metronome midi-clock-source timestamps means traktor-info]
     IClockSync
     (sync-start [this]
-      (add-synced-metronome midi-clock-source metronome (fn [msg] (sync-handler msg buffer metronome traktor-info))))
+      (add-synced-metronome midi-clock-source metronome
+                            (fn [msg] (sync-handler msg timestamps means metronome traktor-info))))
     (sync-stop [this]
       (remove-synced-metronome midi-clock-source metronome))
     (sync-status [this]
       (dosync
-       (ensure buffer)
+       (ensure timestamps)
        (ensure traktor-info)
-       (let [n (count @buffer)
-             lag (when (pos? n) (- (now) (last @buffer)))
+       (let [n (count @timestamps)
+             lag (when (pos? n) (- (now) (last @timestamps)))
              current (and (= n max-clock-intervals)
                           (< lag 100))
              traktor-current (traktor-beat-phase-current @traktor-info)]
@@ -422,7 +430,7 @@
           :level (if traktor-current :beat :bpm)
           :source midi-clock-source
           :status (cond
-                    (empty? @buffer) "Inactive, no clock pulses have been received."
+                    (empty? @timestamps) "Inactive, no clock pulses have been received."
                     (not current) (str "Stalled? " (if (< n max-clock-intervals)
                                                      (str "Clock pulse buffer has " n " of "
                                                           max-clock-intervals " pulses in it.")
@@ -489,6 +497,7 @@

        1 (fn [^afterglow.rhythm.Metronome metronome]
            (let [sync-handler (ClockSync. metronome (first result) (ref (ring-buffer max-clock-intervals))
+                                          (ref (ring-buffer max-clock-intervals))
                                           (ref {:master (get-in @clock-sources [(first result) :master])}))]
              (sync-start sync-handler)
              sync-handler))


Return nil for a spec with no actions.

Return nil for a spec with no actions.

--- src/circle/backend/build/config.clj
+++ src/circle/backend/build/config.clj
@@ -98,10 +98,11 @@
         extra (-> spec :extra)
         extra (-> extra set-spec (set-type :post-test))

-        actions (concat pre-setup setup test extra)
-        actions (template/apply-template :build actions)]
-    {:job-name :build
-     :actions actions}))
+        actions (concat pre-setup setup test extra)]
+    (if (= actions [])
+      nil
+      {:job-name :build
+       :actions  (template/apply-template :build actions)})))

 (defn validate-job [job]
   (validate! [(require-keys [:template])] job))


making tests pass

making tests pass

--- test/restaurant_inspections_api/db_test.clj
+++ test/restaurant_inspections_api/db_test.clj
@@ -13,4 +13,4 @@

 (deftest build-select-inspections-query-test
   (testing "Given a params-map with all params present, returns a complete SQL query"
-    (is (= (build-select-inspections-query params-map) "SELECT i.inspection_visit_id, i.inspection_number, i.visit_number, i.inspection_class, i.inspection_type, i.inspection_disposition, i.inspection_date, i.total_violations, i.high_priority_violations, i.intermediate_violations, i.basic_violations, i.county_number, i.license_number, r.county_number, r.license_type_code, r.license_number, r.business_name, r.location_address, r.location_city, r.location_zipcode, r.location_latitude, r.location_longitude, c.county_name, c.district FROM inspections AS i INNER JOIN counties AS c ON c.county_number = i.county_number INNER JOIN restaurants AS r ON r.county_number = i.county_number AND r.license_number = i.license_number WHERE i.inspection_date BETWEEN \"2013-02-02\" AND \"2017-02-01\" AND r.location_zipcode IN (\"32345\",\"33136\") AND r.business_name LIKE \"Johnys Pizza\" AND c.district = \"D3\" AND i.county_number = 19 LIMIT 20 OFFSET 1;"))))
+    (is (= (build-select-inspections-query params-map) "SELECT i.inspection_visit_id, i.inspection_number, i.visit_number, i.inspection_class, i.inspection_type, i.inspection_disposition, i.inspection_date, i.total_violations, i.high_priority_violations, i.intermediate_violations, i.basic_violations, i.county_number, i.license_number, r.county_number, r.license_type_code, r.license_number, r.business_name, r.location_address, r.location_city, r.location_zipcode, r.location_latitude, r.location_longitude, c.county_name, c.district FROM inspections AS i INNER JOIN counties AS c ON c.county_number = i.county_number INNER JOIN restaurants AS r ON r.county_number = i.county_number AND r.license_number = i.license_number WHERE i.inspection_date BETWEEN \"2013-02-02\" AND \"2017-02-01\" AND r.location_zipcode IN (\"32345\" \"33136\") AND r.business_name LIKE \"Johnys Pizza\" AND c.district = \"D3\" AND i.county_number = 19 LIMIT 20 OFFSET 1;"))))


Fix asset fingerprinting

Fix asset fingerprinting

--- src/clj/clojuredocs/site/common.clj
+++ src/clj/clojuredocs/site/common.clj
@@ -55,23 +55,27 @@
        [:div.col-md-10.col-md-offset-1
         [:div.ac-results-widget]]])]])

+(defn md5-path [path]
+  (-> path slurp util/md5))
+
 (def clojuredocs-script
   [:script {:src (str "/cljs/clojuredocs.js?"
-                      (util/md5 "resources/public/cljs/clojuredocs.js"))}])
+                      (md5-path "resources/public/cljs/clojuredocs.js"))}])

 (def app-link
   [:link {:rel :stylesheet
           :href (str "/css/app.css?"
-                     (util/md5 "resources/public/css/app.css"))}])
+                     (md5-path "resources/public/css/app.css"))}])

 (def bootstrap-link
   [:link {:rel :stylesheet
           :href (str "/css/bootstrap.min.css?"
-                     (util/md5 "resources/public/css/bootstrap.min.css"))}])
+                     (md5-path "resources/public/css/bootstrap.min.css"))}])

 (def font-awesome-link
-  [:link {:rel :stylesheet :href (str "/css/font-awesome.min.css?"
-                                      (util/md5 "resources/public/css/font-awesome.min.css"))}])
+  [:link {:rel :stylesheet
+          :href (str "/css/font-awesome.min.css?"
+                     (md5-path "resources/public/css/font-awesome.min.css"))}])

 (defn $main [{:keys [content title body-class user page-data] :as opts}]
   [:html5


Only take first period

Only take first period

--- src/clj/forma/hadoop/jobs/forma.clj
+++ src/clj/forma/hadoop/jobs/forma.clj
@@ -160,12 +160,12 @@
   (<- [?s-res ?mod-h ?mod-v ?s ?l ?prob-series]
         (beta-src ?s-res ?eco ?beta)
         (dynamic-src ?s-res ?pd ?mod-h ?mod-v ?s ?l ?val ?neighbor-val)
-        ;; (= ?pd 693)
         (static-src ?s-res ?mod-h ?mod-v ?s ?l _ _ ?eco _)
         ;; (apply-betas [?beta] ?eco ?val ?neighbor-val :> ?prob)
         (log/logistic-prob-wrap ?beta ?val ?neighbor-val :> ?prob)
         (log/mk-timeseries ?pd ?prob :> ?prob-series)
-        (:distinct false)))
+        (:distinct false)
+        (= ?pd 693)))

 (defn prep-for-betas
   [dynamic-src static-src]


Remove unused namespace import

Remove unused namespace import

--- src/clj/lambdacd/execution/core.clj
+++ src/clj/lambdacd/execution/core.clj
@@ -5,8 +5,7 @@
             [lambdacd.execution.internal.pipeline :as pipeline]
             [lambdacd.execution.internal.execute-step :as execute-step]
             [lambdacd.execution.internal.execute-steps :as execute-steps]
-            [lambdacd.execution.internal.kill :as kill]
-            [lambdacd.execution.internal.retrigger :as retrigger]))
+            [lambdacd.execution.internal.kill :as kill]))

 (defn run-pipeline
   "Execute a complete run of the pipeline.


Rename play-from to start-at

Rename play-from to start-at

--- src/cljs/asciinema_player/core.cljs
+++ src/cljs/asciinema_player/core.cljs
@@ -21,7 +21,7 @@
             :font-size font-size
             :theme theme
             :cursor {:on true}
-            :play-from 0
+            :start-at 0
             :current-time 0
             :show-hud false}
            (select-keys options [:auto-play :loop :title :author :author-url :author-img-url]))))
@@ -118,9 +118,9 @@
   Returns function which stops the playback and returns time of the playback."
   [state dispatch]
   (let [start (js/Date.)
-        play-from (:play-from state)
+        start-at (:start-at state)
         speed (:speed state)
-        frames (-> (:frames state) (next-frames play-from) (frames-at-speed speed))
+        frames (-> (:frames state) (next-frames start-at) (frames-at-speed speed))
         diff-chan (coll->chan frames (partial merge-with merge) {})
         timer-chan (coll->chan (repeat [0.3 true]))
         stop-playback-chan (chan)
@@ -132,7 +132,7 @@
       (loop [cursor-blink-chan (make-cursor-blink-chan)]
         (let [[v c] (alts! [diff-chan timer-chan cursor-blink-chan stop-playback-chan])]
           (condp = c
-            timer-chan (let [t (+ play-from (elapsed-time))]
+            timer-chan (let [t (+ start-at (elapsed-time))]
                          (dispatch [:update-state assoc :current-time t])
                          (recur cursor-blink-chan))
             cursor-blink-chan (do
@@ -148,7 +148,7 @@
             stop-playback-chan nil))) ; do nothing, break the loop
       (dispatch [:update-state reset-blink]))
     (-> state
-        (apply-diff (prev-diff (:frames state) play-from))
+        (apply-diff (prev-diff (:frames state) start-at))
         (assoc :stop stop-fn))))

 (defn stop-playback
@@ -157,7 +157,7 @@
   (let [t ((:stop state))]
     (-> state
         (dissoc :stop)
-        (update-in [:play-from] + t))))
+        (update-in [:start-at] + t))))

 (defn fetch-frames
   "Fetches frames, setting :loading to true at the start,
@@ -195,7 +195,7 @@
     (when playing?
       ((:stop state)))
     (let [new-state (-> state
-                        (assoc :current-time new-time :play-from new-time)
+                        (assoc :current-time new-time :start-at new-time)
                         (apply-diff diff))]
       (if playing?
         (start-playback new-state dispatch)
@@ -221,7 +221,7 @@
     (dispatch [:toggle-play]))
   (-> state
       (dissoc :stop)
-      (assoc :play-from 0)
+      (assoc :start-at 0)
       (assoc :current-time (:duration state))))

 (defn speed-up [speed]
@@ -236,7 +236,7 @@
   (if-let [stop (:stop state)]
     (let [t (stop)]
       (-> state
-          (update-in [:play-from] + t)
+          (update-in [:start-at] + t)
           (update-in [:speed] change-fn)
           (start-playback dispatch)))
     (update-in state [:speed] change-fn)))


fix build API bug when requiring a macros namespace of the same name

--- src/cljs/bundled/lumo/compiler.cljs
+++ src/cljs/bundled/lumo/compiler.cljs
@@ -177,21 +177,25 @@
         source
         (:ns opts)
         (merge opts {:verbose false
-                     :load (fn [{dep :name :as m} cb]
-                             (if (or (not-empty (get-in cenv [::ana/namespaces dep :defs]))
-                                   (contains? (:js-dependency-index cenv) (name dep))
-                                   (ana/node-module-dep? dep)
-                                   (ana/js-module-exists? (name dep))
-                                   (deps/find-classpath-lib dep))
-                               (cb {:lang :js})
-                               (if-let [{:keys [source-file]} (first
-                                                                (filter
-                                                                  #(symbol-identical? dep (:ns %))
-                                                                  (:sources cenv)))]
-                                 (cb {:lang :clj
-                                      :file (util/path source-file)
-                                      :source (slurp source-file)})
-                                 (original-load m cb))))})
+                     :load (fn [{:keys [macros]
+                                 dep :name :as m} cb]
+                             (let [dep (if macros
+                                         (symbol (str dep "$macros"))
+                                         dep)]
+                               (if (or (not-empty (get-in cenv [::ana/namespaces dep :defs]))
+                                     (contains? (:js-dependency-index cenv) (name dep))
+                                     (ana/node-module-dep? dep)
+                                     (ana/js-module-exists? (name dep))
+                                     (deps/find-classpath-lib dep))
+                                 (cb {:lang :js})
+                                 (if-let [{:keys [source-file]} (first
+                                                                  (filter
+                                                                    #(symbol-identical? dep (:ns %))
+                                                                    (:sources cenv)))]
+                                   (cb {:lang :clj
+                                        :file (util/path source-file)
+                                        :source (slurp source-file)})
+                                   (original-load m cb)))))})
         (fn [{:keys [value error] :as m}]
           (if error
             (cb {:error error})


Setting up custom port, host and api-key

--- src/cljs/catsocket_client/core.cljs
+++ src/cljs/catsocket_client/core.cljs
@@ -42,21 +42,25 @@
   (swap! cat assoc :connected? true)
   (send cat "identify" {}))

-(defn init []
-  (let [url "ws://localhost:9000/api/ws"
-        s (js/WebSocket. url)
-        cat (atom {:socket s
-                   :connected? false
-                   :identified? false
-                   :queue []
-                   :sent-messages {}})]
-    (set! (.-onopen s ) #(on-open cat %))
-    (set! (.-onmessage s ) #(on-message cat (.parse js/JSON (.-data %))))
+(defn init
+  ([api-key] (init api-key {}))

-    cat))
+  ([api-key {:keys [host port] :or {host "localhost", port 9000}}]
+   (let [url (str "ws://" host ":" port "/api/ws")
+         socket (js/WebSocket. url)
+         cat (atom {:socket socket
+                    :api-key api-key
+                    :connected? false
+                    :identified? false
+                    :queue []
+                    :sent-messages {}})]
+     (set! (.-onopen socket) #(on-open cat %))
+     (set! (.-onmessage socket) #(on-message cat (.parse js/JSON (.-data %))))
+
+     cat)))

 (defn send [cat action data]
-  (let [params {:api_key "foo"
+  (let [params {:api_key (:api-key @cat)
                 :user (user)
                 :action action
                 :data data
@@ -105,7 +109,7 @@
 ;;

 (defn main []
-  (let [cat (init)]
+  (let [cat (init "foo-key")]
     (join cat "test")
     (broadcast cat "test" "hello!"))


Now common requires clojure.string for join.

--- src/cljs/cljs_bootstrap/common.cljs
+++ src/cljs/cljs_bootstrap/common.cljs
@@ -1,4 +1,5 @@
-(ns cljs-bootstrap.common)
+(ns cljs-bootstrap.common
+  (:require [clojure.string :as string]))

 (defn echo-callback
   "Echoes the input success and result, returning [success,
@@ -39,7 +40,7 @@
     (if-let [next-err (.-cause e)]
       (recur next-err (conj msgs (.-message next-err)))
       (if (seq msgs)
-        (clojure.string/join " - " msgs)
+        (string/join " - " msgs)
         ""))))

 (defn error-keyword-not-supported


fixes military>standard time display edge case

--- src/cljs/early_vote_site/utils.cljs
+++ src/cljs/early_vote_site/utils.cljs
@@ -35,6 +35,7 @@
    (cond
      (> hour 12) (str (mod hour 12) rest " PM")
      (= hour 12) (str all " PM")
+     (str/starts-with? all "00") (str "12" (subs all 2 5) " AM")
      (str/starts-with? all "0") (str (subs all 1 5) " AM")
      :else (str all " AM"))))


Add 'town' to city label.

Add 'town' to city label.

--- src/cljs/kixi/hecuba/bootstrap.cljs
+++ src/cljs/kixi/hecuba/bootstrap.cljs
@@ -192,7 +192,7 @@
              :type "text"
              :id "address_street_two"}]]
    [:div.form-group
-    [:label.control-label {:for "address_city"} "City"]
+    [:label.control-label {:for "address_city"} "City / Town"]
     [:input {:value (om/get-state owner (conj keys :address_city))
              :on-change #(handle-change owner (conj keys :address_city)  %1)
              :class "form-control"


Prevent call resolver with break values

Prevent call resolver with break values

--- src/com/wsscode/pathom/connect.cljc
+++ src/com/wsscode/pathom/connect.cljc
@@ -403,22 +403,24 @@
 (defn call-resolver [{::keys [pool-chan]
                       :as    env}
                      entity]
-  (if pool-chan
-    (let [out (async/promise-chan)]
-      (go
-        (let [tid (pt/trace-enter env {::pt/event   ::schedule-resolver
-                                       ::pt/label   (-> env ::resolver-data ::sym)
-                                       :key         (-> env :ast :key)
-                                       ::sym        (-> env ::resolver-data ::sym)
-                                       ::input-data entity})]
-          (>! pool-chan {:out out
-                         :f   #(do
-                                 (pt/trace-leave env tid {::pt/event ::schedule-resolver})
-                                 (try
-                                   (call-resolver* env entity)
-                                   (catch #?(:clj Throwable :cljs :default) e e)))})))
-      out)
-    (call-resolver* env entity)))
+  (if (seq (filter #(contains? p/break-values (second %)) entity))
+    (throw (ex-info "Insufficient resolver input" {:entity entity}))
+    (if pool-chan
+      (let [out (async/promise-chan)]
+        (go
+          (let [tid (pt/trace-enter env {::pt/event   ::schedule-resolver
+                                         ::pt/label   (-> env ::resolver-data ::sym)
+                                         :key         (-> env :ast :key)
+                                         ::sym        (-> env ::resolver-data ::sym)
+                                         ::input-data entity})]
+            (>! pool-chan {:out out
+                           :f   #(do
+                                   (pt/trace-leave env tid {::pt/event ::schedule-resolver})
+                                   (try
+                                     (call-resolver* env entity)
+                                     (catch #?(:clj Throwable :cljs :default) e e)))})))
+        out)
+      (call-resolver* env entity))))

 (defn- entity-select-keys [env entity input]
   (let [entity (p/maybe-atom entity)]


Fix typo in keyword value

Fix typo in keyword value

--- src/env_logger/db.clj
+++ src/env_logger/db.clj
@@ -92,7 +92,7 @@
 (defn get-tb-image
   "Returns the name of the latest FMI Testbed image."
   [db-con]
-  (let [tb-image-name (:tb-mage-name
+  (let [tb-image-name (:tb-image-name
                        (jdbc/execute-one! db-con
                                           (sql/format
                                            {:select [:tb_image_name]


Cleaing up core

Cleaing up core

--- src/mcc/core.clj
+++ src/mcc/core.clj
@@ -12,35 +12,35 @@
    [com.rpl.specter :refer :all]
    [datascript.core :as d]))

-(def testtest (slurp  "dev-resources/sample.c"))
+(defn string->db [s]
+  (let [chunked (-> s into-bundles into-chunks)]))
+(def sample (slurp  "dev-resources/sample.c"))

-(def bundled (into-bundles testtest))
-(def tags (map :type bundled))
-(def test-chunks (into-chunks bundled))
-(map join (cart (map produce-text test-chunks)))
-
+(def bundled (into-bundles sample))
+(def chunked (into-chunks bundled))
+(map join (cart (map produce-text chunked)))

 (s/explain :mcc/bundles bundled)
 (s/conform :mcc/bundles bundled)

 (s/explain (s/* :mcc/chunked) bundled)
 (s/conform (s/* :mcc/chunked) bundled)
-(apply diff (map clean-parse (produce-strings test-chunks)))

-(def testparse
- (clean-parse (first (produce-strings test-chunks))))
-(def metad (enlive-output->datascript-datums testparse))
+(apply diff (map clean-parse (produce-strings chunked)))
+
+(def parsed
+ (clean-parse (first (produce-strings chunked))))
+
+(def datums-sample (enlive-output->datascript-datums parsed))
 (def conn (d/create-conn schema))
-(d/transact! conn [metad])
-
-(def printf
- (d/q '[:find  ?prize
-        :where [?value :value "printf"]
-               [?symbol :content ?value]
-               [?fun-call :content ?symbol]
-               [?fun-call :content ?args]
-               [?args :order 1]
-               [?args :content ?temp1]
-               [?temp1 :content ?temp2]
-               [?temp2 :value ?prize]]
-      @conn))
+(d/transact! conn [datums-sample])
+(d/q '[:find  ?prize
+       :where [?value :value "printf"]
+              [?symbol :content ?value]
+              [?fun-call :content ?symbol]
+              [?fun-call :content ?args]
+              [?args :order 1]
+              [?args :content ?temp1]
+              [?temp1 :content ?temp2]
+              [?temp2 :value ?prize]]
+     @conn)


Documenting «abort» for the exploration repl

Signed-off-by: Daniel Borchmann <25857343a15bf1edafebc2912e82ecf775c585c1@mailbox.tu-dresden.de>

--- src/conexp/fca/exploration/repl.clj
+++ src/conexp/fca/exploration/repl.clj
@@ -211,7 +211,8 @@
 (define-repl-fn help
   "Prints help."
   (let [commands (suitable-repl-commands "")]
-    (println "Any command can be abbreviated, as long as this is unambigious.")
+    (println "Type «abort» to abort exploration.")
+    (println "Any other command can be abbreviated, as long as this is unambigious.")
     (doseq [cmd commands]
       (println (str "  " cmd))
       (println (str "    -> " (help-repl-command cmd))))


checked that have step does not normalize first (typing doesn't require it)

--- src/latte/kernel/proof.clj
+++ src/latte/kernel/proof.clj
@@ -195,7 +195,7 @@
     ;; check synthetized term
     (if (= status :ko)
       [:ko {:msg "Cannot perform have step: incorrect term." :have-name name :from term}]
-      (let [term (n/special-normalize def-env ctx term)
+      (let [term (n/special-normalize def-env ctx term) ;; <-- need to remove the specials ASAP
             term' term ;; XXX: full normalization should not be needed ... (n/normalize def-env ctx term)
             [status have-type] (if (and (symbol? have-type)
                                         (= (clojure.core/name have-type) "_"))


Minor bugfix on push based publisher.

Minor bugfix on push based publisher.

--- src/futura/stream.clj
+++ src/futura/stream.clj
@@ -179,7 +179,7 @@

   nil
   (publisher* [source xform]
-    (publisher* 1 xform))
+    (publisher* nil xform))

   Publisher
   (publisher* [source xform]


Bug fixes on promise coersion and proxying.

--- src/futura/stream.clj
+++ src/futura/stream.clj
@@ -37,18 +37,17 @@

 (defn- promise->subscription
   [subscriber source]
-  (let [canceled (atomic/boolean false)]
+  (let [canceled (atomic/boolean false)
+        completed (atomic/boolean false)]
     (reify Subscription
       (^void request [_ ^long n]
-        (-> source
-            (p/then (fn [v]
-                      (when-not @canceled
-                        (.onNext subscriber v)
-                        (.onComplete subscriber))))
-            (p/catch (fn [e]
-                       (when-not @canceled
-                         (.onError subscriber e))))))
+        (when (atomic/compare-and-set! completed false true)
+          (p/then source (fn [v]
+                           (when-not @canceled
+                             (.onNext subscriber v)
+                             (.onComplete subscriber))))))
       (^void cancel [_]
+        (atomic/set! completed true)
         (atomic/set! canceled true)))))

 (defn- subscribe-once
@@ -75,20 +74,25 @@
                     ([s] s)
                     ([s v] (.onNext s v)))
         rf (xform transform)
+        completed (atomic/boolean false)
         subscription (atomic/ref nil)]
     (reify Subscriber
       (onSubscribe [_ s]
         (atomic/set! subscription s)
         (.onSubscribe subscriber s))
       (onNext [_ v]
-        (let [res (rf subscriber v)]
-          (when (reduced? res)
-            (.cancel @subscription)
-            (.onComplete (rf subscriber)))))
+        (when-not @completed
+          (let [res (rf subscriber v)]
+            (when (reduced? res)
+              (.cancel @subscription)
+              (.onComplete (rf subscriber))
+              (atomic/set! completed true)))))
       (onError [_ e]
         (.onError (rf subscriber) e))
       (onComplete [_]
-        (.onComplete (rf subscriber))))))
+        (when-not @completed
+          (.onComplete (rf subscriber))
+          (atomic/set! completed true))))))

 (definterface IPushStream
   (push [_ v] "Push a value into stream.")


Use namespace qualified put! on stream ns.

--- src/futura/stream.clj
+++ src/futura/stream.clj
@@ -30,7 +30,7 @@
       (reify Subscription
         (^void request [_ ^long n]
           (when-not @completed
-            (put! requests n)))
+            (async/put! requests n)))
         (^void cancel [_]
           (atomic/set! completed true)
           (async/close! requests))))))


Do nothing when there are no files

Do nothing when there are no files

The view can change by moving from a PR to a non-PR page, but that
doesn't mean that Gitique should run. This stops errors appearing in the
JS console.

--- src/gitique/core.cljs
+++ src/gitique/core.cljs
@@ -38,10 +38,11 @@

 (add-watch state :files-change (fn [_ _ old new]
                                  (let [new-files (:files new)]
-                                   (when (not= (:files old) new-files) (update-dom! new-files)))))
+                                   (when (and (not= (:files old) new-files) (not-empty new-files))
+                                     (update-dom! new-files)))))

 (add-watch state :view-change (fn [_ _ old new]
-                                (when (not= (:view old) (:view new))
+                                (when (and (not= (:view old) (:view new)) (not-empty (:files new)))
                                   (update-dom! (:files new)))))

 (defn- is? [type] (fn [item] (= (:type item) type)))


Snapshot only when we're quiescent.

Snapshot only when we're quiescent.

--- src/cbfg/world/t1.cljs
+++ src/cbfg/world/t1.cljs
@@ -38,8 +38,10 @@
 (defn prog-event [world label prog-frame-fn]
   (let [prog-next (swap! prog-curr prog-frame-fn)
         ts (count @prog-history)]
-    (swap! prog-history #(conj % [ts label prog-next]))
-    (swap! prog-ss #(assoc % ts (ago-snapshot (actx-agw world))))))
+    ; Only snapshot when we're quiescent.
+    (when (<= (.-length cljs.core.async.impl.dispatch/tasks) 0)
+      (swap! prog-history #(conj % [ts label prog-next]))
+      (swap! prog-ss #(assoc % ts (ago-snapshot (actx-agw world)))))))

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

@@ -57,8 +59,8 @@
     (ago-restore (actx-agw (:world @prog-base)) ago-ss)
     (swap! prog-history #(vec (take (+ ts 1) %)))
     ; TODO: This prog-frame deref is strange, as it turned into a
-    ; om.core/MapCursor somehow during the event handler rather
-    ; an the expected prog-frame dict.
+    ; om.core/MapCursor somehow during the event handler rather than
+    ; an expected prog-frame dict.
     (reset! prog-curr @prog-frame)
     (cbfg.world.base/render-client-hist (:reqs @prog-curr))))

@@ -146,7 +148,8 @@
                                  event-ch step-ch event-run-ch)
         (cbfg.vis/process-render el-prefix world event-run-ch
                                  (fn [vis-next]
-                                   (println :on-delayed-event-cb @last-id)))
+                                   ; (println :on-delayed-event-cb @last-id)
+                                   ))
         (make-net world
                   (:net-listen-ch @prog-base)
                   (:net-connect-ch @prog-base))


bugfix

bugfix

--- src/blog_clj/webhooks.clj
+++ src/blog_clj/webhooks.clj
@@ -22,7 +22,7 @@
                                          (apply union
                                                 (map #(set (change-type %))
                                                      commits)))))
-        [added removed modified] (map get-changed-files [:added :removed :modified])
+        [added removed modified] (map #(set (get-changed-files %)) [:added :removed :modified])
         real-added (difference added removed)
         real-removed (difference removed added)
         real-modified (difference modified added removed)]


Remove unused generate-iv multimethod.

Remove unused generate-iv multimethod.

--- src/buddy/core/crypto.clj
+++ src/buddy/core/crypto.clj
@@ -351,15 +351,6 @@
          (throw+ {:type :validation :cause :authtag :message message} e))))
     output))

-;; TODO: maybe use hierarchies for remove repetitions
-(defmulti generate-iv identity)
-(defmethod generate-iv :aes128-cbc-hmac-sha256 [_] (nonce/random-bytes 16))
-(defmethod generate-iv :aes192-cbc-hmac-sha384 [_] (nonce/random-bytes 16))
-(defmethod generate-iv :aes256-cbc-hmac-sha512 [_] (nonce/random-bytes 16))
-(defmethod generate-iv :aes128-gcm [_] (nonce/random-bytes 12))
-(defmethod generate-iv :aes192-gcm [_] (nonce/random-bytes 12))
-(defmethod generate-iv :aes256-gcm [_] (nonce/random-bytes 12))
-
 (defn- aad->bytes
   [aad]
   (let [length (* (count aad) 8)


add support to close items

add support to close items

for that we add a checkbox that is only enabled if the item is not
closed and on click we call the tudu.item/close mutator with the id we
want to close and we tell transact that :tudu/items will change.

we define the mutator tudu.item/close to assoc the field :state of the
todo item for the given id to :close

--- src/tudu/ui.cljs
+++ src/tudu/ui.cljs
@@ -10,6 +10,9 @@
                      {:id 2 :status :open :title "Buy Food"}
                      {:id 3 :status :open :title "Implement next Step"}]})

+(defn close-item [component id]
+  (om/transact! component `[(tudu.item/close {:id ~id}) :tudu/items]))
+
 (defui TodoItemUI
   static om/IQuery
   (query [this]
@@ -20,8 +23,13 @@
   Object
   (render [this]
           (let [{:keys [id status title]} (om/props this)
+                closed? (= status :close)
                 class-name (str "todo-list-item-title status-" (name status))]
             (dom/div #js {:className "todo-list-item" :key (str "todo-item-" id)}
+                     (dom/input #js {:type "checkbox" :disabled closed?
+                                     :checked closed?
+                                     :onClick #(close-item this id)})
+
                      (dom/span #js {:className class-name} title)))))

 (def todo-item-ui (om/factory TodoItemUI {:keyfn :id}))
@@ -61,12 +69,16 @@
   (let [st @state]
     (into [] (map #(get-in st %)) (get st :tudu/items))))

-
 (defmethod read :tudu/items [{:keys [state]} key params]
   {:value (get-items state)})

-(def reconciler (om/reconciler
-                  {:state initial-state
-                   :parser (om/parser {:read read :mutate mutate})}))
+(defmethod mutate 'tudu.item/close [{:keys [state]} _ {:keys [id]}]
+  {:action (fn []
+             (swap! state
+                    #(assoc-in % [:tudu.items/by-id id :status] :close)))})
+
+(defonce reconciler (om/reconciler
+                      {:state initial-state
+                       :parser (om/parser {:read read :mutate mutate})}))

 (om/add-root! reconciler UI (gdom/getElement "main-app-area"))


Add big hack to generate a dynamic var, load-string compiles the generated ns successfully

--- src/googlica/core.clj
+++ src/googlica/core.clj
@@ -38,8 +38,8 @@
 (defn generate-global-vars
   "Generates global variables that are used throughout the generated namespace"
   [root-url service-path]
-  `[(def ~'base-url ~(str root-url service-path))
-    (def (~'vary-meta ~'*api-key* ~'assoc :dynamic true) nil)
+  `[(def \^ :dynamic ~'*api-key* nil)
+    (def ~'base-url ~(str root-url service-path))
     ~'(defn ?assoc
         "Same as assoc, but skip the assoc if v is nil"
         [m & kvs]
@@ -161,4 +161,10 @@
           ;;(mapv generate-function-from-method ;; TODO get all the methods)])))
          (apply concat) ;; <- this is for flattening the methods
          (mapv symbols->str)
+         ;; HACK: the *api-key* var should be dynamic (for rebinding)
+         ;; now, since the only way to define dynamic vars is through metadata,
+         ;; doing this in the def means using the ^ symbol, which is a reader macro.
+         ;; So we cannot have it as a clojure symbol in data. To go around this,
+         ;; we output a char \^, and do this replace once we generate the final string.
+         ((fn [sexps] (update sexps 1 #(str/replace % "\\^ :" "^:"))))
          (str/join "\n\n"))))