Add math functions

Add math functions

--- src/play_clj/math.clj
+++ src/play_clj/math.clj
@@ -1,9 +1,180 @@
 (ns play-clj.math
-  (:import [com.badlogic.gdx.math Vector2 Vector3]))
+  (:require [play-clj.utils :as u])
+  (:import [com.badlogic.gdx.math Bezier Bresenham2 BSpline CatmullRomSpline
+            Circle ConvexHull DelaunayTriangulator EarClippingTriangulator
+            Ellipse FloatCounter Frustum Vector2 Vector3]))
+
+; bezier
+
+(defn bezier*
+  ([]
+    (Bezier.))
+  ([points]
+    (Bezier. (into-array points) 0 (count points))))
+
+(defmacro bezier
+  [points & options]
+  `(u/calls! ^Bezier (bezier* ~points) ~@options))
+
+(defmacro bezier!
+  [object k & options]
+  `(u/call! ^Bezier ~object ~k ~@options))
+
+; bresenham2
+
+(defn bresenham2*
+  []
+  (Bresenham2.))
+
+(defmacro bresenham2
+  [& options]
+  `(u/calls! ^Bresenham2 (bresenham2*) ~@options))
+
+(defmacro bresenham2!
+  [object k & options]
+  `(u/call! ^Bresenham2 ~object ~k ~@options))
+
+; b-spline
+
+(defn b-spline*
+  ([]
+    (BSpline.))
+  ([points degree cont?]
+    (BSpline. (into-array points) degree cont?)))
+
+(defmacro b-spline
+  [points degree cont? & options]
+  `(u/calls! ^BSpline (b-spline* ~points ~degree ~cont?) ~@options))
+
+(defmacro b-spline!
+  [object k & options]
+  `(u/call! ^BSpline ~object ~k ~@options))
+
+; catmull-rom-spline
+
+(defn catmull-rom-spline*
+  ([]
+    (CatmullRomSpline.))
+  ([points cont?]
+    (CatmullRomSpline. (into-array points) cont?)))
+
+(defmacro catmull-rom-spline
+  [points cont? & options]
+  `(u/calls! ^CatmullRomSpline (catmull-rom-spline* ~points ~cont?) ~@options))
+
+(defmacro catmull-rom-spline!
+  [object k & options]
+  `(u/call! ^BSpline ~object ~k ~@options))
+
+; circle
+
+(defn circle*
+  ([]
+    (Circle.))
+  ([x y radius]
+    (Circle. x y radius)))
+
+(defmacro circle
+  [x y radius & options]
+  `(u/calls! ^Circle (circle* ~x ~y ~radius) ~@options))
+
+(defmacro circle!
+  [object k & options]
+  `(u/call! ^Circle ~object ~k ~@options))
+
+; convex-hull
+
+(defn convex-hull*
+  []
+  (ConvexHull.))
+
+(defmacro convex-hull
+  [& options]
+  `(u/calls! ^ConvexHull (convex-hull*) ~@options))
+
+(defmacro convex-hull!
+  [object k & options]
+  `(u/call! ^ConvexHull ~object ~k ~@options))
+
+; delaunay-triangulator
+
+(defn delaunay-triangulator*
+  []
+  (DelaunayTriangulator.))
+
+(defmacro delaunay-triangulator
+  [& options]
+  `(u/calls! ^DelaunayTriangulator (delaunay-triangulator*) ~@options))
+
+(defmacro delaunay-triangulator!
+  [object k & options]
+  `(u/call! ^DelaunayTriangulator ~object ~k ~@options))
+
+; ear-clipping-triangulator
+
+(defn ear-clipping-triangulator*
+  []
+  (EarClippingTriangulator.))
+
+(defmacro ear-clipping-triangulator
+  [& options]
+  `(u/calls! ^EarClippingTriangulator (ear-clipping-triangulator*) ~@options))
+
+(defmacro ear-clipping-triangulator!
+  [object k & options]
+  `(u/call! ^EarClippingTriangulator ~object ~k ~@options))
+
+; ellipse
+
+(defn ellipse*
+  ([]
+    (Ellipse.))
+  ([x y width height]
+    (Ellipse. x y width height)))
+
+(defmacro ellipse
+  [x y width height & options]
+  `(u/calls! ^Ellipse (ellipse* ~x ~y ~width ~height) ~@options))
+
+(defmacro ellipse!
+  [object k & options]
+  `(u/call! ^Ellipse ~object ~k ~@options))
+
+; float-counter
+
+(defn float-counter*
+  [window-size]
+  (FloatCounter. window-size))
+
+(defmacro float-counter
+  [window-size & options]
+  `(u/calls! ^FloatCounter (float-counter* ~window-size) ~@options))
+
+(defmacro float-counter!
+  [object k & options]
+  `(u/call! ^FloatCounter ~object ~k ~@options))
+
+; frustum
+
+(defn frustum*
+  []
+  (Frustum.))
+
+(defmacro frustum
+  [& options]
+  `(u/calls! ^Frustum (frustum*) ~@options))
+
+(defmacro frustum!
+  [object k & options]
+  `(u/call! ^Frustum ~object ~k ~@options))
+
+; vector-2

 (defn vector-2*
-  [x y]
-  (Vector2. x y))
+  ([]
+    (Vector2.))
+  ([x y]
+    (Vector2. x y)))

 (defmacro vector-2
   [x y & options]
@@ -13,9 +184,13 @@
   [object k & options]
   `(u/call! ^Vector2 ~object ~k ~@options))

+; vector-3
+
 (defn vector-3*
-  [x y z]
-  (Vector3. x y z))
+  ([]
+    (Vector3.))
+  ([x y z]
+    (Vector3. x y z)))

 (defmacro vector-3
   [x y z & options]


Cast to vector for clarity

Cast to vector for clarity

--- src/play_clj/repl.clj
+++ src/play_clj/repl.clj
@@ -24,7 +24,7 @@
   ([screen-object]
     (-> screen-object :entities deref))
   ([screen-object filter-fn]
-    (filter filter-fn (e screen-object))))
+    (vec (filter filter-fn (e screen-object)))))

 (defn e!
   "Resets the entities in `screen-object`, or associates values to the entities
@@ -38,8 +38,8 @@
   ([screen-object filter-fn & args]
     (swap! (:entities screen-object)
            (fn [entities]
-             (for [e entities]
-               (if (filter-fn e)
-                 (apply assoc e args)
-                 e))))
+             (vec (for [e entities]
+                    (if (filter-fn e)
+                      (apply assoc e args)
+                      e)))))
     (e screen-object filter-fn)))


Remove the use of `noConflict`.

Remove the use of `noConflict`.

--- src/promesa/impl.cljc
+++ src/promesa/impl.cljc
@@ -44,7 +44,7 @@
      (ForkJoinPool/commonPool)))

 #?(:cljs
-   (def ^:const Promise (js/Promise.noConflict)))
+   (def ^:const Promise js/Promise))

 ;; --- Promise Impl


fundamental.clj: small change in (fundamental-group)

--- clojure/org/gavrog/clojure/fundamental.clj
+++ clojure/org/gavrog/clojure/fundamental.clj
@@ -115,7 +115,7 @@
                      :let [w (trace-word ds edge2word i j D)]
                      :when (seq w)]
                  [D i j (relator-rep w) (v ds i j D)])]
-    {:generators (sort (keys gen2edge))
+    {:nr-generators (count gen2edge)
      :relators (sort (concat (for [[D i j w v] orbits] (-** w v))
                              (mirror-relators ds gen2edge)))
      :axes (sort (for [[D i j w v] orbits, :when (> v 1)] [w v]))


Don’t join nil classes into classes string (#132)

--- src/sablono/util.cljc
+++ src/sablono/util.cljc
@@ -66,6 +66,7 @@
                :else (seq %))
             classes)
        (flatten)
+       (remove nil?)
        (str/join " ")))

 (defn react-fn


-- additional logs in autoscaler (#139)

-- additional logs in autoscaler (#139)

--- waiter/src/waiter/scaling.clj
+++ waiter/src/waiter/scaling.clj
@@ -12,7 +12,6 @@
   (:require [clj-time.core :as t]
             [clojure.core.async :as async]
             [clojure.set :as set]
-            [clojure.string :as str]
             [clojure.tools.logging :as log]
             [metrics.core]
             [metrics.counters :as counters]
@@ -49,8 +48,8 @@
         (loop [service-id->scaling-executor-chan initial-state]
           (recur
             (let [[data channel] (async/alts! [executor-multiplexer-chan query-chan] :priority true)]
-              (cond
-                (= channel executor-multiplexer-chan)
+              (condp = channel
+                executor-multiplexer-chan
                 (let [{:keys [service-id scale-amount correlation-id] :as scaling-data} data]
                   (cid/with-correlation-id
                     correlation-id
@@ -69,7 +68,8 @@
                           (log/info "shutting down scaling executor channel for" service-id)
                           (async/close! executor-chan)
                           (dissoc service-id->scaling-executor-chan service-id))))))
-                (= channel query-chan)
+
+                query-chan
                 (let [{:keys [response-chan service-id]} data]
                   (if service-id
                     (if-let [query-chan (get-in service-id->scaling-executor-chan [service-id :query-chan])]
@@ -356,7 +356,7 @@
             (map (fn [service-id]
                    (let [outstanding-requests (or (service-id->outstanding-requests service-id) 0)
                          {:keys [healthy-instances expired-instances]} (service-id->router-state service-id)
-                         {:keys [instances task-count]} (service-id->scheduler-state service-id)
+                         {:keys [instances task-count] :as scheduler-state} (service-id->scheduler-state service-id)
                          ; if we don't have a target instance count, default to the number of tasks
                          target-instances (get-in service-id->scale-state [service-id :target-instances] task-count)
                          {:keys [target-instances scale-to-instances scale-amount]}
@@ -368,7 +368,10 @@
                                           :outstanding-requests outstanding-requests
                                           :target-instances target-instances
                                           :total-instances instances})
-                           {:scale-to-instances instances :target-instances target-instances :scale-amount 0})]
+                           (do
+                             (log/info "no target instances available for service"
+                                       {:scheduler-state scheduler-state, :service-id service-id})
+                             {:scale-to-instances instances :target-instances target-instances :scale-amount 0}))]
                      (when-not (zero? scale-amount)
                        (apply-scaling-fn service-id
                                          {:outstanding-requests outstanding-requests
@@ -419,9 +422,11 @@
                         (assoc current-state :continue-looping false :timeout-chan nil)
                         state-chan
                         (let [{:keys [service-id->healthy-instances service-id->unhealthy-instances service-id->expired-instances]} args
+                              existing-service-ids-set (set (keys service-id->router-state))
                               service-ids-set (set/union (-> service-id->healthy-instances (keys) (set))
                                                          (-> service-id->unhealthy-instances (keys) (set)))
-                              deleted-service-ids (set/difference (set (keys service-id->router-state)) service-ids-set)
+                              deleted-service-ids (set/difference existing-service-ids-set service-ids-set)
+                              new-service-ids (set/difference service-ids-set existing-service-ids-set)
                               service-id->router-state' (pc/map-from-keys
                                                           (fn [service-id]
                                                             {:healthy-instances (count (service-id->healthy-instances service-id))
@@ -429,6 +434,8 @@
                                                           service-ids-set)]
                           (cid/with-correlation-id
                             correlation-id
+                            (when (seq new-service-ids)
+                              (log/info "started tracking following services:" new-service-ids))
                             (when (seq deleted-service-ids)
                               (log/info "no longer tracking following services:" deleted-service-ids)
                               ; trigger closing of the scaling executors for the services


Cleaup

Cleaup

--- src/tango/export2.clj
+++ src/tango/export2.clj
@@ -353,14 +353,6 @@
     (make-copy-with-timestamp export-path)
     (spit export-path (ppxml (xml/emit-str out-xml)))))

-(map activity-result->class-result activities-with-result)
-(activity-result->class-result activities-with-result)
-
 (defn smoke-test [] (export-results (activities-with-result) "dp.xml"))

-(smoke-test)
-
-(defn smoke-test-old []
-  (let [in-xml (get-xml-from-file "test/tango/examples/real-example.xml")
-        out-xml (add-results-to-dp-xml in-xml (first class-results))]
-    (spit "export5.xml" (xml/emit-str out-xml))))
+;; (smoke-test)


fixed clojure implementation

fixed clojure implementation

--- clj.clj
+++ clj.clj
@@ -6,9 +6,9 @@
 (set! *warn-on-reflection* true)
 (set! *unchecked-math* :warn-on-boxed)

-(deftype route [#^int dest #^int cost])
+(defrecord route [#^int dest #^int cost])

-(deftype node [#^clojure.lang.PersistentVector neighbours])
+(defrecord node [#^clojure.lang.PersistentVector neighbours])

 (defn mk-node [_] (->node []))

@@ -17,33 +17,36 @@
         num-lines (Integer/parseInt (get lines 0))
         node-vec (vec (take num-lines (iterate mk-node (->node []))))]
     (letfn [(my-loop [nodes i]
-           (let [nums (str/split (get lines i) #" ")
-                 len (count nums)]
-             (if (and (> len 2) (> (count lines) (+ i 1)))
-               (let [node-id (Integer/parseInt (get nums 0))
-                     neighbour (Integer/parseInt (get nums 1))
-                     cost (Integer/parseInt (get nums 2))
-                     new-node (->node
-                               (conj (.neighbours (get nodes node-id))
-                                     (route. neighbour cost)))]
-                 (my-loop (assoc nodes node-id new-node) (+ i 1)))
-               nodes)))]
+              (let [nums (str/split (get lines i) #" ")
+                    len (count nums)]
+                (if (and (> len 2) (> (count lines) (+ i 0)))
+                  (let [node-id (Integer/parseInt (get nums 0))
+                        neighbour (Integer/parseInt (get nums 1))
+                        cost (Integer/parseInt (get nums 2))
+                        new-node (->node
+                                  (conj (:neighbours (get nodes node-id))
+                                        (route. neighbour cost)))]
+                    (if (= (count lines) (+ i 1))
+                      (assoc nodes node-id new-node)
+                      (my-loop (assoc nodes node-id new-node) (+ i 1))))
+                  nodes)))]
       (my-loop node-vec 1))))

-(defn get-longest-path [#^clojure.lang.PersistentVector nodes #^long node-id #^booleans visited]
-  (aset visited node-id true)
-  (let [max (atom 0)]
-    (dorun (map (fn [#^route neighbour]
-                  (if (not (aget visited (.dest neighbour)))
-                    (let [dist (+ (.cost neighbour) (get-longest-path nodes (.dest neighbour) visited))]
-                      (if (> dist @max)
-                        (reset! max dist)
-                        nil))
-                    nil))
-                (.neighbours (get nodes node-id))))
-    (aset visited node-id false)
-    @max))
+(defn get-longest-path [nodes #^long node-id-obj #^booleans visited]
+  (let [node-id (long node-id-obj)]
+    (aset visited node-id true)
+    (let [max (atom (long 0))]
+      (dorun (map (fn [#^route neighbour]
+                    (if (not (aget visited (.dest neighbour)))
+                      (let [dist (+ (.cost neighbour) (get-longest-path nodes (.dest neighbour) visited))]
+                        (if (> dist @max)
+                          (reset! max dist)
+                          nil))
+                      nil))
+                  (:neighbours (get nodes node-id))))
+      (aset visited node-id false)
+      @max)))

-(def nodes (read-places))
+(def nodes (to-array (read-places)))
 (def visited (make-array Boolean/TYPE (count nodes)))
 (print (get-longest-path nodes 0 visited))


make extract-fn easier to read

make extract-fn easier to read

--- src/tufdown/core.cljc
+++ src/tufdown/core.cljc
@@ -22,9 +22,7 @@
   (let [태그맵 {:큰제목 "h2", :작은제목 "h3", :일반목록 "ul", :숫자목록 "ol"
                 :항목 "li", :인용 "blockquote", :원문 "pre", :문단 "div"
                 :문장 "p", :기울임 "i", :굵게 "em"}
-        추출 (fn [tag] (some
-                       (fn [e] (if (= (first e) tag) (apply str (rest e))))
-                       내용))]
+        추출 (fn [tag] (apply str (some #(= (first %) tag) 내용)))]
     (case 태그
       :빈줄   "
"
       :구분줄 "
"


sort require-clauses

sort require-clauses

--- src/whatsoup/core.clj
+++ src/whatsoup/core.clj
@@ -3,13 +3,13 @@
             [com.stuartsierra.component :as component]
             [compojure.core :refer :all]
             [compojure.route :as route]
-            [ring.middleware.defaults :refer [wrap-defaults site-defaults]]
-            [ring.middleware.session.memory :refer [memory-store]]
             [noir.session :as session]
             [noir.response :as response]
+            [ring.middleware.session.memory :refer [memory-store]]
+            [ring.middleware.defaults :refer [wrap-defaults site-defaults]]
             [whatsoup.food-kb :as kb]
+            [whatsoup.meal-generator :as meal-generator]
             [whatsoup.web :as web]
-            [whatsoup.meal-generator :as meal-generator]
             [whatsoup.util :as util]))

 (defn production-system [config-file]


Fixed omission of CORS header when value is false

--- src/yada/security.clj
+++ src/yada/security.clj
@@ -161,7 +161,7 @@
         allow-origin
         (assoc-in [:response :headers "access-control-allow-origin"] allow-origin)

-        (:allow-credentials access-control)
+        (contains? access-control :allow-credentials)
         (assoc-in [:response :headers "access-control-allow-credentials"]
                   (to-header (:allow-credentials access-control)))


fix: project.clj for ssclj

fix: project.clj for ssclj

--- ssclj/jar/project.clj
+++ ssclj/jar/project.clj
@@ -95,7 +95,7 @@

    :dev
      { :env {  :clj-env        "development"
-               :config-path    "config-hsqldb-mem.edn"}
+               :config-path    "config-hsqldb.edn"}
        :jvm-opts ["-Dlogfile.path=development"]
        :dependencies [ [peridot/peridot "0.4.1"]
                        [expectations/expectations "2.1.4"]]}


Updates UMM generators to return nil instead of empty seqs.

--- umm-spec-lib/src/cmr/umm_spec/test/umm_generators.clj
+++ umm-spec-lib/src/cmr/umm_spec/test/umm_generators.clj
@@ -69,11 +69,13 @@
   [schema type-name schema-type]
   (rejected-unexpected-fields #{:items :minItems :maxItems} schema-type)
   (let [{:keys [items minItems maxItems]} (merge array-defaults schema-type)
-        item-generator (schema-type->generator schema type-name items)]
-    (gen/vector item-generator
-                minItems
-                ;; Limit the maximum number of items in an array to 5.
-                (min maxItems 5))))
+        item-generator (schema-type->generator schema type-name items)
+        ;; Limit the maximum number of items in an array to 5.
+        maxItems (min maxItems 5)]
+    (if (= minItems 0)
+      ;; Return nil instead of empty vectors.
+      (gen/one-of [(gen/return nil) (gen/vector item-generator 1 maxItems)])
+      (gen/vector item-generator minItems maxItems))))

 (defmethod schema-type->generator :$ref
   [schema type-name schema-type]


Codox now working

Codox now working

--- ruotasfortuna/project.clj
+++ ruotasfortuna/project.clj
@@ -24,7 +24,10 @@
             [lein-codox "0.10.3"]
    ]

-:codox {:language :clojurescript}
+:codox {:language :clojurescript
+        :source-paths ["src/"]
+}
+
 :docstring-checker {  :include [#"ruotasfortuna"]
                       :exclude [#"test"]}
  :eastwood {:add-linters [:unused-locals


Missed refactored function

Missed refactored function

--- env/dev/clj/gtfve/datomic.clj
+++ env/dev/clj/gtfve/datomic.clj
@@ -229,7 +229,7 @@

 (defn load-trips! [path conn]
   (->> path
-       (csv-tx trips-header-keys trips-val-transforms)
+       (csv->maps trips-header-keys trips-val-transforms)
        (map assoc-temp-id)
        (d/transact conn)))


Caso cuando se ejecuta y no hay resultado (porque no se pasaron ciudades).

--- desafio2/clojure/src/weather/core.clj
+++ desafio2/clojure/src/weather/core.clj
@@ -7,11 +7,13 @@
 (def report-format "%-30.30s %2.1f   %s")

 (defn print-weather [reports]
-  (doseq [report reports]
-    (if (:error report)
-      (println (:city report) "Error:" (:error report))
-      (println (format report-format (:city report) (:max-temp report) (:conditions report)))))
-  (shutdown-agents))
+  (if (empty? reports)
+    (println no-cities-provided-message)
+    (doseq [report reports]
+      (if (:error report)
+        (println (:city report) "Error:" (:error report))
+        (println (format report-format (:city report) (:max-temp report) (:conditions report))))))
+    (shutdown-agents))

 (defn sort-reports [reports]
   (sort-by :max-temp #(< 0 (compare %1 %2)) reports))


added i18n dep back

added i18n dep back

--- src/cards/untangled/components/cards_ui.cljs
+++ src/cards/untangled/components/cards_ui.cljs
@@ -3,6 +3,7 @@
             [devtools.core :as devtools]
             [untangled.components.forms]
             [untangled.components.tables]
+            [yahoo.intl-messageformat-with-locales]
             [untangled.components.calendar]))

 (defn start []


fix indentation

fix indentation

--- src/clj_money/models/storage/sql_storage.clj
+++ src/clj_money/models/storage/sql_storage.clj
@@ -737,19 +737,19 @@
     [this criteria]
     (.select-transaction-items this criteria {}))

-(select-transaction-items
-  [_ criteria options]
-  (let [sql (-> (transaction-item-base-query)
-                (adjust-select options)
-                (h/where (map->where criteria))
-                (append-sort (merge
-                               {:sort [:t.transaction_date :i.index]}
-                               options))
-                (append-limit options))
-        result (query db-spec sql)]
-    (if (:count options)
-      (-> result first vals first)
-      result)))
+  (select-transaction-items
+    [_ criteria options]
+    (let [sql (-> (transaction-item-base-query)
+                  (adjust-select options)
+                  (h/where (map->where criteria))
+                  (append-sort (merge
+                                {:sort [:t.transaction_date :i.index]}
+                                options))
+                  (append-limit options))
+          result (query db-spec sql)]
+      (if (:count options)
+        (-> result first vals first)
+        result)))

   ; Reconciliations
   (create-reconciliation


experiment with graph layout

experiment with graph layout

--- src/cljs/flow_editor/views/graph_viewer.cljs
+++ src/cljs/flow_editor/views/graph_viewer.cljs
@@ -40,7 +40,7 @@
                :highlight {:border "#de7a13"
                            :background "#f5fba8"}}
        :size 15
-       :font {:size 12}}}
+       :font {:size 0}}}

      :interaction {:multiselect true}
@@ -73,7 +73,8 @@
                                     node (adjust-pos e node)]
                                 (if (:value e)
                                   (assoc node :borderWidth 5
-                                              :borderWidthSelected 5)
+                                              :borderWidthSelected 5
+                                              :size 20)
                                   node)))))

         process-nodes (->> (:processes graph)
@@ -84,7 +85,8 @@
                                      node (adjust-pos p node)]
                                  (if (:autostart p)
                                    (assoc node :borderWidth 5
-                                               :borderWidthSelected 5)
+                                               :borderWidthSelected 5
+                                               :size 13)
                                    node)))))

         nodes (concat entity-nodes process-nodes)
@@ -188,8 +190,7 @@
                        graph (:graph (r/props comp))
                        vis-data (get-vis-graph graph @types)]
                    (.setSize net (aget dom-rect "width") (aget dom-rect "height"))
-                   (.setData net (clj->js vis-data))
-                   (.fit net)))]
+                   (.setData net (clj->js vis-data))))]

     (r/create-class
       {:reagent-render (fn []
@@ -202,7 +203,8 @@
                                     new-network (js/vis.Network. node)]
                                 (init-vis new-network)
                                 (reset! network new-network)
-                                (render comp new-network)))
+                                (render comp new-network)
+                                (.fit new-network)))

        :component-did-update #(render % @network)})))


+(defn generate [spec])

+(defn generate [spec])

--- test/babel/test/la.cljc
+++ test/babel/test/la.cljc
@@ -5,7 +5,7 @@
    [babel.engine :as engine]
    [babel.english :as source]
    [babel.latin.morphology :refer [analyze conjugate]]
-   [babel.latin :as target :refer [fo generate read-one]]
+   [babel.latin :as target :refer [fo read-one]]
    [clojure.repl :refer [doc]]
    [clojure.test :refer [deftest is]]
    [clojure.tools.logging :as log]
@@ -24,7 +24,7 @@
 (def source-format-fn (-> ((-> models source-language)) deref :morph))

 ;; function to generate expression in target langage
-(def target-generate-fn (-> ((-> models :la)) deref :generate-fn))
+(def generate (-> ((-> models :la)) deref :generate-fn))

 (def target-format-fn (-> ((-> models :la)) deref :morph))

@@ -48,8 +48,7 @@
          (fo (generate
               {:root "ardēre"
                :synsem {:sem {:subj {:pred :voi}
-                              :tense :present}}}
-              model)))))
+                              :tense :present}}})))))

 (deftest generate-imperfect
   (is (= "ardebam"
@@ -57,17 +56,14 @@
               {:root "ardēre"
                :synsem {:sem {:subj {:pred :I}
                               :tense :past
-                              :aspect :progressive}}}
-              model)))))
+                              :aspect :progressive}}})))))

 (deftest generate-future
   (is (= "ardebunt"
          (fo (generate
               {:root "ardēre"
                :synsem {:sem {:subj {:pred :loro}
-                              :tense :future}}}
-              model)))))
-
+                              :tense :future}}})))))

 (deftest engine-generate
   (is (= "ardetis"
@@ -89,7 +85,7 @@
                 source-format-fn)
         target (->
                 spec
-                target-generate-fn
+                generate
                 target-format-fn)]
     (is (or (= source "he used to answer")
             (= source "he was answering")


catch exception when initializing runtime with (expr 0)

--- src/babel/workbook.clj
+++ src/babel/workbook.clj
@@ -50,11 +50,21 @@
 (def workbook-sandbox
   (sandbox
    (conj
-    ;;clojail.testers/secure-tester-without-def
-    []
+    clojail.testers/secure-tester-without-def
     (blacklist-nses '[
+                      clojure.main
+                      java
+                      javax
+                      org.omg
+                      org.w3c
+                      org.xml
                       ])
     (blacklist-objects [
+                        clojure.lang.Compiler
+                        clojure.lang.Ref
+                        clojure.lang.Reflector
+                        clojure.lang.Namespace
+                        clojure.lang.Var clojure.lang.RT
                         ]))
    :refer-clojure false
    ;; using 60000 for development: for production, use much smaller value.
@@ -189,8 +199,8 @@
     ;; jdk1.5 management interfaces unavailable... JMX support disabled.
     ;; java.security.AccessControlException: access denied
     ;; ("javax.management.MBeanServerPermission" "createMBeanServer")
-    (expr 0)))
-
-
-
-
+    (try (expr 0)
+         (catch Exception e
+           (log/error (str "ignoring exception while trying to do (expr 0): "
+                           e))))))
+


Eliminate sleep before forming socket.

Eliminate sleep before forming socket.

Since we are not launching a process (the iOS app is already running),
we need not wait before attempting to connect.

--- Clojure/src/ambly/repl/jsc.clj
+++ Clojure/src/ambly/repl/jsc.clj
@@ -120,9 +120,6 @@
         env (ana/empty-env)
         core (io/resource "cljs/core.cljs")
         root-path (.getCanonicalFile output-dir)]
-    ;; TODO: temporary hack, should wait till we can read the start string
-    ;; from the process - David
-    (Thread/sleep 300)
     (reset! (:socket repl-env)
       (socket (:host repl-env) (:port repl-env)))
     ;; Start dedicated thread to read messages from socket


Fixed insert of routes in request

Fixed insert of routes in request

--- modules/bidi/src/modular/bidi.clj
+++ modules/bidi/src/modular/bidi.clj
@@ -56,7 +56,10 @@

 (defrecord BidiRingHandlerProvider []
   component/Lifecycle
-  (start [this] this)
+  (start [this]
+    (assoc this :routes ["" (vec (for [v (vals this)
+                                       :when (satisfies? BidiRoutesContributor v)]
+                                   [(or (context v) "") [(routes v)]]))]))
   (stop [this] this)

   Index
@@ -64,12 +67,9 @@

   RingHandlerProvider
   (handler [this]
-    (let [routes ["" (vec (for [v (vals this)
-                                :when (satisfies? BidiRoutesContributor v)]
-                            [(or (context v) "") [(routes v)]]))]]
-      (-> routes
-          bidi/make-handler
-          (wrap-routes routes)))))
+    (let [routes (:routes this)]
+      (-> routes bidi/make-handler
+       (wrap-routes routes)))))

 ;; Keep this around for future integration with Prismatic Schema
 (defn new-bidi-ring-handler-provider []


(PDB-5259) convert-to-plan: drop vestigial :project-fields

It looks like it was just a typo in
77592b5988cefd5b4a00c3ddac82322a231acfd8, and is no longer needed (or
desirable), i.e. the value there is a list of field names:

 ("latest_report_corrective_change" "deactivated" ...)

and not a sequence of items matching the expected `projection-schema`.

--- src/puppetlabs/puppetdb/query_eng/engine.clj
+++ src/puppetlabs/puppetdb/query_eng/engine.clj
@@ -2588,10 +2588,7 @@
         projections (projectable-fields query-rec)]
     (if (instance? Query plan-node)
       plan-node
-      (-> query-rec
-          (assoc :where plan-node
-                 :paging-options paging-options
-                 :project-fields projections)))))
+      (assoc query-rec :where plan-node :paging-options paging-options))))

 (declare push-down-context)


(PDB-3518) More specific join for certname->reports

Previously, queries which cross certnames and reports via latest_report_id would
sometimes get a degenerate query plan due to the presence of
idx_certnames_latest_report_id. The planner was led to believe that this index
made starting with a filtered version of the reports table and then joining that
to certnames was a good plan; it is not.

By adding an additional condition to the join which touches the certname table,
we encourage the planner to deal directly with rows which include both report.id
and certname.certname. The most direct way to do this is to scan down certnames
and pull each latest_report using the main report id index. This is the plan it
makes now, and it's a lot faster.

--- src/puppetlabs/puppetdb/query_eng/engine.clj
+++ src/puppetlabs/puppetdb/query_eng/engine.clj
@@ -257,7 +257,9 @@
                                        [:= :certnames.certname :fs.certname]

                                        :reports
-                                       [:= :certnames.latest_report_id :reports.id]
+                                       [:and
+                                        [:= :certnames.certname :reports.certname]
+                                        [:= :certnames.latest_report_id :reports.id]]

                                        [:environments :catalog_environment]
                                        [:= :catalog_environment.id :catalogs.environment_id]
@@ -899,7 +901,9 @@
                                                    :field (hsql-hash-as-str :reports.hash)}}
                :selection {:from [:certnames]
                            :join [:reports
-                                  [:= :reports.id :certnames.latest_report_id]]}
+                                  [:and
+                                   [:= :certnames.certname :reports.certname]
+                                   [:= :certnames.latest_report_id :reports.id]]]}

                :alias "latest_report"
                :subquery? false


Password input is now actually a password input.

--- src/task_tracker/app/components/account.cljs
+++ src/task_tracker/app/components/account.cljs
@@ -12,10 +12,12 @@
       (dom/label
        #js {:className "account-field-label"}
        (str field-label-text ":"))
-      (dom/input #js {:onChange (fn [e]
-                                  (let [val (.. e -target -value)]
-                                    (om/update! data data-key val)))
-                      :value (data-key data)})))))
+      (dom/input
+       #js {:onChange (fn [e]
+                        (let [val (.. e -target -value)]
+                          (om/update! data data-key val)))
+            :value    (data-key data)
+            :type     (:field-type opts)})))))

 (defcomponent root
   (render
@@ -26,4 +28,5 @@
     (om/build account-field (:account-info data) {:opts {:field-name       "email"
                                                          :field-label-text "Email"}})
     (om/build account-field (:account-info data) {:opts {:field-name       "password"
-                                                         :field-label-text "Password"}}))))
+                                                         :field-label-text "Password"
+                                                         :field-type       "password"}}))))


Remove redundant ns declaration

Remove redundant ns declaration

--- euler_clojure/src/euler/problem55.clj
+++ euler_clojure/src/euler/problem55.clj
@@ -4,8 +4,6 @@
   reverse and add process is called a Lychrel number. How many
   Lychrel numbers are there below ten-thousand? (Only consider fifty
   iterations)")
-
-(ns euler.problem55)

 (defn reverse-num [n]
   ;; 123456 => 654321N


Test default sessions

Test default sessions

--- test/uruk/core_test.clj
+++ test/uruk/core_test.clj
@@ -296,6 +296,37 @@
                                  {:transaction-timeout 234 :derp "invalid!"})))))

+(deftest default-sessions-created-as-expected
+  (testing "We should be able to create default sessions from all kinds of content sources."
+    (testing "...URI content sources"
+      (is (instance? com.marklogic.xcc.impl.SessionImpl
+                     (create-default-session (make-uri-content-source (:uri db)))))
+      (is (= "default session logger" (-> (make-uri-content-source (:uri db)
+                                                                   {:default-logger (Logger/getLogger "default session logger")})
+                                          create-default-session
+                                          .getLogger
+                                          .getName)))
+      (is (= "non-default session logger" (-> (make-uri-content-source (:uri db)
+                                                                       {:default-logger (Logger/getLogger "default session test")})
+                                              (create-default-session {:logger (Logger/getLogger "non-default session logger")})
+                                              .getLogger
+                                              .getName))))
+    (testing "...hosted content sources"
+      (is (instance? com.marklogic.xcc.impl.SessionImpl
+                     (create-default-session (make-hosted-content-source "localhost" 8383
+                                                                         {:content-base "TutorialDB"}))))
+      (is (= "default session logger" (-> (make-hosted-content-source "localhost" 8383
+                                                                      {:default-logger (Logger/getLogger "default session logger")})
+                                          create-default-session
+                                          .getLogger
+                                          .getName)))
+      (is (= "non-default session logger" (-> (make-hosted-content-source "localhost" 8383
+                                                                          {:default-logger (Logger/getLogger "default session test")})
+                                              (create-default-session {:logger (Logger/getLogger "non-default session logger")})
+                                              .getLogger
+                                              .getName))))))
+
+
 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 ;;;; Content creation options
 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;


Cleanup lint warnings.

Cleanup lint warnings.

--- src/onyx/peer/task_lifecycle.clj
+++ src/onyx/peer/task_lifecycle.clj
@@ -12,6 +12,7 @@
             [onyx.lifecycles.lifecycle-compile :as lc]
             [onyx.log.commands.common :as common]
             [onyx.log.entry :as entry]
+            [clojure.set]
             [onyx.log.replica]
             [onyx.messaging.common :as mc]
             [onyx.messaging.messenger-state :as ms]
@@ -101,11 +102,11 @@
       (= (:onyx/min-peers (:onyx.core/task-map event))
          (:onyx/max-peers (:onyx.core/task-map event)))))

-(defn windowed-task? [{:keys [onyx.core/windows onyx.core/triggers] :as event}]
+(defn windowed-task? [{:keys [onyx.core/windows onyx.core/triggers]}]
   (or (not (empty? windows))
       (not (empty? triggers))))

-(defn triggered-task? [{:keys [onyx.core/triggers] :as event}]
+(defn triggered-task? [{:keys [onyx.core/triggers]}]
   (not (empty? triggers)))

 (defn completed? [state]
@@ -129,8 +130,7 @@
             (.update received-timer (- curr-time hb) TimeUnit/NANOSECONDS))
           (all-heartbeat-times messenger))))

-(s/defn next-iteration
-  [state]
+(s/defn next-iteration [state]
   {:post [(empty? (:onyx.core/batch (:event %)))]}
   (-> state
       (set-context! nil)
@@ -272,8 +272,7 @@
     (advance state)))

 (defn trigger-checkpointed-state-event [state epoch]
-  (let [messenger (get-messenger state)
-        {:keys [onyx.core/triggers] :as event} (get-event state)]
+  (let [{:keys [onyx.core/triggers] :as event} (get-event state)]
     (if (not (empty? triggers))
       (ws/assign-windows state
                          (onyx.types/checkpointed-state-event
@@ -287,8 +286,7 @@
 (defn try-seal-job! [state]
   (if (and (completed? state)
            (not (sealed? state)))
-    (let [messenger (get-messenger state)
-          {:keys [onyx.core/triggers] :as event} (get-event state)]
+    (let [{:keys [onyx.core/triggers] :as event} (get-event state)]
       (cond-> state
         (not (empty? triggers))
         (ws/assign-windows (onyx.types/new-state-event :job-completed
@@ -321,7 +319,7 @@
         subscriber (m/subscriber messenger)]
     (if (sub/blocked? subscriber)
       (if (synced? state)
-        (let [{:keys [onyx.core/monitoring] :as event} (get-event state)
+        (let [{:keys [onyx.core/monitoring]} (get-event state)
               watermarks (state->watermarks state)]
           (.set ^AtomicLong (:workflow-watermark monitoring) (:input watermarks))
           (.set ^AtomicLong (:coordinator-watermark monitoring) (:coordinator watermarks))
@@ -464,7 +462,7 @@

 (defn recover-state
   [state]
-  (let [{:keys [onyx.core/task-id onyx.core/peer-opts] :as event} (get-event state)
+  (let [{:keys [onyx.core/peer-opts] :as event} (get-event state)
         _ (cleanup-previous-state-store! state)
         state-serializers (onyx.state.serializers.utils/event->state-serializers event)
         db-name (db-name event)
@@ -645,7 +643,7 @@
         state)
       identity)))

-(defn build-read-batch [{:keys [onyx.core/task-map onyx.core/since-barrier-count onyx.core/peer-opts] :as event}]
+(defn build-read-batch [{:keys [onyx.core/task-map onyx.core/since-barrier-count] :as event}]
   (let [batch-timeout-ns (long (ms->ns (arg-or-default :onyx/batch-timeout task-map)))
         batch-size (long (:onyx/batch-size task-map))]
     (if (source-task? event)
@@ -716,8 +714,7 @@
                     :builder (fn [_] assign-windows)}
                    {:lifecycle :lifecycle/prepare-segments
                     :builder (fn [{:keys [onyx.core/triggers onyx.core/task-map]}]
-                               (let [write-batch (transient [])
-                                     transformed-fn (if (not= :reduce (:onyx/type task-map))
+                               (let [transformed-fn (if (not= :reduce (:onyx/type task-map))
                                                       (fn [event write-batch]
                                                         (run! (fn [segs]
                                                                 (run! (fn [seg]
@@ -755,7 +752,7 @@
                 state-fn-builders)))

 (defn build-task-fns
-  [{:keys [onyx.core/task-map] :as event}]
+  [event]
   (let [task-types (cond-> #{(node-type event)}
                      (windowed-task? event) (conj :windowed))
         phase-order [:recover :start-iteration :barriers :process-batch :heartbeat]]
@@ -766,8 +763,8 @@
                    (not-empty (clojure.set/intersection task-types (:type lifecycle)))))
          (map (fn [lifecycle] (assoc lifecycle :fn ((:builder lifecycle) event))))
          (vec))))
+
 ;; Used in tests to detect when a task stop is called
-
 (defn stop-flag! [])

 (defn notify-created-db! [state-store-ch replica-version event state-store]
@@ -1150,8 +1147,6 @@
                         heartbeat-ns last-heartbeat
                         time-init-state evicted)))

-;; NOTE: currently, if task doesn't start before the liveness timeout, the peer will be killed
-;; peer should probably be heartbeating here
 (defn backoff-until-task-start!
   [{:keys [onyx.core/kill-flag onyx.core/task-kill-flag onyx.core/opts] :as event} start-fn]
   (while (and (not (or @kill-flag @task-kill-flag))
@@ -1213,7 +1208,7 @@
   (if (= :input (:onyx/type task-map))
     (p/start (instantiate-plugin event) event)))

-(defn build-output-pipeline [{:keys [onyx.core/task-map] :as event}]
+(defn build-output-pipeline [event]
   (cond (source-task? event)
         (p/start (mo/new-messenger-output event) event)

@@ -1248,7 +1243,7 @@
             (info log-prefix "Warming up task lifecycle" (:onyx.core/serialized-task event))
             (backoff-until-task-start! event start?-fn)
             (try
-              (let [{:keys [onyx.core/task-map] :as event} (before-task-start-fn event)
+              (let [event (before-task-start-fn event)
                     task-monitoring (component/start (metrics-monitoring/new-task-monitoring event))
                     component (assoc component :task-monitoring task-monitoring)
                     event (assoc event :onyx.core/monitoring task-monitoring)]
@@ -1302,7 +1297,7 @@
           component))))

   (stop [component]
-    (if-let [task-name (:name (:task (:task-information component)))]
+    (if (:name (:task (:task-information component)))
       (info (:log-prefix component) "Stopping task lifecycle.")
       (warn (:log-prefix component) "Stopping task lifecycle, failed to initialize task set up."))
     (some-> component :task-monitoring component/stop)


[ci skip] Remove prn

[ci skip] Remove prn

--- src/onyx/peer/task_lifecycle.clj
+++ src/onyx/peer/task_lifecycle.clj
@@ -297,7 +297,6 @@
              ch (second (alts!! [timeout-ch task-kill-ch]))]
          (when (= ch timeout-ch)
            (let [tail (last (get-in @(:onyx.core/state event) [:timeout-pool]))]
-             (prn tail)
              (doseq [m tail]
                (when (p-ext/pending? event (:id m))
                  (taoensso.timbre/info (str "Message " (:id m) " timed out, replaying it from it's initial task."))


Remove unnecessary namespace declaration

--- euler_clojure/src/euler/problem54.clj
+++ euler_clojure/src/euler/problem54.clj
@@ -1,8 +1,6 @@
 (ns euler.problem54
   "The file, poker.txt, contains one-thousand random hands dealt to two players.
   How many hands does Player 1 win?")
-
-(ns euler.problem54)

 (defn suits
   "Return the suits of a given poker hand"


Ditto

Ditto

--- test/clojurewerkz/cassaforte/stress_test.clj
+++ test/clojurewerkz/cassaforte/stress_test.clj
@@ -1,9 +1,9 @@
 (ns clojurewerkz.cassaforte.stress-test
   (:require [clojurewerkz.cassaforte.test-helper :as th]
-            [clojurewerkz.cassaforte.client :as client])
-  (:use clojurewerkz.cassaforte.cql
-        clojure.test
-        clojurewerkz.cassaforte.query))
+            [clojurewerkz.cassaforte.client :as client]
+            [clojurewerkz.cassaforte.cql :refer :all]
+            [clojure.test :refer :all]
+            [clojurewerkz.cassaforte.query :refer :all]))

 (use-fixtures :each th/initialize!)


correct testing description

correct testing description

--- test/er_cassandra/model/alia/upsert_test.clj
+++ test/er_cassandra/model/alia/upsert_test.clj
@@ -381,7 +381,7 @@
                              [:id]
                              [id])))))

-    (testing "result includes columns removed from an op by :before-save callbacks"
+    (testing "keys which are not valid c* columsn are removed from results"
       (let [m (create-simple-entity-with-protected-column)

             [id] [(uuid/v1)]
@@ -397,9 +397,7 @@
         (is (= record-with-nick
                (fetch-record :simple_upsert_test_with_protected_column
                              [:id]
-                             [id]))))
-
-      )))
+                             [id])))))))

 (deftest upsert-changes*-if-not-exists-test
   (let [m (create-simple-entity)


copy-unique-keys-test

copy-unique-keys-test

--- test/er_cassandra/model/alia/upsert_test.clj
+++ test/er_cassandra/model/alia/upsert_test.clj
@@ -314,7 +314,28 @@
            (fetch-record :upsert_mixed_lookup_test_by_phone
                          [:phone] "456")))))

-(deftest copy-unique-keys-test)
+(deftest copy-unique-keys-test
+  (let [m (t/create-entity
+           {:primary-table {:name :upsert_copy_unique_keys_test :key [:org_id :id]}
+            :unique-key-tables [{:name :upsert_copy_unique_keys_test_by_nick
+                                 :key [:org_id :nick]}
+                                {:name :upsert_copy_unique_keys_test_by_email
+                                 :key [:email]
+                                 :collections {:email :set}}
+                                {:name :upsert_copy_unique_keys_test_by_phone
+                                 :key [:phone]
+                                 :collections {:phone :list}}]})
+        [org-id id] [(clj-uuid/v1) (clj-uuid/v1)]
+        r {:org_id org-id
+           :id id
+           :nick "foo"
+           :email #{"foo@bar.com" "foo@baz.com"}
+           :phone ["123" "456"]}]
+    (is (= (select-keys r [:nick :email :phone])
+           (u/copy-unique-keys
+            m
+            r
+            {})))))

 (deftest has-lookups?-test
   )


format money in history

format money in history

--- frontend/src/leftover/ui.cljs
+++ frontend/src/leftover/ui.cljs
@@ -10,12 +10,14 @@
     [om-bootstrap.input :as obi]
     [om-bootstrap.table :as obt]))

+(def money-format "%.02f")
+
 (defn hist->tr
   [hist]
   (dom/tr
     ; (dom/td  (:when hist))
     (dom/td  (:location hist))
-    (dom/td  (:amount hist))))
+    (dom/td  (gstring/format money-format (:amount hist)))))

 (defn view-history [data owner]
   (reify om/IRender
@@ -44,7 +46,7 @@
   [name str]
   (cond
     (empty? str) {name "is empty"}
-    (not (re-matches #"^\d+(\.\d+)$" str)) {name "is not a number"}))
+    (not (re-matches #"^-?\d+(\.\d+)?$" str)) {name "is not a number"}))

 (defn payment-errors
   [{:keys [location amount]}]
@@ -88,7 +90,7 @@
   (reify om/IRender
     (render [this]
       (dom/h3 {:class "col-sm-6 currenttotal"}
-               (str "Current Total: " (gstring/format "$%.02f" (apply - (:start-amount data) (map :amount (:previous-payments data)))))))))
+               (str "Current Total: $" (gstring/format money-format (apply - (:start-amount data) (map :amount (:previous-payments data)))))))))

 (defn main-view [app owner]
   (reify om/IRender


Wrap draw fn in try/catch

Wrap draw fn in try/catch

--- project-template/src/clj/sketch/dynamic.clj
+++ project-template/src/clj/sketch/dynamic.clj
@@ -38,8 +38,11 @@

       (println "setting seed to:" seed)
       (random-seed seed)
-      (background 40 2 98)
-      (actual-draw)
+
+      (try
+        (actual-draw)
+        (catch Throwable t
+          (println "Exception in draw function:" t)))

       (println "gen time:" (/ (- (System/currentTimeMillis) cur-time) 1000.0) "s")
       (let [img-filename (str "img-" img-num "-" seed ".tif")]


show comments on button hover

show comments on button hover

--- iwaswhere-web/src/cljs/iwaswhere_web/ui/entry.cljs
+++ iwaswhere-web/src/cljs/iwaswhere_web/ui/entry.cljs
@@ -295,6 +295,7 @@
             ^{:key (str "c" (:timestamp comment))}
             [journal-entry comment cfg put-fn
              (contains? new-entries (:timestamp comment))])]
-         [:div.show-comments {:on-click toggle-comments}
+         [:div.show-comments {:on-click       toggle-comments
+                              :on-mouse-enter toggle-comments}
           (let [n (count comments)]
             [:span (str "show " n " comment" (when (> n 1) "s"))])]))]))


Preserve any passed :filter-map

Preserve any passed :filter-map

Pushing for a user. We still need tests and docs around this,
specifically wrt to preserving insertion order and whether it makes
sense for WebSocketHelpyHelpertonFilter to always be last.

--- web/src/immutant/web/internal/wunderboss.clj
+++ web/src/immutant/web/internal/wunderboss.clj
@@ -59,7 +59,7 @@
         servlet? (instance? Servlet hdlr)
         opts (extract-options
                (if servlet?
-                 (assoc opts :filter-map (websocket-servlet-filter-map))
+                 (update opts :filter-map merge (websocket-servlet-filter-map))
                  opts)
                Web$RegisterOption)]
     (if servlet?


Доработка вызова фукции при ошибке в транзите, если не транзит то передает текст

--- radiolamp-6P3S/src/ixinfestor/net.cljs
+++ radiolamp-6P3S/src/ixinfestor/net.cljs
@@ -76,12 +76,20 @@
                      (fn [e]
                        (print "REQUEST ERROR")
                        (let [ee (.-target e)]
+
                          (try
                            (make-reload-if-reload-client (t/read r (.getResponseText ee)))
                            (catch js/Error e
                              (println "ERR -1 " e)))
+
                          (print-error "ERROR" ee false)
-                         (when error-fn (error-fn e)))))
+
+                         (when error-fn
+                           (let [rt (.getResponseText ee)]
+                             (try
+                               (error-fn (t/read r rt))
+                               (catch js/Error e
+                                 (error-fn rt))))))))

       (events/listen req goog.net.EventType.SUCCESS
                      (fn [e]


Fix ns form, add docstring

Fix ns form, add docstring

--- src/braid/server/bots.clj
+++ src/braid/server/bots.clj
@@ -1,11 +1,12 @@
 (ns braid.server.bots
+  "Sending notification of messages and events to bots"
   (:require
+    [braid.server.crypto :as crypto]
+    [braid.server.util :refer [->transit]]
     [org.httpkit.client :as http]
-    [taoensso.timbre :as timbre]
-    [braid.server.crypto :as crypto]
-    [braid.server.util :refer [->transit]])
+    [taoensso.timbre :as timbre])
   (:import
-    java.io.ByteArrayInputStream))
+    (java.io ByteArrayInputStream)))

 (defn send-message-notification
   [bot message]


Add update-index and latest-version tasks.

--- src/cake/tasks/search.clj
+++ src/cake/tasks/search.clj
@@ -5,16 +5,28 @@
         [clojure.string :only [join]])
   (:require [sherlock.core :as sherlock]))

-(defn- print-results [id page results]
+(defn select-repos [repos]
+  (let [repositories (:repositories *project*)]
+    (if (seq repos)
+      (select-keys repositories repos)
+      repositories)))
+
+(defn download-index [id url]
+  (when (sherlock/download-needed? url)
+    (log (str "Downloading index for " id ". This might take a bit."))
+    (sherlock/update-index url)))
+
+(defn identifier [{:keys [group-id artifact-id]}]
+  (if group-id
+    (str group-id "/" artifact-id)
+    artifact-id))
+
+(defn print-results [id page results]
   (when (seq results)
     (println " == Results from" id "-" "Showing page" page "/"
              (-> results meta :_total-hits (/ sherlock/*page-size*) Math/ceil int) "total")
-    (doseq [{:keys [group-id artifact-id version description]} results]
-      (println (str "[" (if group-id
-                          (str group-id "/" artifact-id)
-                          artifact-id)
-                    " \"" version "\"]")
-               description))
+    (doseq [{:keys [version description] :as artifact} results]
+      (println (str "[" (identifier artifact) " \"" version "\"]") description))
     (prn)))

 (deftask search
@@ -24,18 +36,42 @@
    The first time you run this task will take a bit as it has to fetch the
    lucene indexes for your maven repositories.
    Options:
-     --update -- Redownload (update) your existing lucene indexes.
      --page   -- The page number to fetch (each page is 10 results long).
      --repos  -- ids of repositories to search delimited by commas."
-  {update :update [page] :page repos :repos search :search}
-  (let [repositories (:repositories *project*)
-        repos (if repos (select-keys repositories repos) repositories)
-        page (if page (Integer. page) 1)]
+  {[page] :page repos :repos search :search}
+  (let [page (if page (Integer. page) 1)]
     (binding [sherlock/*page-size* 10]
-      (doseq [[id url] repos]
-        (when (or update (sherlock/download-needed? url))
-          (log "Downloading index for" id)
-          (sherlock/update-index url))
+      (doseq [[id url] (select-repos repos)]
+        (download-index id url)
         (print-results
          id page
-         (sherlock/get-page page (sherlock/search url (join " " search) page)))))))+         (sherlock/get-page page (sherlock/search url (join " " search) page)))))))
+
+(deftask update-repos
+  "Update maven lucene indexes."
+  "If passed arguments, they are treated as the name of maven repos to update.
+   Otherwise, update all repos."
+  {:keys [update-repos]}
+  (doseq [[id url] (select-repos update-repos)]
+    (log (str "Updating index for " id ". This might take a bit."))
+    (sherlock/update-index url)))
+
+(deftask latest-version
+  "Find the latest version of an artifact."
+  "Pass the name of a dependency and cake will search the lucene indexes for it
+   and return the latest version. You can pass --repos which is expected to be a
+   comma delimited list of repository names. If it is not passed, all repositories
+   will be searched."
+  {[term] :latest-version, repos :repos}
+  (let [repos (select-repos repos)
+        [group-id artifact-id] (.split term "/")
+        query (if artifact-id (str "g:" group-id "* AND" artifact-id) group-id)]
+    (doseq [[id url] repos] (download-index id url))
+    (let [result (first (sort-by :version (comp unchecked-negate compare)
+                                 (filter (comp #{term} identifier)
+                                         (mapcat #(sherlock/search % query 10 Integer/MAX_VALUE)
+                                                 (vals repos)))))]
+      (println
+       (if result
+         (str "[" (identifier result) " " (:version result) "]")
+         (println "Nothing was found."))))))


some more charts

some more charts

--- src/clj/ceres/curator.clj
+++ src/clj/ceres/curator.clj
@@ -195,6 +195,12 @@
          delays)
        (zip/next loc)))))

+(defn build-tree-from-source [id]
+  (let [origin (mc/find-map-by-id @db "origins" id)
+        tree (compute-impact-tree origin)]
+    {:title (:title (mc/find-map-by-id @db "articles" (:article origin)))
+     :tree tree
+     :analysis (analyze-tree tree)}))

 (defn random-tree []
   (let [origin (rand-nth (mc/find-maps @db "origins" {:source {$in news-accounts}}))
@@ -266,23 +272,35 @@
       (:_id x)
       (update-in x [:created_at] #(f/parse custom-formatter (:created_at %))) )))

+
+  (def some-tree (build-tree-from-source (ObjectId. "53fcc425e4b09b711bdec9a9" )))
+
+  ;; "53fcc425e4b09b711bdec9a9" "53fe02bbe4b09b711bdf26f2" "53f33d9ee4b0c2a12eb4a339" "53ff738fe4b09b711bdfa9c7"
+
+
   (def rand-tree (random-tree))

   (-> rand-tree :analysis :height)
+
+  (-> rand-tree :analysis :size)
+
+  (-> rand-tree :tree ffirst second :_id aprint)
+
+  (-> rand-tree :analysis aprint)

   (def g
     (let [vertices (loop [nodes []
-                          loc (:tree rand-tree)]
+                          loc (:tree some-tree)]
                      (if (zip/end? loc)
                        nodes
                        (recur
                         (if-let [node (zip/node loc)]
                           (if (= (zip/root loc) node)
                             (conj nodes (-> node :tweet :id_str))
-                            (conj nodes [(-> node :tweet :id_str) (-> loc zip/up zip/node :tweet :id_str)]))
+                            (conj nodes [(-> loc zip/up zip/node :tweet :id_str) (-> node :tweet :id_str)]))
                           nodes)
                         (zip/next loc))))]
-      (apply graph vertices)))
+      (apply lg/digraph vertices)))

   (lio/view g)

@@ -372,14 +390,32 @@
     (view (line-chart time tweet-count))
     (view (line-chart (range 24) avg-tweets-per-hour)))

-  (let [days-running (t/in-days (t/interval (t/date-time 2014 7 2) (t/date-time 2014 9 12)))
+
+  (let [days-running (t/in-days (t/interval (t/date-time 2014 7 2) (t/date-time 2014 9 22)))
         dates (take days-running (p/periodic-seq (t/date-time 2014 7 2) (t/days 1)))
         tweet-count (map #(mc/count @db "tweets" {:created_at {$gte % $lt (t/plus % (t/days 1))}}) dates)
-        time (range days-running)]
-    (view (line-chart time tweet-count)))
-
-  (->> (mc/count @db "tweets" {:created_at {$gt (t/date-time 2014 9 18)}})
-       aprint)
+        days (range  2 (inc (inc days-running)))]
+    (view (line-chart days tweet-count :title "tweet counts" :y-label "Tweet Count" :x-label "Day")))
+
+
+  ;; user posts distribution
+  (let [users (->> (mc/find-maps
+                    @db "tweets"
+                    {:created_at {$gt (t/date-time 2014 7 2)}}
+                    ["user.screen_name"])
+                   (pmap #(-> % :user :screen_name))
+                   frequencies)
+        unique-posters #(float (/ (count %) (count users)))]
+    (view (histogram (filter #(< % 51) (vals users)) :nbins 50)))
+
+
+  ;; news posts fraction
+  (let [overall-count (mc/count @db "tweets" {:created_at {$gt (t/date-time 2014 7 1)}})
+        news-count (mc/count
+                    @db "tweets" {$and [{:created_at {$gt (t/date-time 2014 7 1)}}
+                                        {:user.screen_name {$in news-accounts} }]})]
+    (aprint (float (/ news-count overall-count))))
+


add combined user-mentioned index

add combined user-mentioned index

--- src/clj/ceres/curator.clj
+++ src/clj/ceres/curator.clj
@@ -38,8 +38,8 @@
     (mc/ensure-index (:db @mongo-state) "tweets" (array-map :id_str 1))
     (mc/ensure-index (:db @mongo-state) "tweets" (array-map :retweeted_status.id_str 1))
     (mc/ensure-index (:db @mongo-state) "tweets" (array-map :in_reply_to_status_id_str 1))
-    (mc/ensure-index (:db @mongo-state) "tweets" (array-map :created_at 1))))
-
+    (mc/ensure-index (:db @mongo-state) "tweets" (array-map :created_at 1))
+    (mc/ensure-index (:db @mongo-state) "tweets" (array-map :entities.user_mentions.screen_name 1 :retweeted_status.user.screen_name 1 :in_reply_to_screen_name 1))))

 (defrecord Article [source tweet reactions])
 (defrecord Reaction [tweet reactions])


fix some assumptions around the source map dynamic vars

--- src/clj/cljs/compiler.clj
+++ src/clj/cljs/compiler.clj
@@ -112,7 +112,8 @@
      (seq? x) (apply emits x)
      (fn? x)  (x)
      :else (let [s (print-str x)]
-             (swap! *cljs-gen-col* (fn [col] (+ col (count s))))
+             (when *cljs-source-map*
+               (swap! *cljs-gen-col* (fn [col] (+ col (count s)))))
              (print s))))
   nil)

@@ -122,8 +123,10 @@
 (defn emitln [& xs]
   (apply emits xs)
   (println)
-  (swap! *cljs-gen-line* inc)
-  (reset! *cljs-gen-col* 0)
+  (when *cljs-gen-line*
+    (swap! *cljs-gen-line* inc))
+  (when *cljs-gen-col*
+    (reset! *cljs-gen-col* 0))
   nil)

 (defn ^String emit-str [expr]
@@ -225,18 +228,19 @@
         info (if (= (namespace var-name) "js")
                (name var-name)
                info)]
-    (when (and (:line env) (symbol? var-name))
-      (let [{:keys [line column]} env]
-        (swap! *cljs-source-map*
-          (fn [m]
-            (let [minfo {:gcol  @*cljs-gen-col*
-                         :gline @*cljs-gen-line*
-                         :name  var-name}]
-              (update-in m [line]
-                (fnil (fn [m]
-                        (update-in m [(or column 0)]
-                          (fnil (fn [v] (conj v minfo)) [])))
-                  (sorted-map))))))))
+    (when *cljs-source-map*
+      (when (and (:line env) (symbol? var-name))
+        (let [{:keys [line column]} env]
+          (swap! *cljs-source-map*
+            (fn [m]
+              (let [minfo {:gcol  @*cljs-gen-col*
+                           :gline @*cljs-gen-line*
+                           :name  var-name}]
+                (update-in m [line]
+                  (fnil (fn [m]
+                          (update-in m [(or column 0)]
+                            (fnil (fn [v] (conj v minfo)) [])))
+                    (sorted-map)))))))))
     (when-not (= :statement (:context env))
       (emit-wrap env (emits (munge info))))))

@@ -798,9 +802,9 @@
                    ana/*cljs-file* (.getPath ^java.io.File src)
                    *data-readers* tags/*cljs-data-readers*
                    *emitted-provides* (atom #{})
-                   *cljs-source-map* (atom (sorted-map))
+                   *cljs-source-map* (when (:source-map opts) (atom (sorted-map)))
                    *cljs-gen-line* (atom 0)
-                   *cljs-gen-col*  (atom 0)]
+                   *cljs-gen-col* (atom 0)]
            (loop [forms (forms-seq src)
                   ns-name nil
                   deps nil]


Added keyword and symbol support to reader

--- src/cljs/cljs/reader.cljs
+++ src/cljs/cljs/reader.cljs
@@ -56,16 +56,24 @@
                        (unread next-ch)
                        next-ch)))))

-(defn- string-prefix?
-  "Checks whether the character starts a string"
-  [ch]
-  (= "\"" ch))
-
 (declare read macros dispatch-macros)

 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 ;; read helpers
 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+
+(defn macro-terminating? [ch]
+  (and (not= ch "#") (not= ch "\'") (contains? macros ch)))
+
+(defn read-token
+  [rdr initch]
+  (loop [sb (gsb/StringBuffer. initch)
+         ch (read-char rdr)]
+    (if (or (nil? ch)
+            (whitespace? ch)
+            (macro-terminating? ch))
+      (do (unread rdr ch) (.toString gsb))
+      (recur (do (.append sb ch) sb) (read-char rdr)))))

 (defn- skip-line
   "Advances the reader to the end of a line. Returns the reader"
@@ -201,9 +209,9 @@

 (defn read-number
   [reader initch]
-  (loop [buffer (gstring/StringBuffer. initch)
+  (loop [buffer (gsb/StringBuffer. initch)
          ch (read-char reader)]
-    (if (or (nil? ch) (whitespace? ch) (macro? ch))
+    (if (or (nil? ch) (whitespace? ch) (contains? macros ch))
       (do
         (unread reader ch)
         (match-number (.toString buffer)))
@@ -211,7 +219,7 @@

 (defn read-string
   [reader _]
-  (loop [buffer (gstring/StringBuffer.)
+  (loop [buffer (gsb/StringBuffer.)
          ch (read-char reader)]
     (cond
      (nil? ch) (throw "EOF while reading string")
@@ -220,7 +228,20 @@
      :default (recur (do (.append buffer ch) buffer) (read-char reader)))))

 (defn read-symbol
-  [reader initch is-recursive])
+  [reader initch]
+  (let [token (read-token reader initch)]
+    (if (gstring/contains token "/")
+      (symbol (subs token 0 (.indexOf token "/"))
+              (subs (inc (.indexOf token "/")) (.length token)))
+      (symbol token))))
+
+(defn read-keyword
+  [reader initch]
+  (let [token (read-token reader (read-char reader))]
+    (if (gstring/contains token "/")
+      (keyword (subs token 0 (.indexOf token "/"))
+              (subs (inc (.indexOf token "/")) (.length token)))
+      (keyword token))))

 (defn desugar-meta
   [f]
@@ -240,34 +261,25 @@
         (with-meta o (merge (meta o) m))
         (throw "Metadata can only be applied to IWithMetas")))))

-#_(defn read-token
-  [rdr initch]
-  (let [sb (gsb/StringBuffer. initch)]
-    (loop [ch (read-char rdr)]
-      (if (or (nil? ch)
-              (whitespace? ch)
-              (macro-terminating? ch))
-        (do (unread rdr ch) s)
-        (recur (.append sb ch))))))
-
 (def macros
-  { \" read-string
-    \; not-implemented ;; never hit this
-    \' not-implemented
-    \@ not-implemented
-    \^ read-meta
-    \` not-implemented
-    \~ not-implemented
-    \( read-list
-    \) read-unmatched-delimiter
-    \[ read-vector
-    \] read-unmatched-delimiter
-    \{ read-map
-    \} read-unmatched-delimiter
-    \\ read-char
-    \% not-implemented
-    \# read-dispatch
-    })
+     { \" read-string
+       \: read-keyword
+       \; not-implemented ;; never hit this
+       \' not-implemented
+       \@ not-implemented
+       \^ read-meta
+       \` not-implemented
+       \~ not-implemented
+       \( read-list
+       \) read-unmatched-delimiter
+       \[ read-vector
+       \] read-unmatched-delimiter
+       \{ read-map
+       \} read-unmatched-delimiter
+       \\ read-char
+       \% not-implemented
+       \# read-dispatch
+       })

 (def dispatch-macros
   {"{" read-set})


Minor clean-up

Minor clean-up

--- src/cljs/drawer/core.cljs
+++ src/cljs/drawer/core.cljs
@@ -28,7 +28,7 @@
   (add-watch state :redraw-canvas
              (let [canvas (.getElementById js/document "canvas")
                    context (.getContext canvas "2d")]
-               (fn [key ref old new]
+               (fn [_ _ _ new]
                  (canvas/redraw-canvas new canvas context)))))

 (defn- app


Use core.match in board ui

Use core.match in board ui

--- src/cljs/ji/ui/board.cljs
+++ src/cljs/ji/ui/board.cljs
@@ -82,27 +82,30 @@
   (go
     (loop [board-data []
            last-set nil]
-      (if-let [[board* sets] (<! board-state)]
-        (cond
-          (= :disable board*)
-          (do (unlisten-cards! board-el)
-              (recur (doall (map unbind-card! board-data))
-                     (last sets)))
+      (match (<! board-state)
+        nil
+        board-data

-          (= :enable board*)
-          (do (listen-cards! board-el)
-              (recur (doall (map #(bind-card! card-sel %) board-data))
-                     (last sets)))
+        :disable
+        (do (unlisten-cards! board-el)
+            (recur (doall (map unbind-card! board-data))
+                   last-set))

-          (set? board*)
-          (let [board (set (map :card board-data))
-                -cards (s/difference board board*)
-                +cards (s/difference board* board)]
-            (recur (-> board-data
-                       (remove-cards! -cards)
-                       (add-cards! board-el card-sel +cards))
-                   (last sets))))
-        board-data))))
+        :enable
+        (do (listen-cards! board-el)
+            (recur (doall (map #(bind-card! card-sel %) board-data))
+                   last-set))
+
+        [board sets]
+        (let [old-board (set (map :card board-data))
+              -cards (s/difference old-board board)
+              +cards (s/difference board old-board)]
+          (recur (-> board-data
+                     (remove-cards! -cards)
+                     (add-cards! board-el card-sel +cards))
+                 (last sets)))
+        :else
+        (recur board-data last-set)))))

 (defn create! [container board-state card-sel]
   (let [board-el (board-tmpl)]


Improve compiler; add documentation

Improve compiler; add documentation

--- src/cljx/revue/riley.cljx
+++ src/cljx/revue/riley.cljx
@@ -198,67 +198,125 @@
   `more?`.  Otherwise compile the first form with `val?` set to
   `false` and `more?` set to `true`, since the value is ignored and
   there are more forms to compile."
-  (cond (empty? forms)
-        (comp-const nil val? more?)
-        (util/singleton? forms)
-        (comp (first forms) env val? more?)
-        :else
-        (gen-seq (comp (first forms) env false true)
-                 (comp-sequence (rest forms) env val? more?))))
+  (cond
+   ;; An empty sequence evaluates to `nil`.
+   (empty? forms)
+   (comp-const nil val? more?)
+   ;; A sequence containing a single form is equivalent to this form.
+   (util/singleton? forms)
+   (comp (first forms) env val? more?)
+   ;; If we have more than one form in the sequence we compile the
+   ;; first one for effect and recurse on the rest.  This means that,
+   ;; e.g., constants appearing in the sequence will not generate any
+   ;; code.
+   :else
+   (gen-seq (comp (first forms) env false true)
+            (comp-sequence (rest forms) env val? more?))))

 (defn comp-parameters [forms env]
+  "Compile each member of `forms` and push the result on the stack.
+  In contrast to `comp-sequence` each parameter is evaluated for
+  value."
   (if (empty? forms)
     ()
     (gen-seq (comp (first forms) env true true)
              (comp-parameters (rest forms) env))))

 (defn comp-lambda
+  "Compile a lambda abstraction.  This is done by compiling the body
+  of the function as sequence in a new environment augmented with the
+  arguments of the function.  If a `name` is supplied it is used as
+  name of the function for debugging purposes, but it is not bound as
+  a variable."
   ([args body env]
      (comp-lambda '%anonymous-lambda args body env))
   ([name args body env]
-     ;; TODO: Need to invoke the assembler
      (binding [*current-function* name]
-       (vm/assemble (vm/make-fun :env env :args args
-                              :code (gen-seq (gen-args name args)
-                                             (comp-sequence
-                                              body
-                                              (conj env (vec args))
-                                              true false)))))))
+       (vm/make-fun :env env :args args
+                    :code (gen-seq (gen-args name args)
+                                   (comp-sequence
+                                    body
+                                    (conj env (vec args))
+                                    true false))))))

 ;;; Support for macros
 ;;; ==================

-(def macro-environment (atom {}))
+;;; We don't want to implement many forms that are directly
+;;; manipulated by the compiler.  Therefore we rely on macros to
+;;; implement most of the syntax of the language.
+
+(def macro-environment
+  "The macro enironment holds the compile-time bindings of macros,
+  i.e., function that take a source code form and an environment and
+  return a new source code form to be compiled.  We currently only
+  support global macros; therefore we only need a flat, global
+  environment for macros."
+  (atom {}))

 (defn riley-macro? [op env]
+  "Returns `true` if `op` has a macro binding in `env`.  Since we
+  don't support lexical macros for the time being, we ignore the
+  environment and just check whether the name is bound in
+  `macro-environment`."
   (get @macro-environment op false))

 (defn expand-riley-macro [op args env]
+  "Expand the macro `op` when given arguments `args`.  This may only
+  be called if `op` is known to be a macro."
   (let [expander (get @macro-environment op)]
     (assert expander (str op " has no macro expander."))
     (expander args env)))

-(defn riley-macroexpand-1 [[op & args] & [env]]
-  (expand-riley-macro op args env))
-
-(defn riley-macroexpand [[op & args] & [env]]
-  (let [result (expand-riley-macro op args env)]
+(defn macroexpand-1 [[op & args :as form] env]
+  "Macroexpand `form` once if it is a macro, or return it unchanged if
+  it is not."
+  (if (riley-macro? op env)
+    (expand-riley-macro op args env)
+    form))
+
+(defn macroexpand [form env]
+  "Repeatedly macroexpand `form` until its outermost operator is no
+  longer a macro.  Subexpressions may still be macros, i.e.,
+  `macroexpand` is not a tree walker."
+  (let [result (macroexpand-1 form env)]
     (if (riley-macro? (first result) env)
       (recur result env)
       result)))

 (defn define-riley-macro [name expander]
+  "Define a new macro by giving its name and an expander function that
+  takes a source form and an environment."
   (swap! macro-environment assoc name expander))

+;;; Expand a top-level `define` form by expanding either in a simple
+;;; `set!` if the defined value is a symbol, or by building a new
+;;; lambda-term if the defined value is a list.
+
 (define-riley-macro 'define
-  (fn [[name & forms] env]
+  (fn [[name & forms :as definition] env]
     (if (symbol? name)
       (do
-        (assert (util/singleton? forms))
+        (assert (util/singleton? forms)
+                (str "Definition for " name " is not a single value."))
         (list 'set! name (first forms)))
-      (list 'set! (first name)
-            (list 'lambda (first name) (rest name)
-                  (util/maybe-add 'begin forms nil))))))
+      (let [fun-name (first name)
+            args (rest name)]
+        (assert (symbol? fun-name)
+                (str "Cannot define a function named " fun-name "."))
+        (assert (sequential? args)
+                (str "Parameter list of " fun-name " is not a sequence."))
+        (assert (every? symbol args)
+                (str "Parameters of " fun-name " must all be symbols."))
+        (list 'set! fun-name
+              (list 'lambda fun-name args
+                    (util/maybe-add 'begin forms nil)))))))
+
+;;; `letrec` binds name to values, similar to `let`, however all
+;;; values in a `letrec` are in scope of all variables.  This is
+;;; implemented by first setting the value of all variables to `nil`
+;;; and then assigning the correct values inside the contour
+;;; established inside the variable bindings.

 (define-riley-macro 'letrec
   (fn [[bindings & body] env]
@@ -266,6 +324,10 @@
            (list* 'begin
                   (map #(list 'set! (first %) (second %)) bindings))
            body)))
+
+;;; `let` is the most commonly used binding form. Normal `let`s are
+;;; easily translated into lambdas; named let forms that are very
+;;; convenient for loops are translated into `letrec`s.

 (define-riley-macro 'let
   (fn [[bindings & body] env]
@@ -438,21 +500,32 @@
                         :or {env (util/env) assemble? true}}]
   (reset! label-counter 0)
   (try
-    (comp-lambda 'top-level () (list form) env)
+    (let [fun (comp-lambda 'top-level () (list form) env)]
+      (if assemble?
+        (vm/assemble fun)
+        fun))
     (catch #+clj java.lang.Exception #+cljs js/Error e
            :compiler-error)))

 (defn compile-all [forms & {:keys [env assemble?]
                             :or {env (util/env) assemble? true}}]
   (try
-    (comp-lambda 'top-level () forms env)
+    (let [fun (comp-lambda 'top-level () forms env)]
+      (if assemble?
+        (vm/assemble fun)
+        fun))
     (catch #+clj java.lang.Exception #+cljs js/Error e
            :compiler-error)))

 (defn compile-str [string & {:keys [env assemble?]
                              :or {env (util/env) assemble? true}}]
   (try
-    (comp-lambda 'top-level () (util/read-program-from-string string) env)
+    (let [fun (comp-lambda
+               'top-level ()
+               (util/read-program-from-string string) env)]
+      (if assemble?
+        (vm/assemble fun)
+        fun))
     (catch #+clj java.lang.Exception #+cljs js/Error e
            :compiler-error)))


acquire button: make a new album when image is incompatible with the current album

git-svn-id: 03a8048b5ee8463be5048a3801110fb50f378627@6310 d0ab736e-dc22-4aeb-8dc9-08def0aa14fd

--- acqEngine/src/org/micromanager/acq_engine.clj
+++ acqEngine/src/org/micromanager/acq_engine.clj
@@ -133,8 +133,8 @@
 ;; metadata

 (defn annotate-image [img event state]
-  (TaggedImage. img (JSONObject.
-    (merge
+  {:pix img
+   :tags (merge
       (map-config (core getSystemStateCache))
       {
        "AxisPositions" (when-let [axes (get-in event [:position :axes])] (JSONObject. axes))
@@ -156,7 +156,10 @@
        "UUID" (UUID/randomUUID)
        "Width"  (state :init-width)
        "ZPositionUm" (state :last-z-position)
-      }))))
+      })})
+
+(defn make-TaggedImage [annotated-img]
+  (TaggedImage. (:pix annotated-img) (JSONObject. (:tags annotated-img))))

 ;; acq-engine

@@ -259,7 +262,7 @@
                 :snap (collect-snap-image)
                 :init-burst (collect-burst-image)
                 :collect-burst (collect-burst-image))]
-    (.put out-queue (annotate-image image event @state))))
+    (.put out-queue (make-TaggedImage (annotate-image image event @state)))))

 (defn compute-z-position [event]
   (if-let [z-drive (:z-drive event)]
@@ -417,34 +420,49 @@

 ;; acquire button

-(def current-acquire-win (atom nil))
-
-(defn acquire-single [position-index]
+(def current-album (atom nil))
+
+(defn compatible-image? [album annotated-image]
+  (let [tags1 (:first-image-tags album)
+        tags2 (:tags annotated-image)
+        matching-keys ["Width" "Height" "PixelType"]]
+    (= (select-keys tags1 matching-keys)
+       (select-keys tags2 matching-keys))))
+
+(defn create-new-album [first-image]
+  (let [summary {:interval-ms 0.0, :use-autofocus false, :autofocus-skip 0,
+                 :relative-slices true, :keep-shutter-open-slices false, :comment "",
+                 :prefix "Untitled", :root "",
+                 :time-first false, :positions (), :channels (), :slices-first true,
+                 :slices nil, :numFrames 0, :keep-shutter-open-channels false,
+                 :zReference 0.0, :frames (), :save false}
+            summary-metadata (make-summary-metadata summary)
+	          cache (MMImageCache. (TaggedImageStorageRam. summary-metadata))
+	          display (doto (VirtualAcquisitionDisplay. "" true false)
+	                        (.setCache cache) .initialize)]
+	          (reset! current-album {:cache cache :display display
+	                                 :first-image-tags (:tags first-image)
+	                                 :count 0})))
+
+(defn acquire-single []
   (core snapImage)
   (let [w (core getImageWidth)
         h (core getImageHeight)
-        summary {:interval-ms 0.0, :use-autofocus false, :autofocus-skip 0,
-                 :relative-slices true, :keep-shutter-open-slices false, :comment "",
-                 :prefix "Untitled", :root "/Users/arthur/AcquisitionData",
-                 :time-first false, :positions (), :channels (), :slices-first true,
-                 :slices nil, :numFrames 0, :keep-shutter-open-channels false,
-                 :zReference 0.0, :frames (), :save false}
-        event   {:position-index position-index, :position -1,
+        event   {:position-index 2, :position -1,
                  :frame-index 0, :slice 0.0, :channel-index 0, :slice-index 0, :frame 0
                  :channel {:name (core getCurrentConfig (core getChannelGroup))},
                  :exposure (core getExposure), :relative-z true,
                  :task :snap, :z-drive (core getFocusDevice), :wait-time-ms 0}
         state   {:init-width w :init-height h}
-        summary-metadata (make-summary-metadata summary)
         tagged-image (annotate-image (collect-snap-image) event state)]
-	  (if-not @current-acquire-win
-	    (let [cache (MMImageCache. (TaggedImageStorageRam. summary-metadata))
-	          display (doto (VirtualAcquisitionDisplay. "" true false)
-	                        (.setCache cache) .initialize)]
-	          (reset! current-acquire-win {:cache cache :display display})))
-	  (let [{:keys [display cache]} @current-acquire-win]
-      (.putImage cache tagged-image)
-      (doto display (.showImage tagged-image)))))
+	  (if-not (and @current-album (compatible-image? @current-album tagged-image))
+	    (create-new-album tagged-image))
+	  (let [{:keys [display cache]} @current-album
+	        myTaggedImage (make-TaggedImage
+	          (assoc-in tagged-image [:tags "PositionIndex"] (@current-album :count)))]
+      (.putImage cache myTaggedImage)
+      (doto display (.showImage myTaggedImage))
+      (swap! current-album update-in [:count] inc))))

 ;; java interop

@@ -501,16 +519,6 @@
 (defn -nextWakeTime [this]
   (or (:next-wake-time @(.state this)) -1))

-(defn -acquireSingle [this]
-  (prepare-state this)
-  (let [out-queue (GentleLinkedBlockingQueue.)
-        event {:close-shutter true, :frame-index 0, :position-index 0,
-               :autofocus false, :channel-index 0, :slice-index 0,
-               :exposure nil, :relative-z true, :task :snap, :z-drive "Z",
-               :wait-time-ms 0}]
-    (execute (make-event-fns event out-queue))
-    (cleanup)))
-
 ;; testing

 (defn create-acq-eng []


Update ns docstring

Update ns docstring

Fix #350

--- planck-cljs/src/planck/repl_resources.cljs
+++ planck-cljs/src/planck/repl_resources.cljs
@@ -9,13 +9,15 @@
            :doc   "You must currently use the ns form only with the following caveats

     * You must use the :only form of :use
-    * :require supports :as and :refer
-      - both options can be skipped
+    * :require supports :as, :refer, and :rename
+      - all options can be skipped
       - in this case a symbol can be used as a libspec directly
         - that is, (:require lib.foo) and (:require [lib.foo]) are both
           supported and mean the same thing
+      - :rename specifies a map from referred var names to different
+        symbols (and can be used to prevent clashes)
       - prefix lists are not supported
-    * The only option for :refer-clojure is :exclude
+    * The only options for :refer-clojure are :exclude and :rename
     * :import is available for importing Google Closure classes
       - ClojureScript types and records should be brought in with :use
         or :require :refer, not :import ed


core: true?

core: true?

--- core.clj
+++ core.clj
@@ -359,3 +359,9 @@
   {:tag Bool
    :added "1.0"}
   [x] (=* x false))
+
+(defn true?
+  "Returns true if x is the value true, false otherwise."
+  {:tag Bool
+   :added "1.0"}
+  [x] (=* x true))


todomvc: make it friendly to Replay mode by ignoring loading from storage when mode is active

--- examples/todomvc/src/app/spec.cljs
+++ examples/todomvc/src/app/spec.cljs
@@ -5,6 +5,15 @@
             [middleware.schema :as schema]
             [middleware.history :as h]
             [middleware.persistence :as persistence]))
+
+(defn -wrap-load-from-storage
+  "Prohibits loading from storage in replay mode.
+  Without this hack replayed actions would make no effect since replaying happens before app loads model from storage."
+  [load-from-storage]
+  (fn wrapped-load-from-storage
+    [model loaded-model dispatch-signal]
+    (when (not (-> @model :middleware.devtools/debugger :replay-mode?))
+      (load-from-storage model loaded-model dispatch-signal))))

 (defn new-spec
   [history storage storage-key todo-titles]
@@ -15,6 +24,8 @@

       ; Debugger deals with persistence itself, so we have to blacklist it here to get rid of loading conflicts.
       ; Token is blacklisted because on start we want the app to read current token from the urlbar instead of storage.
-      (persistence/add storage storage-key {:blacklist #{:middleware.devtools/debugger ::h/token}})
+      (persistence/add storage storage-key {:load-wrapper -wrap-load-from-storage
+                                            :blacklist    #{:middleware.devtools/debugger
+                                                            ::h/token}})

       (h/add history)))


Use compliance test for filestore.

Use compliance test for filestore.

--- test/konserve/filestore_test.clj
+++ test/konserve/filestore_test.clj
@@ -14,21 +14,8 @@
           _      (spit "/tmp/foo" (range 1 10))
           _      (delete-store folder)
           store  (<!! (new-fs-store folder))]
-      (testing "edn" (is (= (<!! (get store :foo))
-                            nil))
-               (<!! (assoc-in store [:foo] {:bar :baz}))
-               (is (= (<!! (get store :foo))
-                      {:bar :baz}))
-               (<!! (assoc-in store [:baz] 0))
-               (<!! (update-in store [:baz] inc))
-               (is (= (<!! (get store :baz)) 1))
-               (is (= (<!! (keys store))
-                      #{(<!! (get-meta store :foo)) (<!! (get-meta store :baz))}))
-               (<!! (dissoc store :foo))
-               (is (= (<!! (get store :foo))
-                      nil))
-               (is (= (<!! (keys store))
-                      #{(<!! (get-meta store :baz))})))
+      (testing "compliance test"
+        (compliance-test store))
       (testing "Binary"
         (testing "ByteArray"
           (let [res-ch (chan)]


add QUIT tests

add QUIT tests

--- test/subrosa/test/connection.clj
+++ test/subrosa/test/connection.clj
@@ -125,3 +125,25 @@
     (transmit s "USER dan 0 * :Dan Larkin")
     (transmit s "THISCOMMANDDOESNOTEXIST")
     (is (received? s #":Unknown command"))))
+
+(deftest quit-command
+  (with-connection s1
+    (with-connection s2
+      (transmit s1 "NICK dan")
+      (transmit s1 "USER dan 0 * :Dan Larkin")
+      (is (received? s1 #"Welcome to the .* dan$"))
+      (transmit s2 "NICK dan2")
+      (transmit s2 "USER dan 0 * :Dan Larkin")
+      (is (received? s2 #"Welcome to the .* dan2$"))
+      ;; does dan show up in users list?
+      (transmit s2 "WHOIS dan")
+      (is (received? s2 #"dan"))
+      ;; tell dan to disconnect
+      (transmit s1 "QUIT")
+      (is (received? s1 #"QUIT :Client Quit"))
+      ;; attempt to read, to verify socket is closed:
+      (is (= -1 (.read (:in s1))))
+      (Thread/sleep 1000)
+      ;; make sure dan isn't in the user list anymore
+      (transmit s2 "WHOIS dan")
+      (is (received? s2 #"401 dan2 dan :No such nick/channel")))))


Make todomvc look like it should

Make todomvc look like it should

--- examples/todomvc/src/todomvc.cljs
+++ examples/todomvc/src/todomvc.cljs
@@ -18,7 +18,9 @@
 (defn complete-all [v] (swap! todos mmap map #(assoc-in % [1 :done] v)))
 (defn clear-done [] (swap! todos mmap remove #(get-in % [1 :done])))

-(dotimes [x 5] (add-todo (str "Some todo " x)))
+(add-todo "Rename Cloact to Reagent")
+(add-todo "Add undo demo")
+(complete-all true)

 (defn todo-input [{:keys [title on-save on-stop]}]
   (let [val (atom title)
@@ -75,24 +77,27 @@
       (let [items (vals @todos)
             done (->> items (filter :done) count)
             active (- (count items) done)]
-        [:section#todoapp
-         [:header#header
-          [:h1 "todos"]
-          [todo-input {:id "new-todo"
-                       :placeholder "What needs to be done?"
-                       :on-save add-todo}]]
-         [:section#main
-          [:input#toggle-all {:type "checkbox" :checked (zero? active)
-                              :on-change #(complete-all (pos? active))}]
-          [:label {:for "toggle-all"} "Mark all as complete"]
-          [:ul#todo-list
-           (for [todo (filter (case @filt
-                                :active (complement :done)
-                                :done :done
-                                :all identity) items)]
-             [todo-item {:key (:id todo) :todo todo}])]]
-         [:footer#footer
-          [todo-stats {:active active :done done :filt filt}]]
+        [:div
+         [:section#todoapp
+          [:header#header
+           [:h1 "todos"]
+           [todo-input {:id "new-todo"
+                        :placeholder "What needs to be done?"
+                        :on-save add-todo}]]
+          (when (-> items count pos?)
+            [:div
+             [:section#main
+              [:input#toggle-all {:type "checkbox" :checked (zero? active)
+                                  :on-change #(complete-all (pos? active))}]
+              [:label {:for "toggle-all"} "Mark all as complete"]
+              [:ul#todo-list
+               (for [todo (filter (case @filt
+                                    :active (complement :done)
+                                    :done :done
+                                    :all identity) items)]
+                 [todo-item {:key (:id todo) :todo todo}])]]
+             [:footer#footer
+              [todo-stats {:active active :done done :filt filt}]]])]
          [:footer#info
           [:p "Double-click to edit a todo"]]]))))


Focus management #38 - :focus-traversal-order performance optimization: avoid extra re-sorting of container components by default

--- flatguicore/src/flatgui/focus.clj
+++ flatguicore/src/flatgui/focus.clj
@@ -93,17 +93,20 @@
 ;;; Sorts focusable components so that they are traversed in left->right, up->down direction.
 ;;; To make such an order, arranges components in a vector of horizontal "lines".
 ;;;
-;;;  NOTE:
-;;; This implementation is slow. For containers that have frequenlty moving children, it's better
-;;; to wrap it into another function that would call this one in rare cases (e.g. only when :children
-;;; change)
-(fg/defevolverfn :focus-traversal-order
+;;; NOTE: This implementation is slow. Use only if explicitly needed to follow changes in child positions
+(fg/defevolverfn sort-focus-traversal-order-evolver :focus-traversal-order
   (let [accepting-children (get-accepting-children component)]
     (if (pos? (count accepting-children))
       (let [lines (group-by-lines component accepting-children)
             result (mapcat (fn [i] (map :id (nth lines i))) (range 0 (count lines)))]
         result)
       [])))
+
+(fg/defevolverfn :focus-traversal-order
+  (let [reason (fg/get-reason)]
+    (if (or (nil? reason) (= reason [:this]))
+      (sort-focus-traversal-order-evolver component)
+      old-focus-traversal-order)))

 (fg/defaccessorfn get-child-ids-in-traversal-order [component]
   (if-let [focus-traversal-order (get-property component [:this] :focus-traversal-order)]


Formatting

Formatting

--- test/yada/atom_resource_test.clj
+++ test/yada/atom_resource_test.clj
@@ -11,15 +11,15 @@

 (deftest atom-test
   (testing "atom"
-      (let [resource (atom {:name "Frank"})
-            handler (yada resource)
-            request (request :get "/")
-            response @(handler request)]
+    (let [resource (atom {:name "Frank"})
+          handler (yada resource)
+          request (request :get "/")
+          response @(handler request)]

-        (given response
-          :status := 200
-          :headers :> {"content-length" 16
-                       "content-type" "application/edn"}
-          :body :? string?)
+      (given response
+        :status := 200
+        :headers :> {"content-length" 16
+                     "content-type" "application/edn"}
+        :body :? string?)

-        )))
+      )))


Clear up documentation.

Clear up documentation.

--- project/analyze-data/src/analyze_data/knn/core.clj
+++ project/analyze-data/src/analyze_data/knn/core.clj
@@ -9,9 +9,9 @@
    [--x2--]
    ...]

-  y is a vector
+  y is a core.matrix vector

-  Return a vector of [distance-from-x1 distance-from-x2 ...]."
+  Return a sequence of [distance-from-x1 distance-from-x2 ...]."
   [X y]
   (m/div
     (m/sub 1 (m/mmul X y))
@@ -26,9 +26,9 @@
    [--x2--]
    ...]

-  y is a vector
+  y is a core.matrix vector

-  Return a vector of [distance-from-x1 distance-from-x2 ...]."
+  Return a sequence of [distance-from-x1 distance-from-x2 ...]."
   [X y]
   (map (partial m/distance y) X))

@@ -40,7 +40,7 @@
    [--x2--]
    ...]

-  y is a vector
+  y is a core.matrix vector

   Options
     :k (default 3)


figwheel.main: be clearer about where to place index.html

--- figwheel-repl/src/figwheel/server/ring.clj
+++ figwheel-repl/src/figwheel/server/ring.clj
@@ -149,7 +149,7 @@

                        "
This page is currently hosting your REPL and application evaluation environment. "
                        "Validate the connection by typing (js/alert \"Hello Figwheel!\") in the REPL.
"
-                       "
To provide your own custom page, place an index.html file on the server path.
"
+                       "
To provide your own custom page, place an index.html file on the server path (normally resources/public/index.html).
"
                        "
"
                        "<!DOCTYPE html>\n"
                        "<html>\n"


age estimation of weibo

age estimation of weibo

--- src/Miscellaneous/newware.clj
+++ src/Miscellaneous/newware.clj
@@ -620,26 +620,50 @@
   (reduce #(apply conj %1 (keys %2)) #{} coll))

-(def abcd (mc/find-maps "shejian2_weibo_realtime_detaileduser"))
-
-(doall (get-keys abcd))
+;(def abcd (mc/find-maps "car_weibo_history_detaileduser"))
+
+#_(doall (get-keys abcd))

 (defn accumulator
   [the-key coll]
-  (let [func (fn [x] (->> x frequencies (clojure.core/sort #(> (val %1) (val %2)))))]
+  (let [func (fn [x] (->> x frequencies (clojure.core/sort #(> (val %1) (val %2)))))
+        coll2 (->> coll (map #(dissoc % :_systime :_id)) distinct)]
     (loop [c coll]
-      (if-not (nil? (first c))
-        (if (vector? (first c))
-          (func (mapcat the-key coll))
-          (func (map the-key coll)))
-        (recur (rest coll))))))
-
-(accumulator :性别 abcd)
-
-
-
-
-
+      (when-not (empty? c)
+        (if-not (nil? (get (first c) the-key))
+          (if (vector? (get (first c) the-key))
+            (func (mapcat the-key coll2))
+            (func (map the-key coll2)))
+          (recur (rest c)))))))
+
+
+
+(accumulator :高中 abcd)
+
+(defn age-estimated-utility
+  [entry]
+  (let [regex #(or (re-find #"\(([^\(年\)]+)年\)" %) (re-find #"(\d+)年\d+月\d+日" %))
+        since #(->> (regex %)
+                    second
+                    read-string
+                    (- (t/year (t/today))))
+        edu [:生日 :高中 :中专技校 :初中 :小学 :大学]
+        edu-age {:生日 0 :高中 15 :中专技校 15 :初中 12 :小学 6 :大学 18}
+        birth (get entry :生日)]
+    (loop [a edu]
+      (let [item (get entry (first a))]
+        (when-not (empty? a)
+          (if (and (not (nil? item)) (not (nil? (regex item))))
+            (+ (get edu-age (first a)) (since item))
+            (recur (rest a))))))))
+
+(frequencies (remove nil? (map age-estimated-utility abcd)))
+
+
+
+(re-find #"\(([^\(年\)]+)年\)" "(1985年)春天")
+
+(re-find #"(\d+)年\d+月\d+日" "1985年10月5日")
 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;working zone;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

 (mg/connect! {:host "192.168.1.184" :port 7017})


Implemented command line arguments

Implemented command line arguments


add intercom quote

add intercom quote

--- frontend/components/landing_b.cljs
+++ frontend/components/landing_b.cljs
@@ -145,9 +145,9 @@
               :position 0}
     :intercom {:name "Intercom"
                :logo ""
-               :quote "Sed dolor dolor, accumsan et lacinia bibendum, molestie eget est. Ut et aliquet quam, a molestie felis. Donec dignissim mi eget nibh iaculis convallis."
-               :cite "Tony Stark"
-               :cite-title "Engineer"
+               :quote "We love Circle at Intercom. Having a record of the full test suite for every push makes it easy for the code reviewer."
+               :cite "Ciaran Lee"
+               :cite-title "CTO"
                :cite-avatar "/img/outer/stories/john.jpg"
                :tools #{:node :javascript}
                :position 1}
@@ -169,7 +169,7 @@
                   :position 3}
     :gocardless {:name "GoCardless"
                  :logo ""
-                 :quote "CircleCI lets us develop and ship better code, faster. Its awesome parallelisation feature allows us to test more thoroughly and deploy with confidence."
+                 :quote "CircleCI lets us develop and ship better code, faster. Its awesome parallelisation feature allows us to deploy with confidence."
                  :cite "Alan Kennedy"
                  :cite-title "Engineer"
                  :cite-avatar "/img/outer/stories/arthur.jpg"


add deprecated meta

add deprecated meta

--- src/java_time/convert.clj
+++ src/java_time/convert.clj
@@ -82,7 +82,7 @@
                       (IllegalArgumentException.)
                       (throw))))))

-(defn ^java.util.Date to-java-date
+(defn ^:deprecated ^java.util.Date to-java-date
   "Converts a date entity to a `java.util.Date`.

   *Deprecated*:
@@ -93,7 +93,7 @@
   (if (instance? Date o) o
     (Date/from (jt.t/instant o))))

-(defn ^java.sql.Date to-sql-date
+(defn ^:deprecated ^java.sql.Date to-sql-date
   "Converts a local date entity to a `java.sql.Date`.

   *Deprecated*:
@@ -102,7 +102,7 @@
   instead."
   [o] (java.sql.Date/valueOf (jt.l/local-date o)))

-(defn ^java.sql.Timestamp to-sql-timestamp
+(defn ^:deprecated ^java.sql.Timestamp to-sql-timestamp
   "Converts a date entity to a `java.sql.Timestamp`.

   *Deprecated*:


Tweak web cache settings

Tweak web cache settings

--- src/kevin/routes/home.clj
+++ src/kevin/routes/home.clj
@@ -5,23 +5,24 @@
             [kevin.core :as s]
             [kevin.views :as views]))

-(noir.util.cache/set-timeout! 10)
-(noir.util.cache/set-size! 500)
+(noir.util.cache/set-timeout! 600) ; 10 minutes
+(noir.util.cache/set-size! 1000)

 (defn home []
   (cache! :home
     (views/main-template
       :body (views/form "Kevin Bacon" nil nil))))

-(defn- cache-key [search]
-  (mapv :actor-id (first search)))
+(defn- cache-key [search hard-mode]
+  (conj (mapv :actor-id (first search)) hard-mode))

 (defn search [context {:keys [person1 person2 hard-mode] :as params}]
   (let [db (-> context :db :conn d/db)
-        search (s/search db person1 person2)]
+        search (s/search db person1 person2)
+        hard-mode? (boolean (seq hard-mode))]
     (if (= 1 (count search))
-      (cache! (cache-key search)
-        (views/results-page (s/annotate-search db (first search) (seq hard-mode))))
+      (cache! (cache-key search hard-mode?)
+        (views/results-page (s/annotate-search db (first search) hard-mode?)))
       (views/disambiguate search params))))

 (defn home-routes [context]