Подшаманил вывод изображений

Подшаманил вывод изображений

--- src-cljs/ixinfestor/omut.cljs
+++ src-cljs/ixinfestor/omut.cljs
@@ -2494,43 +2494,44 @@
       {:i 0})
     om/IRenderState
     (render-state [_ {:keys [i]}]
-      (dom/div
-       nil
-       (dom/div
-        #js {:style #js {:textAlign "right"}}
-        (dom/div #js {:className "btn-group"}
-                 (ui-button {:type :default
-                             :size :lg
-                             :on-click (fn [_]
-                                         (om/update-state!
-                                          own :i
-                                          #(let [i (dec %)]
-                                             (if (< i 0) (dec (count @app)) i)))
-                                         1)
-                             :text (dom/span nil
-                                             (dom/span #js {:className "glyphicon glyphicon-chevron-left"
-                                                            :aria-hidden "true"}))
-                             })
-                 (ui-button {:type :default
-                             :size :lg
-                             :on-click (fn [_]
-                                         (om/update-state!
-                                          own :i
-                                          #(let [i (inc %)]
-                                             (if (= i (count @app)) 0  i)))
-                                         1)
-                             :text (dom/span nil
-                                             (dom/span #js {:className "glyphicon glyphicon-chevron-right"
-                                                            :aria-hidden "true"}))
-                             })
-                 ))
-       (dom/br nil)
-       (if (empty? @app)
-         (dom/h1 nil "Изображений нет")
+      (if (empty? @app)
+        (dom/h2 nil "Изображений нет")
+        (dom/div
+         #js {}
+         (dom/b #js {:style #js {:fontSize "26px"}} "Изображение " (inc i) " из " (count @app))
+         (dom/div #js {:className "btn-group" :style #js {:float "right"}}
+                  (ui-button {:type :default
+                              :size :lg
+                              :on-click (fn [_]
+                                          (om/update-state!
+                                           own :i
+                                           #(let [i (dec %)]
+                                              (if (< i 0) (dec (count @app)) i)))
+                                          1)
+                              :text (dom/span nil
+                                              (dom/span #js {:className "glyphicon glyphicon-chevron-left"
+                                                             :aria-hidden "true"}))
+                              })
+                  (ui-button {:type :default
+                              :size :lg
+                              :on-click (fn [_]
+                                          (om/update-state!
+                                           own :i
+                                           #(let [i (inc %)]
+                                              (if (= i (count @app)) 0  i)))
+                                          1)
+                              :text (dom/span nil
+                                              (dom/span #js {:className "glyphicon glyphicon-chevron-right"
+                                                             :aria-hidden "true"}))
+                              }))
+         (dom/br nil)
+         (dom/br nil)
          (dom/div
           #js {:className "thumbnail"}
           (dom/img #js {:className ""
-                        :src (get-in @app [i :path] "")})))))))
+                        :src (get-in @app [i :path] "")}))
+         (dom/h2 nil (get-in @app [i :top_description] ""))
+         (dom/p nil (get-in @app [i :description] "")))))))

 ;; END Thumbs
 ;;..................................................................................................
@@ -2751,28 +2752,30 @@
   (reify
     om/IRender
     (render [_]
-      (ui-panel
-       {:heading " Список файлов"
-        :badge (str (count @app))
-        :heading-glyphicon "folder-open"
-        :type :primary
-        :after-body
-        (ui-table
-         {:hover? true
-          :bordered? true
-          :striped? true
-          :responsive? true
-          :tbody
-          (->> @app
-               (map (fn [{:keys [filename path top_description description size]}]
-                      (dom/tr nil
-                              (dom/td nil
-                                      (ui-media {:href path
-                                                 :media-object (ui-glyphicon "file" nil "5em")
-                                                 :heading filename
-                                                 :heading-2 top_description
-                                                 :body (dom/p nil description)})))))
-               (apply dom/tbody nil))})}))))
+      (if (empty? @app)
+        (dom/h2 nil "Нет файлов")
+        (ui-panel
+         {:heading " Список файлов"
+          :badge (str (count @app))
+          :heading-glyphicon "folder-open"
+          :type :primary
+          :after-body
+          (ui-table
+           {:hover? true
+            :bordered? true
+            :striped? true
+            :responsive? true
+            :tbody
+            (->> @app
+                 (map (fn [{:keys [filename path top_description description size]}]
+                        (dom/tr nil
+                                (dom/td nil
+                                        (ui-media {:href path
+                                                   :media-object (ui-glyphicon "file" nil "5em")
+                                                   :heading filename
+                                                   :heading-2 top_description
+                                                   :body (dom/p nil description)})))))
+                 (apply dom/tbody nil))})})))))

 ;; END files
 ;;..................................................................................................


set up a channel to read from datomic transactions queue

--- src/pc/datomic.clj
+++ src/pc/datomic.clj
@@ -1,5 +1,6 @@
 (ns pc.datomic
-  (:require [clojure.tools.logging :refer (infof)]
+  (:require [clojure.core.async :as async]
+            [clojure.tools.logging :refer (infof)]
             [datomic.api :refer [db q] :as d])
   (:import java.util.UUID))

@@ -57,8 +58,18 @@
   (let [{:keys [a e v tx added]} datom]
     [(if added :db/add :db/retract) e a v]))

+(defonce tx-report-ch (async/chan (async/sliding-buffer 1024)))
+
+(defn setup-tx-report-ch [conn]
+  (let [queue (d/tx-report-queue conn)]
+    (future (while true
+              (let [transaction (.take queue)]
+                (async/put! tx-report-ch transaction))))))
+
 (defn init []
   (infof "Creating default database if it doesn't exist: %s"
          (d/create-database default-uri))
   (infof "Ensuring connection to default database")
-  (infof "Connected to: %s" (conn)))
+  (infof "Connected to: %s" (conn))
+  (infof "forwarding report-queue to tx-report-ch")
+  (setup-tx-report-ch (conn)))


improve docstr

improve docstr

--- src/qttt/game.cljs
+++ src/qttt/game.cljs
@@ -64,7 +64,10 @@
            v)))

 (defn cycle-search
-  "Return a seq of cell cycles discovered"
+  "Return a seq of cell cycles discovered.
+
+   Tracks the turn of the entanglement just
+   followed, to avoid backtracking immediately."
   [game cell visited from-turn]
   (set (mapcat (fn [[edge turn]]
                  (when-not (= turn from-turn)


Upgrading to latest aleph

Upgrading to latest aleph

--- modules/aleph/project.clj
+++ modules/aleph/project.clj
@@ -1,12 +1,12 @@
 ;; Copyright © 2014 JUXT LTD.

-(defproject juxt.modular/aleph "0.0.2"
+(defproject juxt.modular/aleph "0.0.3"
   :description "A modular extension that provides support for aleph"
   :url "https://github.com/juxt/modular/tree/master/modules/aleph"
   :license {:name "The MIT License"
             :url "http://opensource.org/licenses/MIT"}
-  :dependencies [[aleph "0.4.0-alpha9" :exclusions [org.clojure/clojure]]
-                 [prismatic/schema "0.2.1"]
+  :dependencies [[aleph "0.4.0-beta1" :exclusions [org.clojure/clojure]]
+                 [prismatic/schema "0.3.5"]
                  [juxt.modular/ring "0.5.2"]
                  ]
   :profiles {:dev {:dependencies


Fix defhook so that it can be used multiple times in a namespace

--- src/braid/core/module_helpers.clj
+++ src/braid/core/module_helpers.clj
@@ -115,9 +115,10 @@
   ;; This is a macro, so it'll always be Clojure, so we can't just use
   ;; a reader conditional, so we check `(:ns &env)`, which will be
   ;; `nil` if evaluating the macro in Clojure.
-  (let [clojure? (nil? (:ns &env))]
+  (let [clojure? (nil? (:ns &env))
+        extend-thunks (symbol (str reader "-atom"))]
     `(do
-       (defonce extend-thunks# (atom []))
+       (defonce ~extend-thunks (atom []))
        (def ~reader
          ;; Hack around protocol being clojure.lang.IDeref in Clojure vs
          ;; cljs.core/IDeref in Clojurescript and the method being
@@ -137,7 +138,7 @@
                                  `(fn [x#] (x#)))
                               th#)))
               ~initial-value
-              (deref extend-thunks#)))))
+              (deref ~extend-thunks)))))
        (defn ~writer [f#]
          (when-not (~(if clojure? `var? `fn?) f#)
            (throw (ex-info
@@ -145,4 +146,4 @@
                          ~(if clojure? "var" "functions"))
                     {:invalid-value f#
                      :register-fn (quote ~writer)})))
-         (swap! extend-thunks# conj f#)))))
+         (swap! ~extend-thunks conj f#)))))


Removed trap from forma->cdm, added docs instead

--- src/clj/forma/hadoop/jobs/cdm.clj
+++ src/clj/forma/hadoop/jobs/cdm.clj
@@ -72,7 +72,13 @@
     level (integer). `min-period` ensures there are no duplicate records
     due to resampling pixels to CDM.

-  Example usage:
+   Note that there may be a handful of pixels with NA values in the
+   probability series that cause this job to fail. If that's the case,
+   add a trap to the query a la
+
+     (:trap (hfs-seqfile \"s3n://formatemp/output/cdm-trapped\"))
+
+ Example usage:
     (forma->cdm (hfs-seqfile \"/home/dan/Dropbox/local/output\")
                 (hfs-seqfile \"/tmp/forma/data/gadm-path\")
                 -9999.0
@@ -96,8 +102,7 @@
         (min-period ?rp :> ?p)
         (r/modis->latlon ?sres ?modh ?modv ?s ?l :> ?lat ?lon)
         (latlon-valid? ?lat ?lon)
-        (latlon->tile ?lat ?lon zoom :> ?x ?y ?z)
-        (:trap (hfs-seqfile "s3n://formatemp/output/cdm-trapped")))))
+        (latlon->tile ?lat ?lon zoom :> ?x ?y ?z))))

 (defn spark-hits
   "Prep for generate counts by country, for spark graphs on GFW site.


rand-sexp without function wrapping

rand-sexp without function wrapping

--- src/cljc/mokkameister/random.cljc
+++ src/cljc/mokkameister/random.cljc
@@ -20,7 +20,7 @@
         (recur (- i weight) remaining)))))

 (defmacro rand-sexp
-  "Select and run random s-expression"
+  "Select random s-expression"
   [& sexps]
-  (letfn [(wrap-fn [sexp] `(fn [] ~sexp))]
-    `((rand-nth [~@(map wrap-fn sexps)]))))
+  `(case (rand-int ~(count sexps))
+     ~@(apply concat (map-indexed list sexps))))


Better style.

Better style.

--- src/cljs/town_client/control.cljs
+++ src/cljs/town_client/control.cljs
@@ -43,9 +43,9 @@
         first) "properties") "category")))

 (defn handle-new-data [data incomplete-channel user-channel]
-  (condp = (:resource-type data)
+  (case (:resource-type data)
     :divisions
-    (if (:results data)
+    (if (< 1 (count (:results data)))
       ; no id, got all neighborhoods
       (let [neighborhoods
             (sort-by #(:name %)
@@ -79,7 +79,7 @@
                   (subs init-hash 1))))
             (tmpl/populate-neighborhood-menu neighborhoods nil))))
       ; specific neighborhood
-      (tmpl/output-neighborhood data (@app-state :neighborhoods)))
+      (tmpl/output-neighborhood (first (:results data)) (@app-state :neighborhoods)))

     :respondents
     (tmpl/output-stats (count (:results data)) (into {} (for [key
@@ -89,13 +89,11 @@

     :answer-aggregate
     (do
-        (map/add-data data)
-        (tmpl/output-map-stats (analyser/map-stats data (@app-state :neighborhoods)) (:key data)))
+      (map/add-data data)
+      (tmpl/output-map-stats (analyser/map-stats data (@app-state :neighborhoods)) (:key data)))

-    nil ; incomplete answers, to be aggregated
-    (async/put! incomplete-channel data)
-
-))
+    :answers ; incomplete answers, to be aggregated
+      (async/put! incomplete-channel (:results data))))

 (defn receive-partial-data
@@ -104,7 +102,6 @@
    (loop [received-keys #{}
           data {}]
      (let [val (<! channel)
-
            cdata              (js->clj val)
            category           (category cdata)
            aggregate-id       (keyword (category-to-map-id category))
@@ -123,8 +120,7 @@
                   (dissoc data aggregate-id)))
          (recur new-keys new-data))))))

-(defn init
-  []
+(defn init []
   (let [data-channel (chan)
         user-channel (chan)
         incomplete-channel (chan)]


Fix regex

Fix regex

--- src/clojure/nightcode/editors.clj
+++ src/clojure/nightcode/editors.clj
@@ -313,7 +313,7 @@
         old-text (.getText text-area)
         first-half (subs old-text 0 start-position)
         second-half (subs old-text start-position)
-        cleared-text (str (str/replace first-half #"^[\r\n]" " ") second-half)
+        cleared-text (str (str/replace first-half #"[^\r^\n]" " ") second-half)
         result (if paren-mode?
                  (paren-mode cleared-text col row)
                  (indent-mode cleared-text col row))


Added option to disable use of compression in applications.

--- src/cmr/common/api/web_server.clj
+++ src/cmr/common/api/web_server.clj
@@ -32,6 +32,9 @@
    ;; The port Jetty will be running on
    port

+   ;; Whether gzip compressed responses are enabled or not
+   use-compression?
+
    ;; A function that will return the routes. Should accept a single argument of the system.
    routes-fn

@@ -43,22 +46,24 @@

   (start
     [this system]
-    (let [{:keys [port routes-fn]} this
+    (let [{:keys [port routes-fn use-compression?]} this
           routes (routes-fn system)
           ^Server server (jetty/run-jetty routes {:port port
-                                          :join? false
-                                          :min-threads MIN_THREADS
-                                          :max-threads MAX_THREADS})
-          ;; Create a GZIP handler to handle compression of responses
-          new-handler (doto (GzipHandler.)
-                        (.setHandler (.getHandler server))
-                        (.setMinGzipSize MIN_GZIP_SIZE))]
+                                                  :join? false
+                                                  :min-threads MIN_THREADS
+                                                  :max-threads MAX_THREADS})]

-      ;; Replace the existing handler with the gzip handler
-      (doto server
-        (.stop)
-        (.setHandler new-handler)
-        (.start))
+      (when use-compression?
+        (println "using compression")
+        ;; Create a GZIP handler to handle compression of responses
+        (let [new-handler (doto (GzipHandler.)
+                            (.setHandler (.getHandler server))
+                            (.setMinGzipSize MIN_GZIP_SIZE))]
+          ;; Replace the existing handler with the gzip handler
+          (doto server
+            (.stop)
+            (.setHandler new-handler)
+            (.start))))

       (info "Jetty started on port" port)
       (assoc this :server server)))
@@ -73,6 +78,9 @@
 (defn create-web-server
   "Creates a new web server. Accepts argument of port and a routes function that should accept
   system argument and return compojure routes to use."
-  [port routes-fn]
-  (map->WebServer {:port port
-                   :routes-fn routes-fn}))
+  ([port routes-fn]
+   (create-web-server port routes-fn true))
+  ([port routes-fn use-compression]
+   (map->WebServer {:port port
+                    :use-compression? use-compression
+                    :routes-fn routes-fn})))


Added Exception

Added Exception

--- src/clinvar_submitter/core.clj
+++ src/clinvar_submitter/core.clj
@@ -4,12 +4,14 @@
             [clojure-csv.core :as csv]
             [clojure.tools.logging.impl :as impl]
             [clojure.tools.logging :as log])
+  (:import [java.lang.Exception])
   (:gen-class))

 (defn construct-variant
   "Construct and return one row of variant table, with VariantInterpretation as root"
   [t i]
   (log/debug "Function: construct-variant - constructing one row of variant table, with VariantInterpretation as root")
+  (try
   (let [variant (form/get-variant t i)
         condition (form/get-condition t i)
         interp (form/get-interpretation t i)
@@ -58,21 +60,29 @@
      "" ; significance citations without db ids
      (get evidence :summary) ; comment on clinical significance
      "" ; explanation if clinsig is other or drug
-    ]))
+    ])
+   (catch Exception e (println (str "Exception construct-variant: " (.getMessage e))))))

 (defn construct-variant-table
   "Construct and return variant table"
   [interp-path context-path]
   (log/debug "Function: construct-variant-table- context and input Filename (construct-variant-table): " interp-path context-path)
+  (try
   (let [t (ld/generate-symbol-table interp-path context-path)
         m (vals t)
         interps ((prop= t "VariantInterpretation" "type") m)
         rows (map #(construct-variant t %) interps)]
-    rows))
-
+    rows)
+  (catch Exception e (println (str "Exception in construct-variant-table: " (.getMessage e)))
+  (log/debug (str "Exception in construct-variant-table: " (.getMessage e))))))
+
 (defn -main
   "take input assertion, transformation context, and output filename as input
   and write variant table in csv format"
   [in cx out & args]
-  (log/debug "Input and output filename in main method: " cx out)
-  (spit out (csv/write-csv (construct-variant-table in cx))))
+  (log/debug "Input,output and c filename in main method: " in out cx)
+  (try
+  (spit out (csv/write-csv (construct-variant-table in cx)))
+  (catch Exception e (println (str "Exception in main: " (.getMessage e)))
+  (log/debug (str "Exception in main: " (.getMessage e))))))
+


Improve comic-list-selector docstring

Improve comic-list-selector docstring

--- src/clj/comic_reader/sites.clj
+++ src/clj/comic_reader/sites.clj
@@ -61,8 +61,8 @@
   (:comic->url-format options))

 (defn comic-list-selector
-  "An enlive selector for selecting all of the links for each comics
-  information."
+  "An enlive selector for selecting all of the links to comics on the
+  comic list page."
   []
   (:comic-list-selector options))


No need for vector

No need for vector

--- src/clj/mokkameister/train.clj
+++ src/clj/mokkameister/train.clj
@@ -21,30 +21,30 @@
     (str front a b a b a b a back)))

 (defmacro pick-train
-  [trains]
+  [& trains]
   (rand-nth trains))

 (defn rand-train []
   (pick-train
-   [(train ":coffee:" ":coffee:")
-    (train ":coffee:" ":coffee:")
-    (train ":coffee:" ":heart:")
-    (train ":coffee:" ":heart:")
-    (train ":coffee:" ":heart:")
-    (train ":coffeealarm:" ":coffeealarm:")
-    (train ":nespresso:" ":ali:")
-    (train ":ali:" ":gruff:")
-    (train ":coffee:" ":syringe:")
-    (train ":coffee:" ":mushroom:")
-    (train ":coffee:" ":coffeepot:")
-    (train ":coffee:" ":coffeealarm:")
-    (train ":coffee:" ":hocho:")
-    (train ":coffee:" ":timwendelboe:")
-    (train ":coffee:" ":jan-richter:")
-    (train ":syringe:" ":hocho:")
-    ":steam_locomotive::coffee::coffee::running::running::running::dash:"
-    "All aboard the coffee train\n:steam_locomotive::coffee::coffee::running::running::running::dash:"
-    "Det er kaffi å få på kjøken!"
-    "KEEP CALM THE COFFEE IS READY!"
-    "M-m-m-m-m-microdosing! :syringe::syringe::syringe::exclamation:"
-    "PLEASE PROCEED IN ORDERLY FASHION TO RECEIVE COFFEE :syringe:"]))
+   (train ":coffee:" ":coffee:")
+   (train ":coffee:" ":coffee:")
+   (train ":coffee:" ":heart:")
+   (train ":coffee:" ":heart:")
+   (train ":coffee:" ":heart:")
+   (train ":coffeealarm:" ":coffeealarm:")
+   (train ":nespresso:" ":ali:")
+   (train ":ali:" ":gruff:")
+   (train ":coffee:" ":syringe:")
+   (train ":coffee:" ":mushroom:")
+   (train ":coffee:" ":coffeepot:")
+   (train ":coffee:" ":coffeealarm:")
+   (train ":coffee:" ":hocho:")
+   (train ":coffee:" ":timwendelboe:")
+   (train ":coffee:" ":jan-richter:")
+   (train ":syringe:" ":hocho:")
+   ":steam_locomotive::coffee::coffee::running::running::running::dash:"
+   "All aboard the coffee train\n:steam_locomotive::coffee::coffee::running::running::running::dash:"
+   "Det er kaffi å få på kjøken!"
+   "KEEP CALM THE COFFEE IS READY!"
+   "M-m-m-m-m-microdosing! :syringe::syringe::syringe::exclamation:"
+   "PLEASE PROCEED IN ORDERLY FASHION TO RECEIVE COFFEE :syringe:"))


Scroll ac results into view when moving up

--- src/cljs/clojuredocs/anim.cljs
+++ src/cljs/clojuredocs/anim.cljs
@@ -37,8 +37,7 @@

 (defn scroll-into-view
   [elem & [opts]]
-  (dom/scroll-into-view elem false)
-  #_(let [elem (node elem)
+  (let [elem (node elem)
         {:keys [top bottom]} (dom/bounding-client-rect elem)]
     (when (or (< js/window.innerHeight
                 (+ top (.-offsetHeight elem)))


http-kit/clojure: Enrich docstrings.

http-kit/clojure: Enrich docstrings.

--- src/clojure/src/dnsresolvd.clj
+++ src/clojure/src/dnsresolvd.clj
@@ -13,6 +13,8 @@
 ;

 (ns dnsresolvd
+    "The main module of the daemon."
+
     (:require
         [dnsresolvh         :as             AUX]
         [org.httpkit.server :refer [run-server]]
@@ -20,13 +22,29 @@
 )

 (defn reqhandler
-    "The default HTTP request handler." [req]
+    "The request handler callback.
+    Gets called when a new incoming HTTP request is received.

-    (println req)
+    Args:
+        req: The incoming HTTP request object.
+
+    Returns:
+        TODO: TBD.
+    " [req]
+
+    (println req) ; TODO: Implement the request handler callback.
 )

 (defn startup
-    "Starts up the daemon." [args]
+    "Starts up the daemon.
+
+    Args:
+        args: A list containing the server port number to listen on
+              as the first element.
+
+    Returns:
+        The exit code indicating the daemon overall execution status.
+    " [args]

     (let [port-number (nth args 0)]
     (let [daemon-name (nth args 1)]


Added a function; minor clean-ups.

Added a function; minor clean-ups.

--- src/cmr/opendap/auth/roles.clj
+++ src/cmr/opendap/auth/roles.clj
@@ -9,6 +9,16 @@
 (def management-acl :INGEST_MANAGEMENT_ACL)
 (def echo-management-query {:system_object (name management-acl)})

+(defn admin-key
+  [token]
+  (str "admin:" token))
+
+(defn cmr-acl->reitit-acl
+  [cmr-acl]
+  (if (seq (management-acl cmr-acl))
+    #{:admin}
+    #{}))
+
 (defn route-annotation
   "It is expected that the route annotation for roles is of the form:

@@ -19,19 +29,13 @@
   [request]
   (get-in (ring/get-match request) [:data :get :roles]))

-(defn admin-key
-  [token]
-  (str "admin:" token))
-
 (defn admin
   [base-url token user-id]
   (let [perms (acls/check-access base-url
                                  token
                                  user-id
                                  echo-management-query)]
-    (if (seq (management-acl @perms))
-      #{:admin}
-      #{})))
+    (cmr-acl->reitit-acl @perms)))

 (defn cached-admin
   [system base-url token user-id]


(maint) Change HikariCP FailFast to FailTimeout

The failfast property of HikariCP is deprecated and replaced with a
failtimeout.

Our previous setting of failfast=false would not error when the
minimum number of connections could not be obtained. The new fail
timeout setting of less than zero will mean the pool will start
immediately, and it will not timeout if it can't establish the minimum
number connections.

--- src/puppetlabs/puppetdb/jdbc.clj
+++ src/puppetlabs/puppetdb/jdbc.clj
@@ -530,7 +530,7 @@
      (doto config
        (.setJdbcUrl (str "jdbc:" subprotocol ":" subname))
        (.setAutoCommit false)
-       (.setInitializationFailFast false)
+       (.setInitializationFailTimeout -1)
        (.setTransactionIsolation "TRANSACTION_READ_COMMITTED"))
      (some->> pool-name (.setPoolName config))
      (some->> connection-timeout (.setConnectionTimeout config))


update video state only if video hasn't been processed

--- src/oc/storage/resources/entry.clj
+++ src/oc/storage/resources/entry.clj
@@ -211,7 +211,9 @@
     (create-entry! conn entry)))

 (defn update-video-data [conn video entry]
-  (let [video-processed (> (:state video) 4)
+  (let [video-processed (if (:video-processed entry)
+                          true
+                          (> (:state video) 4))
         video-transcript-data (get-in video [:original_stream :audio_transcription :text])
         video-transcript (or video-transcript-data
                              (:video-transcript entry))]


web/scrape.clj: use TextOutputFormat

web/scrape.clj: use TextOutputFormat

For compatibility with web.merge job input

--- src/org/altlaw/jobs/web/scrape.clj
+++ src/org/altlaw/jobs/web/scrape.clj
@@ -54,6 +54,8 @@
     ;; (.setReducerClass job org.altlaw.jobs.web.scrape_reducer)
     (.setNumReduceTasks job 0)
     (.setInputFormat job TextInputFormat)
+    (.setOutputFormat job TextOutputFormat)
+    (FileOutputFormat/setOutputCompressorClass job GzipCodec)
     (.setJobName job "web.scrape")
     (JobClient/runJob job))
   0)


Adjust implementation for new test case.

--- src/dsbdp/processing_fn_utils.clj
+++ src/dsbdp/processing_fn_utils.clj
@@ -46,9 +46,13 @@

 (defn calculate-distribution-mapping
   [in-seq ratios]
-  (reduce
-    (fn [v r]
-      (conj v (int (* (count in-seq) r))))
-    []
-    ratios))
+  (let [mapping (reduce
+                  (fn [v r]
+                    (conj v (int (* (count in-seq) r))))
+                  []
+                  ratios)]
+    (loop [m mapping, idx 0]
+      (if (= (count in-seq) (reduce + m))
+        m
+        (recur (assoc m idx (inc (m idx))) (inc idx))))))


don't specify nil port

don't specify nil port

--- src/er_cassandra/session/alia.clj
+++ src/er_cassandra/session/alia.clj
@@ -31,8 +31,9 @@

 (defnk create-session
   [contact-points keyspace {port nil}]
-  (let [cluster (alia/cluster {:contact-points contact-points
-                               :port port})
+  (let [cluster (alia/cluster (assoc-when
+                               {:contact-points contact-points}
+                               :port port))
         alia-session (alia/connect cluster)]
     (alia/execute alia-session (str "USE " keyspace ";"))
     (->AliaSession keyspace alia-session)))


trace? c* driver opt

trace? c* driver opt

--- src/er_cassandra/session/alia.clj
+++ src/er_cassandra/session/alia.clj
@@ -22,7 +22,7 @@
   [alia-session
    statement
    {trace? :trace?
-    :as  opts}]
+    :as opts}]
   (aliam/execute
    alia-session
    (let [str-statement (if (string? statement)
@@ -33,7 +33,8 @@
          (debug str-statement)
          (log trace? str-statement)))
      str-statement)
-   (dissoc opts :trace?)))
+   (-> opts
+       (dissoc :trace?))))

 (defn- execute-buffered*
   "execute a statement returning a Deferred<Stream<record>>"
@@ -53,7 +54,8 @@
           (debug str-statement)
           (log trace? str-statement)))
       str-statement)
-    (dissoc opts :trace?))))
+    (-> opts
+        (dissoc :trace?)))))

 (defn shutdown-session-and-cluster
   [session]
@@ -112,7 +114,7 @@
   (with-context deferred-context
     (mlet
       [datastax-session (create-alia-session*
-                         (dissoc args :trace?))
+                         (dissoc args :trace? :consistency))
        :let [alia-session (map->AliaSession
                            {:keyspace keyspace
                             :alia-session datastax-session
@@ -205,7 +207,8 @@
     (mlet [datastax-session (create-alia-session*
                              (dissoc args
                                      :truncate-on-close
-                                     :trace?))
+                                     :trace?
+                                     :consistency))
            :let [spy-session (map->AliaSpySession
                               {:keyspace keyspace
                                :alia-session datastax-session


check if cache file exists

check if cache file exists

--- src/refactor_nrepl/artifacts.clj
+++ src/refactor_nrepl/artifacts.clj
@@ -22,7 +22,9 @@
     (if (zero? lm) nil lm)))

 ;;  structure here is {"prismatic/schem" ["0.1.1" "0.2.0" ...]}
-(defonce artifacts (atom (slurp artifacts-file)
+(defonce artifacts (atom (if (.exists (io/as-file artifacts-file))
+                           (-> artifacts-file slurp read-string)
+                           {})
                          :meta {:last-modified
                                 (get-last-modified-from-file artifacts-file)}))
 (def millis-per-day (* 24 60 60 1000))
@@ -116,8 +118,7 @@
 (defn artifact-list
   [{:keys [force]}]
   (when (or (= force "true") (stale-cache?))
-    (update-artifact-cache!)
-    (spit artifacts-file @artifacts))
+    (update-artifact-cache!))
   (->> @artifacts keys list*))

 (defn artifact-versions


+get bored

+get bored

--- src/babel/english/lexicon.clj
+++ src/babel/english/lexicon.clj
@@ -484,7 +484,19 @@
       :english {:participle "getting angry"
                 :present {:3sing "gets angry"}
                 :past "got angry"}})
-
+
+   "get bored"
+   (let [subject-semantics (ref {:human true})]
+     {:synsem {:cat :verb
+               :sem {:pred :get-bored
+                     :subj subject-semantics
+                     :obj subject-semantics}
+               :subcat {:1 {:sem subject-semantics}
+                        :2 '()}}
+      :english {:participle "getting bored"
+                :present {:3sing "gets bored"}
+                :past "got bored"}})
+
    "get dressed"
    (let [subject-semantics (ref {:human true})]
      {:synsem {:cat :verb


add tests

add tests

--- sass-dsl/test/sass_dsl/transform_test.clj
+++ sass-dsl/test/sass_dsl/transform_test.clj
@@ -5,4 +5,18 @@
             [sass-dsl.common-test :as common-test]
             [sass-dsl.parse-test :as parse-test]
             [sass-dsl.common-test :as common-test]))
+
+(def sass-simpler-nesting-flattened-colons
+  "Given a nested vector of sass declarations - flatten the parents down to
+  prefixes."
+  (transform/flatten-colon-suffixes (parse/transform-to-sass-nested-tree
+                                     common-test/basic-css)))
+
+(deftest flatten-parents
+  (testing "Ensure a nested vector of sass declarations is flattened the parents down to prefixes."
+    (is (=
+         sass-simpler-nesting-flattened-colons
+         ["table.h1" ["margin: 2em 0" "td.ln" ["text-align: right"]] "li"
+          ["font-size:1.2em" "font-weight: bold" "font-family: serif"]]))))
+


logging level changes

logging level changes

--- src/ruuvi_server/heroku/config.clj
+++ src/ruuvi_server/heroku/config.clj
@@ -18,4 +18,4 @@

 (def *server-port* (Integer/parseInt (System/getenv "PORT")))

-(defdb db (postgres (create-connection-pool *database-config*)))+(defdb db (postgres *database-config*))


remove vowel contraction e.g. instead of “io m’alzo” generate the more common “io mi alzo”

--- src/babel/italiano/morphology.clj
+++ src/babel/italiano/morphology.clj
@@ -934,18 +934,7 @@
                 (re-find #"^s[t]" b))
            (str "gli " b)

-           ;; 1),2),3) handle e.g. "io lo ho visto" => "io l'ho visto"
-           ;; 1)
-           (and (= a "mi")
-                (string? b)
-                (re-find #"^[aeiouh]" b))
-           (str "m'" b)
-           ;; 2)
-           (and (= a "ti")
-                (string? b)
-                (re-find #"^[aeiouh]" b))
-           (str "t'" b)
-           ;; 3)
+           ;; handle e.g. "io lo ho visto" => "io l'ho visto"
            (and (string? a)
                 (re-find #"^l[ao]$" a)
                 (string? b)


Log nested Exceptions.

Log nested Exceptions.

--- src/fhofherr/clj_db_util/core.clj
+++ src/fhofherr/clj_db_util/core.clj
@@ -23,7 +23,8 @@
            (org.flywaydb.core Flyway)
            (com.zaxxer.hikari HikariDataSource HikariConfig)
            (org.flywaydb.core.api MigrationInfoService)
-           (clojure.lang Keyword)))
+           (clojure.lang Keyword)
+           (java.sql SQLException)))

 (defrecord Database [^DataSource datasource
                      ^String db-resource-path
@@ -216,7 +217,10 @@
   {:added "0.2.0"}
   [tx-state ^Exception ex]
   (log/warn ex "Exception occured during transaction")
-  ;; TODO repeatedly call and log getNextException (if possible) (see java.sql.BatchUpdateException)
+  (loop [e ex]
+    (when (instance? SQLException e)
+      (log/warn e)
+      (recur (.getNextException ^SQLException e))))
   (let [rolled-back (set-rollback-only! tx-state)]
     [nil rolled-back]))


better message

better message

--- src/clj/game/cards-operations.clj
+++ src/clj/game/cards-operations.clj
@@ -227,7 +227,7 @@
                        (swap! state assoc-in (cons :corp (:zone target)) newices)
                        (swap! state update-in [:corp :deck] (fn [coll] (remove-once #(not= (:cid %) (:cid newice)) coll)))
                        (trigger-event state side :corp-install newice)
-                       (system-msg state side (str "uses Mutate to install " (:title newice) " from R&D at no cost")))
+                       (system-msg state side (str "uses Mutate to install and rez " (:title newice) " from R&D at no cost")))
                      (system-msg state side (str "does not find any ICE to install from R&D")))
                    (shuffle! state :corp :deck)))}


Reuse scroll-up/down-lines in other places

--- src/cljs/asciinema_player/vt.cljs
+++ src/cljs/asciinema_player/vt.cljs
@@ -73,13 +73,34 @@
 (defn set-margin [vt top bottom]
   (assoc vt :top-margin top :bottom-margin bottom))

+(defn scroll-up-lines [lines n filler]
+  (let [n (min n (count lines))]
+    (concat
+     (drop n lines)
+     (repeat n filler))))
+
 (defn scroll-up [{:keys [width top-margin bottom-margin char-attrs] :as vt}]
-  (update-in vt [:lines] (fn [lines]
-                           (vec (concat
-                                 (take top-margin lines)
-                                 (subvec lines (inc top-margin) (inc bottom-margin))
-                                 [(empty-line width char-attrs)]
-                                 (drop (inc bottom-margin) lines))))))
+  (let [filler (empty-line width char-attrs)]
+    (update-in vt [:lines] (fn [lines]
+                             (vec (concat
+                                   (take top-margin lines)
+                                   (scroll-up-lines (subvec lines top-margin (inc bottom-margin)) 1 filler)
+                                   (drop (inc bottom-margin) lines)))))))
+
+(defn scroll-down-lines [lines n filler]
+  (let [height (count lines)
+        n (min n height)]
+    (concat
+     (repeat n filler)
+     (take (- height n) lines))))
+
+(defn scroll-down [{:keys [width top-margin bottom-margin char-attrs] :as vt}]
+  (let [filler (empty-line width char-attrs)]
+    (update-in vt [:lines] (fn [lines]
+                             (vec (concat
+                                   (take top-margin lines)
+                                   (scroll-down-lines (subvec lines top-margin (inc bottom-margin)) 1 filler)
+                                   (drop (inc bottom-margin) lines)))))))

 (defn move-cursor-to-col [vt x]
   (-> vt
@@ -156,28 +177,7 @@
          [0x3f 1049] (-> vt switch-to-primary-buffer restore-cursor)
          :else vt))

-(defn scroll-up-lines [lines n filler]
-  (let [n (min n (count lines))]
-    (concat
-     (drop n lines)
-     (repeat n filler))))
-
-(defn scroll-down-lines [lines n filler]
-  (let [height (count lines)
-        n (min n height)]
-    (concat
-     (repeat n filler)
-     (take (- height n) lines))))
-
 ;; control functions
-
-(defn scroll-down [{:keys [width top-margin bottom-margin char-attrs] :as vt}]
-  (update-in vt [:lines] (fn [lines]
-                           (vec (concat
-                                 (take top-margin lines)
-                                 [(empty-line width char-attrs)]
-                                 (subvec lines top-margin bottom-margin)
-                                 (drop (inc bottom-margin) lines))))))

 (defn execute-bs [{{:keys [x]} :cursor :as vt}]
   (move-cursor-to-col vt (max (dec x) 0)))


Send built list of actions to server :)

Send built list of actions to server :)

--- src/cljs/battle_console/game.cljs
+++ src/cljs/battle_console/game.cljs
@@ -125,23 +125,29 @@
   (let [actions (or (state/get-state :current-actions) [])
         current-action (state/get-state :processing-action)
         new-actions (conj actions current-action)]
+    (println data)
     (state/set-state :current-actions new-actions)
-    (println new-actions)
-    (state/set-state :processing-action nil))
-  (println data))
+    (state/set-state :processing-action nil)))
+
+(defn- error-loading-action
+  "Error loading action"
+  []
+  (state/set-state :processing-action nil))

 (defn- add-action
   "Processes a new action"
   [ev]
   (let [action (reader/read-string (get-action))
+        current-actions (or (state/get-state :current-actions) [])
+        new-actions (conj current-actions action)
         game (-> (state/get-state :game-data)
-                 (assoc :actions [action]))
+                 (assoc :actions new-actions))
         jsgame (js/encodeURIComponent (.stringify js/JSON (clj->js game)))
         url (str "http://rules.api.orionsbelt.eu/game/turn/p1?context=" jsgame)]
     (state/set-state :processing-action action)
-    (println (.stringify js/JSON (clj->js game)))
+    (println (.stringify js/JSON (clj->js new-actions)))
     (GET url {:handler action-added
-              :error-handler error-loading})))
+              :error-handler error-loading-action})))

 (defn- add-action-disabled
   "Checks if the button should be disabled"


fix issue with asset granting agenda point not triggering victory

--- src/clj/game/cards-assets.clj
+++ src/clj/game/cards-assets.clj
@@ -53,7 +53,7 @@
    {:effect (effect (lose :runner :max-hand-size 2))
     :leave-play (effect (gain :runner :max-hand-size 2))
     :trash-effect {:req (req (:access @state))
-                   :effect (effect (move :runner card :scored) (gain :runner :agenda-point 2))}}
+                   :effect (effect (move :runner card :scored) (gain-agenda-point :runner :agenda-point 2))}}

    "City Surveillance"
    {:events {:runner-turn-begins
@@ -129,7 +129,7 @@
    "Director Haas"
    {:effect (effect (gain :click 1 :click-per-turn 1)) :leave-play (effect (lose :click-per-turn 1))
     :trash-effect {:req (req (:access @state))
-                   :effect (effect (move :runner card :scored) (gain :runner :agenda-point 2))}}
+                   :effect (effect (move :runner card :scored) (gain-agenda-point :runner :agenda-point 2))}}

    "Docklands Crackdown"
    {:abilities [{:cost [:click 2] :msg "add 1 power counter" :effect (effect (add-prop card :counter 1))}]}
@@ -416,7 +416,7 @@
     :leave-play (effect (gain :runner :agenda-point
                               (count (filter #(> (:agendapoints %) 0) (:scored runner)))))
     :trash-effect {:req (req (:access @state))
-                   :effect (effect (move :runner card :scored) (gain :runner :agenda-point 2))}
+                   :effect (effect (move :runner card :scored) (gain-agenda-point :runner :agenda-point 2))}
     :events {:agenda-stolen {:req (req (> (:agendapoints target) 0))
                              :effect (effect (lose :runner :agenda-point 1))}}}


Only draw visible poisonous gas

Only draw visible poisonous gas

--- src/cljc/robinson/render.cljc
+++ src/cljc/robinson/render.cljc
@@ -646,10 +646,12 @@
                         {:x x :y y :c ch :fg [90 90 90] :bg [0 0 0]}))))

 (defn render-poisonous-gas
-  [screen trap]
-  (doseq [[x y] (keys (get trap :locations))]
-    (let [bg (color->rgb (rand-nth [:beige :temple-beige :light-brown]))]
-    (set-bg screen x y bg))))
+  [screen state trap]
+  (let [current-time (rw/get-time state)]
+    (doseq [[x y] (keys (get trap :locations))]
+      (when (= (get (rw/get-cell state x y) :discovered) current-time)
+        (let [bg (color->rgb (rand-nth [:beige :temple-beige :light-brown]))]
+          (set-bg screen x y bg))))))

 (defn render-traps
   [state]
@@ -660,7 +662,7 @@
           :crushing-wall
             (render-crushing-wall screen trap)
           :poisonous-gas
-            (render-poisonous-gas screen trap)
+            (render-poisonous-gas screen state trap)
           nil)))))

 (def image-cache (atom {}))


Catch errors in set-game-screen! function

--- src/clojure/nightmod/game.clj
+++ src/clojure/nightmod/game.clj
@@ -1,6 +1,7 @@
 (ns nightmod.game
   (:require [clojail.core :as jail]
             [clojure.java.io :as io]
+            [nightcode.utils :as nc-utils]
             [nightmod.manager :as manager]
             [nightmod.screens :as screens]
             [nightmod.utils :as u]
@@ -15,15 +16,21 @@

     (set-game-screen! main-screen text-screen)"
   [& game-screens]
-  ; remove renderers and layers so map assets can be cleared
-  (doseq [gs game-screens]
-    (-> gs :screen (swap! #(dissoc % :renderer :layers))))
   (on-gl ; clear all assets
-         (asset-manager! manager/manager :clear)
-         ; set the supplied screen(s) with the overlay screen added at the end
-         (apply set-screen!
-                screens/nightmod
-                (conj (vec game-screens) screens/overlay-screen))))
+         (try
+           (doseq [gs game-screens]
+             (-> gs :screen (swap! #(dissoc % :renderer :layers))))
+           (asset-manager! manager/manager :clear)
+           ; set the supplied screen(s) with the overlay screen added at the end
+           (apply set-screen!
+                  screens/nightmod
+                  (conj (vec game-screens) screens/overlay-screen))
+           (catch Exception e
+             (when-not @u/error
+               (reset! u/error
+                       {:message (nc-utils/get-string :error-load)
+                        :exception e}))
+             (screens/set-blank-screen!)))))

 (defn restart-game!
   "Causes the core.clj file to be run again."


nimbus-storage-stormdist-root fixed

nimbus-storage-stormdist-root fixed

--- src/clj/backtype/storm/config.clj
+++ src/clj/backtype/storm/config.clj
@@ -84,7 +84,7 @@
   ([]
     (str "/nimbus/stormdist"))
   ([storm-id]
-    (str (master-stormdist-root) "/" storm-id)))
+    (str (nimbus-storage-stormdist-root) "/" storm-id)))

 (defn master-stormjar-path [stormroot]
   (str stormroot "/stormjar.jar"))


correction to pdgmcmp

correction to pdgmcmp

--- src/clj/webapp/routes/pdgmcmp.clj
+++ src/clj/webapp/routes/pdgmcmp.clj
@@ -41,6 +41,7 @@
                         [:option {:value (first opts)} (last opts) ]))]]]
              [:tr [:td "First PDGM Value Clusters: " ]
               [:td [:select#valstring1.required
+
                     {:title "Choose a value.", :name "valstring1"}
                     ;;(for [valcluster valclusters]
                     ;; [:option  valcluster])


implementent coercion for accounts

implementent coercion for accounts

--- src/clj_money/models/accounts.clj
+++ src/clj_money/models/accounts.clj
@@ -4,7 +4,9 @@
             [clojure.spec :as s]
             [clojure.string :as string]
             [clojure.set :refer [rename-keys]]
+            [clj-money.util :refer [pprint-and-return]]
             [clj-money.validation :as validation]
+            [clj-money.coercion :as coercion]
             [clj-money.models.helpers :refer [with-storage]]
             [clj-money.models.storage :refer [create-account
                                               find-account-by-id
@@ -26,21 +28,25 @@
 (s/def ::parent-id integer?)
 (s/def ::new-account (s/keys :req-un [::entity-id ::name ::type] :opt-un [::parent-id]))
 (s/def ::existing-account (s/keys :req-un [::id] :opt-un [::entity-id ::name ::type ::parent-id]))
+; :balance and :children-balance are not specified because they are always calculated and not passed in
+
+(def ^:private coercion-rules
+  [(coercion/rule :integer [:id])
+   (coercion/rule :keyword [:type])
+   (coercion/rule :integer [:entity-id])
+   (coercion/rule :integer [:parent-id])])

 (declare find-by-id)
 (defn- before-validation
   "Adjust account data for validation"
   [storage account]
   (cond-> account
+    true (coercion/coerce coercion-rules)

     ; If no entity is specified, try to look it up
-    (and (:id account) (nil? (:entity-id account)))
-    (assoc :entity-id (:entity-id (find-by-id storage
-                                              (Integer. (:id account)))))
-
-    ; make sure type is a keyword
-    (string? (:type account))
-    (update-in [:type] keyword)
+    (and (:id account)
+         (nil? (:entity-id account)))
+    (assoc :entity-id (:entity-id (find-by-id storage (:id account))))

     ; strip out empty string for parent-id
     (and (string? (:parent-id account))
@@ -107,8 +113,7 @@
   "Creates a new account in the system"
   [storage-spec account]
   (with-storage [s storage-spec]
-    (let [prepared (->> account
-                        (before-validation s))
+    (let [prepared (before-validation s account)
           validated (apply validation/validate
                            ::new-account
                            prepared


Uses a shorter phrase when running in dev mode.

--- src/cadence/model.clj
+++ src/cadence/model.clj
@@ -2,8 +2,8 @@
   (:refer-clojure :exclude [identity])
   (:require [monger.core :as mg]
             [monger.collection :as mc]
-            [cadence.model.validators :as is-valid]
             [noir.validation :as vali]
+            [noir.options :as options]
             [cemerick.friend :as friend])
   (:use clojure.walk
         [cemerick.friend.credentials :only [hash-bcrypt]]))
@@ -38,4 +38,6 @@
 (def identity #(get friend/*identity* :current))

 (defn get-phrase []
-  "completing this phrase is fun")
+  (if (options/dev-mode?)
+    "derp"
+    "completing this phrase is fun"))


Show close button on mobile. Fixes #145.

--- src/cljs/cljs_repl_web/views.cljs
+++ src/cljs/cljs_repl_web/views.cljs
@@ -367,8 +367,8 @@
                                         ; md->react->component function to gain some basic html
                                         ; formatting (like paragraphs)
              examples (map (fn [html string] {:html html :strings string}) examples-htmls examples-strings)
-             popover-width  (if (= :narrow @media-query) 250 400)
-             popover-height (if (= :narrow @media-query) 200 400)
+             popover-width  (if (= :narrow @media-query) 280 400)
+             popover-height (if (= :narrow @media-query) 250 400)
              popover-content-width (- popover-width (* 2 14) 15)] ; bootstrap padding + scrollbar width
         [popover-content-wrapper
          :showing? showing-atom
@@ -377,7 +377,7 @@
          :style {:max-height (str popover-height)
                  :max-width (str popover-width)}
          :backdrop-opacity 0.1
-         :close-button? false
+         :close-button? (= :narrow @media-query)
          :title [h-box
                  :gap "6px"
                  :align :center


extended by-id to search an element's children

--- src/cljs/cloj/resources/html.cljs
+++ src/cljs/cloj/resources/html.cljs
@@ -21,19 +21,23 @@
 (defn create-data-img [id img-data]
   (hipo/create [:img ^:attrs {:id id :src img-data}] ))

+(defn imageize
+  "Turn a HTML image element into an reified IImage"
+  [img]
+  (reify
+    rman/IImage
+    (id [_] (.-id img))
+    (width [_]  (.-width img))
+    (height [_] (.-height img))
+    (img [_] img))
+  )
+
 (defn mk-resource-manager [dom-div-id]
   (let [store (atom {:imgs [] :targets []})
         dom-div (by-id dom-div-id) ]
     (reify
       rman/IResourceManagerInfo
-      (find-img [_ id]
-        (let [img (by-id id) ]
-          (reify
-            rman/IImage
-            (id [_] id)
-            (width [_]  (.-width img))
-            (height [_] (.-height img))
-            (img [_] img))))
+      (find-img [_ id] (imageize (by-id id)))

       (find-render-target [_ id]
         (println "not implemented"))
@@ -64,9 +68,11 @@
                             img-req
                             (:body)
                             (create-data-img id)
-                            (dommy/append! dom-div))
-                  ret-obj   (rman/find-img this id) ]
-              (put! ret-chan ret-obj)))
+                            (dommy/append! dom-div)
+                            (by-id id)
+                            (imageize)) ]
+              (put! ret-chan new-img)))
+
           ret-chan)))))


delay onblur which blocked on click event

--- src/cljs/github_omnibar/core.cljs
+++ src/cljs/github_omnibar/core.cljs
@@ -117,10 +117,10 @@
           highlighted (:highlighted @omni-data)]
       [:div.github-omnibar
        [:div.filter-repos.filter-bar
-        [:input.filter-input {:type "text"
+        [:input.filter-input.form-control {:type "text"
                               :placeholder "Find ..."
                               :auto-focus "true"
-                              :on-blur #(exit!)
+                              :on-blur #(.setTimeout js/window exit! 100)
                               :on-change (fn [e]
                                            (fuzzy-match omni-data (-> e .-target .-value)))
                               :on-key-down on-key-down}]]


Converting global states to core.async

Converting global states to core.async

--- src/cljs/nonojure/puzzleview.cljs
+++ src/cljs/nonojure/puzzleview.cljs
@@ -21,12 +21,6 @@
 ;  [:tr [:td]        [:td#.num 2] [:td#.cell.c0.r2] [:td#.cell.c1.r2] [:td#.cell.c2.r2] [:td#.cell.c3.r2]]
 ;  [:tr [:td]        [:td#.num 4] [:td#.cell.c0.r3] [:td#.cell.c1.r3] [:td#.cell.c2.r3] [:td#.cell.c3.r3]]])

-(def current-fill-style (atom nil)) ;one of [:empty :crossed :filled nil]
-
-(def board (atom nil))
-
-(def drag-type (atom :rect)) ; possible values :rect, :by-one
-
 (defn range-inc [a b]
   (range (min a b) (inc (max a b))))

@@ -35,22 +29,21 @@

 ;;; Board functions

-(defn init-board! [board width height]
-  (let [state (->> (repeat width :empty)
-                   vec
-                   (repeat height)
-                   vec)]
-    (reset! board state)))
-
-(defn change-cell-in-board! [board x y new-state]
-  (swap! board assoc-in [y x] new-state))
-
-(defn update-region-of-board! [board [from-x from-y] [to-x to-y] new-state]
+(defn init-board [width height]
+  (->> (repeat width :empty)
+       vec
+       (repeat height)
+       vec))
+
+(defn change-cell-in-board [board x y new-state]
+  (assoc-in board [y x] new-state))
+
+(defn update-region-of-board [board [from-x from-y] [to-x to-y] new-state]
   (let [cells-to-change (for [x (range-inc from-x to-x)
                               y (range-inc from-y to-y)]
                           [y x])
-        new-board (reduce #(assoc-in %1 %2 new-state) @board cells-to-change)]
-    (reset! board new-board)))
+        new-board (reduce #(assoc-in %1 %2 new-state) board cells-to-change)]
+    new-board))

 (defn pad [nums beg end value]
   (vec (concat (repeat beg value)
@@ -228,17 +221,17 @@
         rows-wrong (get wrong :rows-wrong)
         cols-wrong (get wrong :cols-wrong)
         problem-def (attr (sel1 :#puzzle-table) "problem-def")
-        server-id (get problem-def :id)]
-    (if (and (empty? rows-wrong)
-             (empty? cols-wrong))
+        server-id (get problem-def :id)
+        done (and (empty? rows-wrong)
+                  (empty? cols-wrong))]
+    (if done
       (rate-dialog server-id)
-      (js/alert (str "There are errors in rows:" rows-wrong "and columns:" cols-wrong)))))
+      (js/alert (str "There are errors in rows:" rows-wrong "and columns:" cols-wrong)))
+    done))

 (defn clear-puzzle []
-  (when-let [state @board]
-    (init-board! board (count (first state)) (count state)))
   (doseq [class ["num-clicked" "filled" "crossed"]
-          el (sel (str "." class))]
+          :let [el (sel (str "." class))]]
     (dommy/remove-class! el class)))

 (defn change-cell-style! [cell style]
@@ -277,37 +270,41 @@
     2 :right
     :unknown))

-(defn handle-mouse-down-on-cell [evt]
+(defn handle-mouse-down-on-cell [evt state]
   (let [cell (.-target evt)
         style (new-cell-style-after-click cell (button evt))
         x (attr-int cell :data-x)
         y (attr-int cell :data-y)]
     (change-cell-style! cell style)
-    (change-cell-in-board! board x y style)
-    {:fill-style style
-     :base-cell [x y]
-     :last-cell [x y]}))
-
-(defn handle-mouse-enter-on-cell [evt event-state]
-  (when (:fill-style event-state)
+    (assoc state
+      :fill-style style
+      :base-cell [x y]
+      :last-cell [x y]
+      :board (change-cell-in-board (:board state) x y style))))
+
+(defn handle-mouse-enter-on-cell [evt state]
+  (if-not (:fill-style state)
+    state
     (let [cell (.-target evt)
           x (attr-int cell :data-x)
           y (attr-int cell :data-y)
-          {:keys [fill-style base-cell last-cell]} event-state]
-      (if (= @drag-type :rect)
-        (do (update-cells-region-style! base-cell last-cell (fn [x y] (get-in @board [y x])))
-          (update-cells-region-style! base-cell [x y] (fn [_ _] fill-style)))
-        (do (change-cell-style! cell fill-style)
-          (change-cell-in-board! board x y fill-style)))
-      (assoc event-state :last-cell [x y]))))
-
-(defn stop-dragging [{:keys [fill-style base-cell last-cell]}]
-  (when (and fill-style
-             (= :rect @drag-type))
-    (update-region-of-board! board base-cell last-cell fill-style))
-  {:fill-style nil
-   :base-cell nil
-   :last-cell nil})
+          {:keys [fill-style base-cell last-cell drag-type]} state]
+      (if (= :rect drag-type)
+        (do
+          (update-cells-region-style! base-cell last-cell (fn [x y] (get-in state [:board y x])))
+          (update-cells-region-style! base-cell [x y] (constantly fill-style))
+          (assoc state :last-cell [x y]))
+        (do
+          (change-cell-style! cell fill-style)
+          (assoc state
+            :last-cell [x y]
+            :board (change-cell-in-board (:board state) x y fill-style)))))))
+
+(defn stop-dragging [initial-state {:keys [fill-style base-cell last-cell board drag-type]}]
+  (assoc initial-state :board
+    (if (and fill-style (= :rect drag-type))
+      (update-region-of-board board base-cell last-cell fill-style)
+      board)))

 (defn disable-context-menu [evt]
   (.preventDefault evt)
@@ -330,32 +327,37 @@
              :mouseup (add-event :mouseup)
              :mouseleave (add-event :mouseleave))
     (listen! [(sel1 :#puzzle-table) :.num]
-             :mousedown handle-number-click
+             :mousedown (add-event :number-click)
              :contextmenu disable-context-menu)
-    (listen! (sel1 :#button-done) :click done-handler)
-    (listen! (sel1 :#button-clear) :click clear-puzzle)))
-
-(defn handle-cell-events [event-chan]
+    (listen! (sel1 :#button-done) :click (add-event :done))
+    (listen! (sel1 :#button-clear) :click (add-event :clear))))
+
+(defn handle-cell-events [event-chan initial-state]
   (go-loop
    [[evt event-type] (<! event-chan)
-    state {:fill-style nil
-           :base-cell nil
-           :last-cell nil}]
+    state initial-state]
    (let [new-state (case event-type
-                     :mousedown (handle-mouse-down-on-cell evt)
+                     :mousedown (handle-mouse-down-on-cell evt state)
                      :contextmenu (disable-context-menu evt)
                      :mouseenter (handle-mouse-enter-on-cell evt state)
-                     :mouseup (stop-dragging state)
-                     :mouseleave (stop-dragging state))]
+                     :mouseup (stop-dragging initial-state state)
+                     :mouseleave (stop-dragging initial-state state)
+                     :number-click (handle-number-click evt)
+                     :done (if (done-handler evt) initial-state state)
+                     :clear (do (clear-puzzle) initial-state)
+                     (do (log (str "Unknown event: " event-type)) state))]
      (recur (<! event-chan) new-state))))

 (defn show [nono]
-  (init-board! board (count (:top nono)) (count (:left nono)))
   (dommy/replace! (sel1 :#puzzle-table) (create-template nono))
   (let [event-chan (chan 5)]
     (add-handlers event-chan)
-    (dommy/remove-class! (sel1 :.puzzle-container) "hidden")
-    (handle-cell-events event-chan))
+    (handle-cell-events event-chan
+                        {:fill-style nil
+                         :base-cell nil
+                         :last-cell nil
+                         :drag-type :rect
+                         :board (init-board (count (:top nono)) (count (:left nono)))}))
   (show-view :puzzle))

 (defn ^:export init []


fix error in clojupyter-install with nil qualifier

--- src/clojupyter/misc/leiningen.clj
+++ src/clojupyter/misc/leiningen.clj
@@ -109,7 +109,7 @@
      (str LOGO64-RESOURCE)
      "-fill" "white"
      "-gravity" "South" "-annotate" "+0+0" ver
-     "-gravity" "North" "-annotate" "+0+0" qual-suffix
+     "-gravity" "North" "-annotate" "+0+0" (or qual-suffix "")
      destfile]))

 (defn- write-icons
@@ -122,8 +122,7 @@
             {:keys [exit stdout err]} (apply sh/sh cmdline)]
         (if (zero? exit)
           :ok
-          (ex-info (str "Copying icons failed: " err)
-            {:exit-code exit, :stdout stdout, :err err, :cmdline cmdline})))
+          (throw (Exception. (str "Copying icons failed: " err)))))
       (io/copy LOGO64-RESOURCE (io/file (str destdir "/" LOGO64-FILENAME))))))

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


Arbitrary code-execution from schemas is probably bad.

--- src/clojure/abracad/avro/read.clj
+++ src/clojure/abracad/avro/read.clj
@@ -17,9 +17,9 @@
   (or (get avro/*avro-readers* rname)
       (if-let [reader (.getProp schema "abracad.reader")]
         (case reader
-          nil      nil
           "vector" vector
-          #_else   (-> reader symbol resolve)))))
+          #_else   (throw (ex-info "unknown `abracad.reader`"
+                                   {:reader reader}))))))

 (defn read-record
   [^ClojureDatumReader reader ^Schema expected ^ResolvingDecoder in]


Resolve case warning

Resolve case warning

--- src/clojure/clj_bwa/exception.clj
+++ src/clojure/clj_bwa/exception.clj
@@ -3,7 +3,7 @@

 (defn libbwa-error->exception
   [n]
-  (case n
+  (case (int n)
     0 nil
     ;; General errors
     10 (IllegalArgumentException. "invalid arguments")


Go back to using the system's default encoding

--- src/clojure/nightcode/editors.clj
+++ src/clojure/nightcode/editors.clj
@@ -248,7 +248,7 @@
             (proxy-super setMarginLinePosition size))
           (processKeyBinding [ks e condition pressed]
             (proxy-super processKeyBinding ks e condition pressed)))
-    (.load (FileLocation/create path) "UTF-8")
+    (.load (FileLocation/create path) nil)
     .discardAllEdits
     (.setAntiAliasingEnabled true)
     (.setSyntaxEditingStyle (get-syntax-style path))


Convert strings.

Convert strings.

--- src/cbfg/zgo/core.clj
+++ src/cbfg/zgo/core.clj
@@ -170,6 +170,7 @@
                   (fn-handler lvl scope fn-name args))
    (symbol? expr) (cvt-sym expr)
    (keyword? expr) (str expr)
+   (string? expr) (str "`" expr "`")
    (nil? expr) "nil"
    :default ["DEFAULT-EXPR" expr]))


don't use Clojure's and/or

don't use Clojure's and/or

--- src/clj/cljs/core.clj
+++ src/clj/cljs/core.clj
@@ -46,12 +46,12 @@
                  :imported)))

 (import-macros clojure.core
- [-> ->> ..  and assert comment cond
+ [-> ->> .. assert comment cond
   declare defn defn-
   doto
   extend-protocol fn for
   if-let if-not letfn
-  memfn or
+  memfn
   when when-first when-let when-not while
   cond-> cond->> as-> some-> some->>])

@@ -192,6 +192,28 @@

 (defn bool-expr [e]
   (vary-meta e assoc :tag 'boolean))
+
+(defmacro and
+  "Evaluates exprs one at a time, from left to right. If a form
+  returns logical false (nil or false), and returns that value and
+  doesn't evaluate any of the other expressions, otherwise it returns
+  the value of the last expr. (and) returns true."
+  ([] true)
+  ([x] x)
+  ([x & next]
+   `(let [and# ~x]
+      (if and# (and ~@next) and#))))
+
+(defmacro or
+  "Evaluates exprs one at a time, from left to right. If a form
+  returns a logical true value, or returns that value and doesn't
+  evaluate any of the other expressions, otherwise it returns the
+  value of the last expression. (or) returns nil."
+  ([] nil)
+  ([x] x)
+  ([x & next]
+      `(let [or# ~x]
+         (if or# or# (or ~@next)))))

 (defmacro nil? [x]
   `(coercive-= ~x nil))


current error grabbing strategy in `cljs.repl/pst` is not flexible enough

add `cljs.repl/IGetError` protocol.

--- src/clj/cljs/repl.clj
+++ src/clj/cljs/repl.clj
@@ -113,6 +113,17 @@
   (-parse-error-message [repl-env message error build-options]
     "Given the original JavaScript error message return the string to actually
      use."))
+
+(defprotocol IGetError
+  (-get-error [repl-env name build-options]
+    "Given a symbol representing a var holding an error return the
+     canonical error representation:
+
+     {:value <string>
+      :stacktrace <string>}
+
+    :value should be the host environment JavaScript error message string.
+    :stacktrace should be the host JavaScript environment stacktrace string."))

 (defprotocol IParseStacktrace
   (-parse-stacktrace [repl-env stacktrace error build-options]
@@ -957,12 +968,14 @@
   ([e]
    (let [{:keys [repl-env] :as env} &env]
      (when (and e repl-env)
-       (let [ret (edn/read-string
-                   (evaluate-form repl-env env "<cljs repl>"
-                     `(when ~e
-                        (pr-str
-                          {:value (.-message ~e)
-                           :stacktrace (.-stack ~e)}))))]
+       (let [ret (if (satisfies? IGetError repl-env)
+                   (-get-error repl-env e *repl-opts*)
+                   (edn/read-string
+                     (evaluate-form repl-env env "<cljs repl>"
+                       `(when ~e
+                          (pr-str
+                            {:value (.-message ~e)
+                             :stacktrace (.-stack ~e)})))))]
          (when ret
            (let [ret (update-in ret [:value]
                        (fn [msg]


fix `cljs.test/testing` when used in body of `cljs.test/test`

--- src/clj/cljs/test.clj
+++ src/clj/cljs/test.clj
@@ -170,6 +170,7 @@
   ([form msg]
    (if (contains? (:locals &env) 'cljs$lang$test$body)
      `(fn [env#] (cljs.test/try-expr env# ~msg ~form))
+     ;; expression evaluation case
      `(cljs.test/try-expr (cljs.test/empty-env) ~msg ~form))))

 (defmacro testing
@@ -178,20 +179,27 @@
   ([string & body]
    (if (contains? (:locals &env) 'cljs$lang$test$body)
      `(fn [env#]
-        (reduce #(%2 %1)
+        (reduce
+          (fn [env'# thunk#]
+            (let [ret# (thunk#)]
+              (if (fn? ret#)
+                (ret# env'#)
+                env'#)))
           (update-in env# [:testing-contexts] conj ~string)
-          [~@body]))
-     `(:last-value
-       (reduce
-         (fn [env'# thunk#]
-           (let [ret# (thunk#)]
-             (if (fn? ret#)
-               (ret# env'#)
-               env'#)))
-         (update-in (assoc (cljs.test/empty-env) :return true)
-           [:testing-contexts] conj ~string)
-         (let [~'cljs$lang$test$body nil]
-           [~@(map (fn [expr] `(fn [] ~expr)) body)]))))))
+          [~@(map (fn [expr] `(fn [] ~expr)) body)]))
+     ;; expression evaluation case
+     `(let [~'cljs$lang$test$body nil]
+        (:last-value
+         (reduce
+           (fn [env'# thunk#]
+             (let [ret# (thunk#)]
+               (if (fn? ret#)
+                 (ret# env'#)
+                 env'#)))
+           (update-in (assoc (cljs.test/empty-env) :return true)
+             [:testing-contexts] conj ~string)
+           (let [~'cljs$lang$test$body nil]
+             [~@(map (fn [expr] `(fn [] ~expr)) body)])))))))

 ;; =============================================================================
 ;; Defining Tests


Change `cljs.util/output-directory` so that it can take a default parameter.

--- src/clj/cljs/util.clj
+++ src/clj/cljs/util.clj
@@ -69,5 +69,7 @@
   [^File f]
   (.mkdirs (.getParentFile (.getCanonicalFile f))))

-(defn output-directory [opts]
-  (or (:output-dir opts) "out"))
+(defn output-directory
+  ([opts] (output-directory opts "out"))
+  ([opts default]
+    (or (:output-dir opts) default)))


Suppress system message for movements with same src and dest

--- src/clj/game/core.clj
+++ src/clj/game/core.clj
@@ -1586,17 +1586,18 @@
                            (= last-zone :deck)))
                 (:title c) "a card")
         s (if (#{"HQ" "R&D" "Archives"} server) :corp :runner)]
-    (case server
-      ("Heap" "Archives")
-      (do (trash state s c {:unpreventable true})
-          (system-msg state side (str "trashes " label from-str)))
-      ("HQ" "Grip")
-      (do (move state s (dissoc c :seen :rezzed) :hand)
-          (system-msg state side (str "moves " label from-str " to " server)))
-      ("Stack" "R&D")
-      (do (move state s (dissoc c :seen :rezzed) :deck {:front true})
-          (system-msg state side (str "moves " label from-str " to the top of " server)))
-      nil)))
+    (if (= src server) nil
+      (case server
+        ("Heap" "Archives")
+        (do (trash state s c {:unpreventable true})
+            (system-msg state side (str "trashes " label from-str)))
+        ("HQ" "Grip")
+        (do (move state s (dissoc c :seen :rezzed) :hand)
+            (system-msg state side (str "moves " label from-str " to " server)))
+        ("Stack" "R&D")
+        (do (move state s (dissoc c :seen :rezzed) :deck {:front true})
+            (system-msg state side (str "moves " label from-str " to the top of " server)))
+        nil))))

 (defn click-run [state side {:keys [server] :as args}]
   (when (and (not (get-in @state [:runner :register :cannot-run])) (pay state :runner nil :click 1))


Add main method

Add main method

--- src/clj/ji/system.clj
+++ src/clj/ji/system.clj
@@ -1,4 +1,5 @@
 (ns ji.system
+  (:gen-class)
   (:require [ji.service :as service]
             [clojure.core.async :refer [chan]]
             [com.keminglabs.jetty7-websockets-async.core :as ws]
@@ -20,3 +21,6 @@
   (when-let [server (:server system)]
     (.stop server))
   (dissoc system :server))
+
+(defn -main [& args]
+  (start (system)))


fix error report on process

fix error report on process

--- src/cljs/sm/core.cljs
+++ src/cljs/sm/core.cljs
@@ -36,11 +36,11 @@
       (assoc s :source-url (source-url source))
       s)))

-(defn find-first [{:keys [sources path languages]}]
+(defn find-first [{:keys [sources path search-languages]}]
   (go-catch
     (loop [sources sources]
       (when-let [source (first sources)]
-        (let [[res] (<? (sm/search-subtitles source path languages))]
+        (let [[res] (<? (sm/search-subtitles source path search-languages))]
           (if res
             (-> (source-info source)
                 (assoc :subtitle res))
@@ -154,7 +154,8 @@
              (notify :info) <!
              (p-upload-local-subtitles notify) <?
              (p-run-search notify) <?)
-         (catch js/Error e (>! c [:error e]))
+         (catch js/Error e
+           (<! (notify (assoc query :error e) :error)))
          (finally (close! c))))
      nil)
    c))


Simplified cljs unit test code

Simplified cljs unit test code

--- src/cljs_dev/dev.cljs
+++ src/cljs_dev/dev.cljs
@@ -15,15 +15,11 @@
   #_ (testing "should always fail"
     (is false)))

-(defn end [success]
-  (if js/window.callPhantom
-    (js/window.callPhantom #js {:exit (if success 0 1)})
-    (set! (.-innerHTML (js/document.getElementById "results")) (if success "Success" "Failure"))))
+(defmethod cljs.test/report [:cljs.test/default :end-run-tests] [m]
+  (let [success (cljs.test/successful? m)]
+    (if js/window.callPhantom
+      (js/window.callPhantom #js {:exit (if success 0 1)})
+      (set! (.-innerHTML (js/document.getElementById "results")) (if success "Success" "Failure")))))

-(defn run []
+(set! (.-onload js/window)
   (run-tests 'hyjinks.browser.dev))
-
-(defmethod cljs.test/report [:cljs.test/default :end-run-tests] [m]
-  (end (cljs.test/successful? m)))
-
-(set! (.-onload js/window) run)


fix arrows on matchup table

fix arrows on matchup table

--- src/foosball/views/matchup.clj
+++ src/foosball/views/matchup.clj
@@ -38,9 +38,9 @@
   [:tr
    [:td [:div.text-right  (render-team players pos-players)]]
    [:td [:div.text-center (format-rating pos-rating-diff)]]
-   [:td [:div.text-center (when (neg? expected-diff) [:i.icon-arrow-left])]]
+   [:td [:div.text-center (when (pos? expected-diff) [:i.icon-arrow-left])]]
    [:td [:div.text-center (format-matchup-percentage (* 100 expected-diff))]]
-   [:td [:div.text-center (when (pos? expected-diff) [:i.icon-arrow-right])]]
+   [:td [:div.text-center (when (neg? expected-diff) [:i.icon-arrow-right])]]
    [:td [:div.text-center (format-rating neg-rating-diff)]]
    [:td (render-team players neg-players)]])


内存化的例子

内存化的例子

--- src/learnclojure/chapt2/core3.clj
+++ src/learnclojure/chapt2/core3.clj
@@ -64,5 +64,24 @@
 ;;1.应为对于给定的出入，返回值是确定的，所以便于测试
 ;;2.便于缓存和并行化，因为任何使用纯函数的地方可以直接用它的返回值代替
 ;;所以可以把返回值缓存起来,下次调用这个函数的时候可以直接返回这个返回值,这个叫内存化
+;;clojure提供了一个内存化的简单实现：memoize，下面是例子
+;;一个判断是否是素数的函数
+(defn prime?
+  [n]
+  (cond
+    (== 1 n) false
+    (== 2 n) true
+    (even? n) false
+    :else (->> (range 3 (inc (Math/sqrt n)) 2)
+               (filter #(zero? (rem n %)))
+               empty?)))
+;;数字大的时候函数运行时间比较长
+(time  (prime? 1125899906842679))
+;;用memoize缓存prime？，函数调用一次后再以相同的参数调用会马上返回结果
+;;所以下面的第二次调用(m-prime? 1125899906842679)比第一次快的多
+(let [m-prime? (memoize prime?)]
+(time (m-prime? 1125899906842679))
+(time (m-prime? 1125899906842679)))
+(rand-int 2)


Added convenience function to get the code for the next inserted row

--- src/wishlistd/models/queries.clj
+++ src/wishlistd/models/queries.clj
@@ -1,5 +1,6 @@
 (ns wishlistd.models.queries
-  (:require [clojure.java.jdbc :as sql]))
+  (:require [clojure.java.jdbc :as sql])
+  (:use wishlistd.code))

 (def db {:classname "org.postgresql.Driver"
          :subprotocol "postgresql"
@@ -65,3 +66,9 @@
   (let [{:keys [id]} wish]
     (sql/with-connection db
       (sql/update-values :wish ["id=?" id] wish))))
+
+(defn get-code []
+  (sql/with-connection db
+    (sql/with-query-results results
+      ["select last_value+1 as last_value from wishlist_id_seq"]
+      (generate-code (:last_value (first (into [] results)))))))


Fixed ensure-schema to properly point to the right file location for schema.edn and removed unwanted code as needed.

--- src/conceptnet_clj/system.clj
+++ src/conceptnet_clj/system.clj
@@ -11,8 +11,7 @@
             [clojure.java.io :as io]))

 (defn- ensure-schema [conn]
-  (or (-> conn d/db (d/entid :cnet/name))
-      @(d/transact conn (read-string (slurp "resources/schema.edn")))))
+  @(d/transact conn (read-string (slurp "resources/datomic/schema.edn"))))

 (defn- ensure-db [db-uri]
   (let [newdb? (d/create-database db-uri)
@@ -86,4 +85,4 @@
   (let [s (start (system))]
     (alter-var-root #'sys (constantly s))
     (alter-var-root #'handler (constantly (get-in s [:web :handler])))
-    s))
+    s))


improves the dru/init-user->dru-divisors runtime by making fewer datomic queries from share/get-share (#742)

--- scheduler/src/cook/mesos/share.clj
+++ scheduler/src/cook/mesos/share.clj
@@ -24,8 +24,14 @@
 (def default-user "default")

 (defn- resource-type->datomic-resource-type
+  "Converts the resource type to a datomic resource type keyword, e.g. :cpus to :resource.type/cpus"
   [type]
   (keyword "resource.type" (name type)))
+
+(defn- datomic-resource-type->resource-type
+  "Converts the datomic resource type to a resource type keyword, e.g. :resource.type/cpus to :cpus"
+  [type]
+  (keyword (name type)))

 (defn- retract-share-by-type!
   [conn type user]
@@ -44,27 +50,30 @@
                    [[:db.fn/retractEntity resource]])
       (log/warn "Resource" type "for user" user "does not exist, could not retract"))))

-(defn- get-share-by-type
-  "Query a user's pre-defined share by type (e.g. :cpus, :mem, :gpus).
+(defn get-share-by-types
+  "Query a user's pre-defined share by types (e.g. [:cpus, :mem, :gpus]).
+   Returns a map from resource type to amount (double value).

-   If a user's pre-defined share is NOT defined, return either:
-   1. the explicitly provided default value, or
+   If a user's pre-defined share is NOT defined for a specific resource type, return either:
+   1. the explicitly provided default value in type->share, or
    2. the share for the \"default\" user. If there is NO \"default\"
       value for a specific type, return Double.MAX_VALUE."
-  ([db type user]
-   (or (get-share-by-type db type user nil)
-       (get-share-by-type db type default-user Double/MAX_VALUE)))
-  ([db type user default]
-   (let [query '[:find ?a
-                 :in $ ?u ?t
-                 :where
-                 [?e :share/user ?u]
-                 [?e :share/resource ?r]
-                 [?r :resource/type ?t]
-                 [?r :resource/amount ?a]]
-         datomic-resource-type (resource-type->datomic-resource-type type)]
-     (or (ffirst (q query db user datomic-resource-type))
-         default))))
+  [db user types type->share]
+  (let [query '[:find ?t ?a
+                :in $ ?u [?t ...]
+                :where
+                [?e :share/user ?u]
+                [?e :share/resource ?r]
+                [?r :resource/type ?t]
+                [?r :resource/amount ?a]]
+        datomic-resource-types (map resource-type->datomic-resource-type types)
+        default-type->share (pc/map-from-keys
+                              (fn [type] (get type->share type Double/MAX_VALUE))
+                              types)]
+    (->> (q query db user datomic-resource-types)
+         (into {})
+         (pc/map-keys datomic-resource-type->resource-type)
+         (merge default-type->share))))

 (defn get-share
   "Query a user's pre-defined share.
@@ -75,11 +84,10 @@
   ([db user]
    (get-share db user (util/get-all-resource-types db)))
   ([db user resource-types]
-   (pc/map-from-keys (fn get-share-3p-helper [type] (get-share-by-type db type user))
-                     resource-types))
+   (let [type->default (get-share-by-types db default-user resource-types {})]
+     (get-share db user resource-types type->default)))
   ([db user resource-types type->default]
-   (pc/map-from-keys (fn get-share-4p-helper [type] (get-share-by-type db type user (type->default type)))
-                     resource-types)))
+   (get-share-by-types db user resource-types type->default)))

 (timers/deftimer [cook-mesos share get-shares-duration])

@@ -93,8 +101,7 @@
   ([db users resource-types]
    (timers/time!
      get-shares-duration
-     (let [type->default (-> (fn [type] (get-share-by-type db type default-user Double/MAX_VALUE))
-                             (pc/map-from-keys resource-types))]
+     (let [type->default (get-share db default-user resource-types {})]
        (-> (fn [user] (get-share db user resource-types type->default))
            (pc/map-from-keys users))))))


selling with Aesop should be unpreventable so Fall Guy won't prompt

--- src/clj/game/cards-resources.clj
+++ src/clj/game/cards-resources.clj
@@ -24,7 +24,7 @@
    "Aesops Pawnshop"
    {:abilities [{:msg (msg "trash " (:title target) " and gain 3 [Credits]")
                  :choices {:req #(and (= (:side %) "Runner") (:installed %))}
-                 :effect (effect (gain :credit 3) (trash target))}]}
+                 :effect (effect (gain :credit 3) (trash target {:unpreventable true}))}]}

    "Always Be Running"
    {:abilities [{:once :per-turn


Refactoring

Refactoring

--- src/cljs/caves_of_cljs/core.cljs
+++ src/cljs/caves_of_cljs/core.cljs
@@ -28,11 +28,12 @@
 (defonce key-loop
   (go-loop []
     (when-let [event (<! key-chan)]
-      (let [keycode (.. event -keyCode)
-            input (get *keys* (if (<= 96 keycode 105)
-                                (- keycode 48)
-                                keycode))]
-        (swap! app-state assoc :input input))
+      (let [key-code (.. event -keyCode)
+            input (get *keys* (if (<= 96 key-code 105)
+                                (- key-code 48)
+                                key-code))]
+        (when (:game @app-state)
+          (swap! app-state assoc-in [:game :input] input)))
       (recur))))

 (defmulti draw-ui
@@ -54,7 +55,8 @@
 (defn draw-game [game screen]
   (.clear screen)
   (doseq [ui (:uis game)]
-    (draw-ui ui game screen)))
+    (draw-ui ui game screen))
+  game)

 (defmulti process-input
   (fn [game input]
@@ -75,21 +77,26 @@
     (assoc game :uis [])
     (assoc game :uis [{:kind :start}])))

-(defn game-loop []
+(defn handle-input [game]
+  (if-let [input (:input game)]
+    (-> game
+        (process-input input)
+        (dissoc :input))
+    game))
+
+(defn tick-game []
   (when-let [screen (:screen @app-state)]
-    (let [input (:input @app-state)
-          game (if (nil? input)
-                 (:game @app-state)
-                 (process-input (:game (swap! app-state dissoc :input))
-                                input))]
-      (draw-game game screen)
-      (swap! app-state assoc :game game)))
-  (.requestAnimationFrame js/window #(game-loop)))
+    (let [game (:game @app-state)]
+      (swap! app-state assoc :game
+             (-> game
+                 handle-input
+                 (draw-game screen))))))

-(defn init-game! []
-  (.requestAnimationFrame js/window #(game-loop)))
+(defn game-loop! []
+  (tick-game)
+  (.requestAnimationFrame js/window game-loop!))

-(init-game!)
+(game-loop!)

 ;; -------------------------
 ;; Views


Null move support (Clojure only for now).

--- src/clojure/clj_chess/board.cljc
+++ src/clojure/clj_chess/board.cljc
@@ -259,6 +259,14 @@
   new board. The move is assumed to be legal."
   [board move]
   (.doMove board move))
+
+#?(:clj
+   (defn do-null-move
+     "Do a null move, i.e. just change the side to move without making a
+     move. This will only work if the side to move is not in check, or if
+     the board is a pseudo-chess board where king captures are allowed."
+     [board]
+     (.doNullMove board)))

 (defn do-uci-move
   "Do the move represented by a UCI string, and return the new board. If no


second refactoring of aggregators/reducers - an impl of sum() - parameters need extracting and reflection needs to be avoided

--- src/main/clojure/org/dada/demo/whales.clj
+++ src/main/clojure/org/dada/demo/whales.clj
@@ -3,6 +3,7 @@
  org.dada.demo.whales
  (:use [org.dada.core])
  (:import [clojure.lang Symbol])
+ (:import [java.math BigDecimal])
  (:import [org.dada.core
 	   Average
 	   Creator
@@ -13,6 +14,9 @@
 	   Transformer
 	   Transformer$Transform
 	   VersionedModelView
+
+	   Reducer
+	   Reducer$Strategy
 	   ])
  )

@@ -109,7 +113,7 @@
 ;; create 10,000 whales and insert them into model
 (insert-n
  whales
- (let [num-whales 1000
+ (let [num-whales 10
        time (System/currentTimeMillis)
        #^Creator creator (.getCreator whale-metadata)
        max-length-x-100 (* max-length 100)
@@ -187,19 +191,44 @@
 ;; demonstrate reduction
 ;;----------------------------------------

-
-;; (defn make-reducer [view #^Model model #^Keyword key #^Reducer$Strategy reduction]
-;;   )
-
-;; (defn do-reduce [view #^Model model #^Keyword key #^Reducer$Strategy reduction]
-;;   (connect model (make-reducer reduction view))
-;;   view)
-
-;; (def sum nil)
-
-;; ;; sum, average, mean, mode, COUNT, minimum, maximum,...
-;; (def narwhals-total-length (do-reduce "SUM(length)" sum narwhals-length :length))
-;; (insert *metamodel* narwhals-total-length)x
+(let [metadata (class-metadata "org.dada.core.Sum" Object :key :version
+			       [:key String :version Integer :sum Number])
+      getter (.getAttributeGetter (.getMetadata heavier-whales-length) "length")
+      accessor (fn [value] (.get getter value))
+      new-value #(accessor (.getNewValue %))
+      old-value #(accessor (.getOldValue %))]
+  (def sum
+       (proxy
+	[Reducer$Strategy]
+	[]
+	(initialValue [] 0M)
+	(initialType [type] type)
+	(currentValue [key version value]
+		      (println "currentValue: " key version value)
+		      (.create metadata [key version value]))
+	(reduce [insertions updates deletions]
+		(-
+		 (+
+		  (reduce #(+ %1 (new-value %2)) 0 insertions)
+		  (reduce #(+ %1 (- (new-value %2) (old-value %2))) 0 updates))
+		 (reduce #(+ %1 (old-value %2)) 0 deletions))
+		)
+	(apply [currentValue delta]
+	       (println "apply: " currentValue  delta)
+	       (+ currentValue delta))
+	))
+
+  (defn make-reducer [#^Model model #^Keyword key-key #^Reducer$Strategy strategy]
+    (let [key (name key-key)]
+      (Reducer. (str (.getName model) ".sum(" key ")") metadata key strategy)))
+  )
+
+(defn do-reduce [#^Model model #^Keyword key #^Reducer$Strategy reduction]
+  (connect model (make-reducer model key reduction)))
+
+;; sum, average, mean, mode, COUNT, minimum, maximum,...
+(def heavier-whales-length-sum (do-reduce heavier-whales-length :length sum))
+(insert *metamodel* heavier-whales-length-sum)

 ;;----------------------------------------
 ;; select - being refactored into filter, transform, aggregate, group, ...


final model design output

final model design output

--- src/crawler/model.clj
+++ src/crawler/model.clj
@@ -201,16 +201,17 @@
                             (= (nth prefix i)
                                (nth rx i)))
                           (range
-                           (count prefix))))))]
-    (into
-     {}
-     (filter
-      (fn [[action-seq n]]
-        (not
-         (reduce
-          #(or %1 %2)
-          (map
-           (fn [prefix]
-             (prefix-match prefix action-seq))
-           remove))))
-      init-planned))))
+                           (count prefix))))))
+        pruned (filter
+                (fn [[action-seq n]]
+                  (not
+                   (reduce
+                    #(or %1 %2)
+                    (map
+                     (fn [prefix]
+                       (prefix-match prefix action-seq))
+                     remove))))
+                init-planned)]
+
+    {:action-seq (into {} pruned)
+     :pagination (into {} paging)}))


adding check for WebSocket support

adding check for WebSocket support

--- support/src/figwheel/client.cljs
+++ support/src/figwheel/client.cljs
@@ -137,31 +137,36 @@
   (set! (.-provide js/goog) (.-exportPath_ js/goog))
   (set! (.-CLOSURE_IMPORT_SCRIPT (.-global js/goog)) figwheel-closure-import-script))

+(defn have-websockets? [] (js*  "(\"WebSocket\" in window)"))
+
 (defn watch-and-reload* [{:keys [retry-count websocket-url
                                  jsload-callback
                                  on-compile-fail] :as opts}]
-    (.debug js/console "Figwheel: trying to open cljs reload socket")
-    (let [socket (js/WebSocket. websocket-url)]
-      (set! (.-onmessage socket) (fn [msg-str]
-                                   (let [msg (read-string (.-data msg-str))]
-                                     #_(.log js/console (prn-str msg))
-                                     (condp = (:msg-name msg)
-                                       :files-changed  (reload-js-files opts msg)
-                                       :css-files-changed (reload-css-files opts msg)
-                                       :compile-failed    (compile-failed msg on-compile-fail)
-                                       nil))))
-      (set! (.-onopen socket)  (fn [x]
-                                 (patch-goog-base)
-                                 (.debug js/console "Figwheel: socket connection established")))
-      (set! (.-onclose socket) (fn [x]
-                                 (log opts "Figwheel: socket closed or failed to open")
-                                 (when (> retry-count 0)
-                                   (.setTimeout js/window
-                                                (fn []
-                                                  (watch-and-reload*
-                                                   (assoc opts :retry-count (dec retry-count))))
-                                                2000))))
-      (set! (.-onerror socket) (fn [x] (log opts "Figwheel: socket error ")))))
+  (if-not (have-websockets?)
+    (.debug js/console "Figwheel: Can't start Figwheel!! This browser doesn't support WebSockets")
+    (do
+      (.debug js/console "Figwheel: trying to open cljs reload socket")
+      (let [socket (js/WebSocket. websocket-url)]
+        (set! (.-onmessage socket) (fn [msg-str]
+                                     (let [msg (read-string (.-data msg-str))]
+                                       #_(.log js/console (prn-str msg))
+                                       (condp = (:msg-name msg)
+                                         :files-changed  (reload-js-files opts msg)
+                                         :css-files-changed (reload-css-files opts msg)
+                                         :compile-failed    (compile-failed msg on-compile-fail)
+                                         nil))))
+        (set! (.-onopen socket)  (fn [x]
+                                   (patch-goog-base)
+                                   (.debug js/console "Figwheel: socket connection established")))
+        (set! (.-onclose socket) (fn [x]
+                                   (log opts "Figwheel: socket closed or failed to open")
+                                   (when (> retry-count 0)
+                                     (.setTimeout js/window
+                                                  (fn []
+                                                    (watch-and-reload*
+                                                     (assoc opts :retry-count (dec retry-count))))
+                                                  2000))))
+        (set! (.-onerror socket) (fn [x] (log opts "Figwheel: socket error ")))))))

 (defn default-on-jsload [url]
   (.dispatchEvent (.querySelector js/document "body")


Docstring for conexp.contrib.algorithms

Docstring for conexp.contrib.algorithms

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

--- src/conexp/contrib/algorithms.clj
+++ src/conexp/contrib/algorithms.clj
@@ -7,6 +7,7 @@
 ;; You must not remove this notice, or any other, from this software.

 (ns conexp.contrib.algorithms
+  "Provides some optimized versions of the standard algorithms of conexp.main"
   (:require [conexp.main :as cm]
             [clojure.core.reducers :as r]
             conexp.contrib.algorithms.linclosure))


Simplify the processor constructor.

Simplify the processor constructor.

--- src/dragon/blog/post/core.clj
+++ src/dragon/blog/post/core.clj
@@ -33,11 +33,7 @@
 ;;;   Constructor   ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

-(defn new-processor-fn
+(defn new-processor
   [system]
   (case (config/processor-constructor system)
-    :default (fn [] (default/new-processor system))))
-
-(defn new-processor
-  [system]
-  (default/new-processor system))
+    :default (default/new-processor system)))


Update auth.clj

Update auth.clj

--- backend/src/akvo/lumen/lib/auth.clj
+++ backend/src/akvo/lumen/lib/auth.clj
@@ -72,7 +72,7 @@
             auth-uuid-tree (if (and (match-by-jwt-family-name? request)
                                     (match-by-template-and-method? auth-calls request))
                              (let [permissions   (->> (map :source dss)
-                                                      (filter #(and (= (get % "instance") "uat1") (= "AKVO_FLOW" (get % "kind"))))
+                                                      (filter #(= "AKVO_FLOW" (get % "kind")))
                                                       (map c.flow/>api-model)
                                                       (c.flow/check-permissions flow-api (jwt/jwt-token request))
                                                       :body


fix bug with write-bq-table schema

fix bug with write-bq-table schema

--- src/datasplash/bq.clj
+++ src/datasplash/bq.clj
@@ -3,7 +3,7 @@
             [clojure.java.shell :refer [sh]]
             [clojure.string :as str]
             [clj-time [coerce :as tc]
-                      [format :as tf]]
+             [format :as tf]]
             [clojure.tools.logging :as log]
             [datasplash.core :refer :all])
   (:import
@@ -188,7 +188,9 @@
      (let [schema (:schema options)
            base-coll pcoll]
        (->> base-coll
-            (dmap clj-nested->table-row (assoc safe-opts :coder (TableRowJsonCoder/of)))
+            (dmap clj-nested->table-row (-> safe-opts
+                                            (assoc :coder (TableRowJsonCoder/of))
+                                            (dissoc :schema)))
             (write-bq-table-raw to safe-opts))))))

 (defn write-bq-table


Added deathdname column to database schema

--- src/demogorgon/nh.clj
+++ src/demogorgon/nh.clj
@@ -429,6 +429,7 @@
       [:version "TEXT"]
       [:points "INT"]
       [:deathdnum "INT"]
+      [:deathdname "TEXT"]
       [:deathlev "INT"]
       [:maxlvl "INT"]
       [:dlev_name "TEXT"]


changes from feedback

changes from feedback

--- src/ctia/task/purge_es_stores.clj
+++ src/ctia/task/purge_es_stores.clj
@@ -27,5 +27,5 @@
   (log/info "purging all ES Stores data")
   (setup)
   (delete-store-indexes)
-  (println "done")
+  (log/info "done")
   (System/exit 0))


Fix typo

Fix typo

--- src/zooniverse_live/data_init.cljs
+++ src/zooniverse_live/data_init.cljs
@@ -28,7 +28,7 @@
         (filter #(contains? (enabled-projects @app) (keyword (:project %))))))

 (defn request
-  [url callback-fn & {:keys [type clojurize] :or {type "GET" clojureize ture}}]
+  [url callback-fn & {:keys [type clojurize] :or {type "GET" clojureize true}}]
   (let [xhr (js/XMLHttpRequest.)
         convert-fn (if clojurize str-clj json)]
     (set! (.-onreadystatechange xhr)


Added a couple more interval functions.

Added a couple more interval functions.

I need to stop fiddling with the scheduler and actually make the rest of
the app :P

--- src/eddy/schedule.clj
+++ src/eddy/schedule.clj
@@ -19,7 +19,12 @@

 (defn calendar-interval-function [unit]
   (case (str unit)
-    (or "second" "seconds") "with-interval-in-seconds"
+    "second" "with-interval-in-seconds"
+    "seconds" "with-interval-in-seconds"
+    "minute" "with-interval-in-minutes"
+    "minutes" "with-interval-in-minutes"
+    "hour" "with-interval-in-hours"
+    "hours" "with-interval-in-hours"
     (throw (IllegalArgumentException. "Interval syntax invalid"))))

 (defn calendar-interval-operands [operand-data]


added doc string to stop-server

added doc string to stop-server

--- src/elliot/server.clj
+++ src/elliot/server.clj
@@ -30,17 +30,18 @@

 (defonce server (atom nil))

-(defn stop-server []
+(defn stop-server
+  "Stops server, when an http-kit server named `server` exists"
+  []
   (when-not (nil? @server)
     ;; graceful shutdown: wait 100ms for existing requests to be finished
     ;; :timeout is optional, when no timeout, stop immediately
     (@server :timeout 100)
     (reset! server nil)))

-(defn -main [& args]
-  ;; The #' is useful when you want to hot-reload code
-  ;; You may want to take a look: https://github.com/clojure/tools.namespace
-  ;; and http://http-kit.org/migration.html#reload
+(defn -main
+  "Starts or restarts server"
+  [& args]
   (if (not (nil? @server))
     (stop-server))
   (reset! server (run-server #'app {:port 8080})))


Function get-output-format

Function get-output-format

--- src/emender_jenkins/rest_api.clj
+++ src/emender_jenkins/rest_api.clj
@@ -384,6 +384,18 @@
                     :method method}]
         (send-error-response response request :bad-request)))

+(defn get-output-format
+    [request]
+    (let [output-format (-> (:params request) (get "format"))]
+        (condp = output-format
+            "json" :json
+            "xml"  :xml
+            "csv"  :csv
+            "edn"  :edn
+            "text" :txt
+            "txt"  :txt
+                   :json)))
+
 (defn get-metadata
     [request]
     (let [params  (:params request)


Allow no valid config to be specified.

Allow no valid config to be specified.

Still print a pretty angry message.

--- src/incise/config.clj
+++ src/incise/config.clj
@@ -2,6 +2,7 @@
   (:require [clojure.java.io :refer [reader file resource]]
             [clojure.edn :as edn]
             [pallet.map-merge :refer [merge-keys]]
+            [taoensso.timbre :refer [warn]]
             [manners.victorian :refer [defmannerisms]])
   (:import [java.io PushbackReader])
   (:refer-clojure :exclude [reset! load assoc! get get-in]))
@@ -42,8 +43,10 @@
   "Load the config from "
   [& [path-to-config]]
   (when path-to-config (clojure.core/reset! config-path path-to-config))
-  (when-let [config-file (file (or @config-path (resource "incise.edn")))]
-    (merge! (edn/read (PushbackReader. (reader config-file))))))
+  (when-let [config-url (or @config-path (resource "incise.edn"))]
+    (try (-> config-url file reader PushbackReader. edn/read merge!)
+      (catch RuntimeException e
+        (warn e "Had trouble reading in config file:" (str config-url))))))

 (defn- str-starts-or-ends-with-slash?
   [a-str]


Style 404 page a tiny bit.

Style 404 page a tiny bit.

--- src/incise/server.clj
+++ src/incise/server.clj
@@ -12,6 +12,24 @@

        <title>404 - Page not found</title>
+

404


Fix logging when message has % but doesn't use format args

--- src/less4clj/util.clj
+++ src/less4clj/util.clj
@@ -11,7 +11,10 @@
   [verbosity args]
   (when (>= *verbosity* verbosity)
     (binding [*out* *err*]
-      (apply printf args) (flush))))
+      (print (if (seq (rest args))
+               (apply format args)
+               (first args)))
+      (flush))))

 (defn dbug [& more] (print* 2 more))
 (defn info [& more] (print* 1 more))


Screwing around with things like threading details

--- src/frereth_server/system.clj
+++ src/frereth_server/system.clj
@@ -21,12 +21,15 @@
   (assert (not @(:client-connections universe)))

   ;; Q: How many threads should I dedicate to the networking context?
-  ;; A: For now, run with "available - 1.
+  ;; A: For now, run with "available - 1."
   ;; This value will really vary according to need and is something
   ;; that is ripe for tweaking. In all honesty, it should probably
   ;; be 1 for now.
+  ;; FIXME: Load this from configuration.
+  ;; For that matter, really should be able to tweak it at runtime.
   (let [;; Actual networking context
-        context (mq/context (- (.availableProcessors (Runtime/getRuntime)) 1))
+        ;;context (mq/context (- (.availableProcessors (Runtime/getRuntime)) 1))
+        context (mq/context 1)
         ;; Where should the master server be listening?
         master-port config/master-port
         ;; Connection to localhost for Ultimate Power...
@@ -37,8 +40,11 @@
         ;; These probably need to be something different
         client-sockets (mq/socket context mq/router)]
     ;; Using JNI, I can use shared memory sockets, can't I?
-    ;; Whatever. Can't bind to a single dynamic hostname.
-    ;(mq/bind master-socket (format "tcp://localhost:%d" master-port))
+    ;;(mq/bind master-socket (format "ipc://127.0.0.1:%d" master-port))
+    ;; Doesn't work on windows.
+    ;; Note that, on unix, we have to set up the named pipe.
+    ;; FIXME: Should probably plan on using that, if it's available.
+    ;; For now, it qualifies as premature optimization.
     (mq/bind master-socket (format "tcp://127.0.0.1:%d" master-port))
     ;; Want to be pickier about who can connect. Or, at least,
     ;; have the option to do so.


THA add :photos to app state

THA add :photos to app state

--- src/hatti/views/dataview.cljs
+++ src/hatti/views/dataview.cljs
@@ -20,6 +20,9 @@
   {:overview {:view :overview
               :label "Overview"
               :component overview-page}
+   :photos {:view :photos
+            :label "Photos"
+            :component photos-page}
    :map {:view :map
          :label "Map"
          :component map-page}


Update json-core.clj

Update json-core.clj

mysql con Vorbereitung (mglw. auf totem Pferd geritten)

--- src/hello_world/json-core.clj
+++ src/hello_world/json-core.clj
@@ -4,6 +4,26 @@
             [ring.middleware.json :as middleware]
             [ring.adapter.jetty :as jetty]
             [compojure.handler :as handler]))
+;            [clojure.java.jdbc :as jdbc])
+;  (:gen-class))
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;(let [db-host "localhost"
+;      db-port 3306
+;      db-name "mgm_schema"]
+
+;(def mysql-db {:classname "com.mysql.jdbc.Driver" ; must be in classpath
+;           :subprotocol "mysql"
+;           :subname (str "//" db-host ":" db-port "/" db-name)
+           ; Any additional keys are passed to the driver
+           ; as driver-specific properties.
+;           :user "usernameplaceholder"
+;           :password "passwordplaceholder"}))
+
+;(defn sqlquery [name]
+;(first (jdbc/query mysql-db [(str "select * from konten where Name='" name "'")])))
+;(jdbc/update! mysql-db :konten {:Guthaben 99} ["Name = ?" name]))
+;maybe this sets the guthaben to 99
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;,

 (defn- get-article [id]
 	{:body {:body "
body text
"


Fix bad authentication hash after registration.

--- src/lunchlotto/auth/handlers.clj
+++ src/lunchlotto/auth/handlers.clj
@@ -79,10 +79,12 @@
     (if valid?
       (do
         (models/confirm-user db data)
-        (friend/merge-authentication
-          (respond-with/redirect "/lunches/upcoming" (t [:flash :registered]))
-          {:username (:email data)
-           :roles #{::user}}))
+        (let [user (models/find-user-by-email db (:email data))]
+          (friend/merge-authentication
+            (respond-with/redirect "/lunches/upcoming" (t [:flash :registered]))
+            {:id (:id user)
+             :username (:email data)
+             :roles #{::user}})))
       (respond-with/bad-request (views/confirmation-page {:params data})))))

 (defn authenticate