replace servlet gen logic with call to make-servlet

--- src/leiningen/new/migae.clj
+++ src/leiningen/new/migae.clj
@@ -1,15 +1,15 @@
 (ns leiningen.new.migae
   (:require  [clojure.java.io :as io]
-             [clojure.string :only [join]])
+             [clojure.string :as str])
   (:use
-        [leiningen.new.templates :only [*dir* project-name
-                                        renderer
-                                        render-text
-                                        multi-segment
-                                        sanitize-ns name-to-path
-                                        ->files
-                                        year]]
-        [leiningen.core.main :only [abort]]))
+   [leiningen.new.templates :only [*dir* project-name
+                                   renderer
+                                   render-text
+                                   multi-segment
+                                   sanitize-ns name-to-path
+                                   ->files
+                                   year]]
+   [leiningen.core.main :only [abort]]))

 (defn- template-path [name path data]
@@ -24,26 +24,247 @@
   (let [dir (or *dir*
                 (-> (System/getProperty "leiningen.original.pwd")
                     (io/file name) (.getPath)))]
-;        foo (println (format "->files dir: %s" dir))]
+                                        ;        foo (println (format "->files dir: %s" dir))]
     (if (or *dir* (.mkdir (io/file dir)))
       (doseq [path paths]
         (do ;(println (format "topath %s" (first path)))
-            (println (format "  rendered: %s" (template-path dir (first path) data)))
-        (if (string? path)
-          (do (println (format "mkdirs %s"  (template-path dir path data)))
-              (.mkdirs (template-path dir path data)))
-          (let [[path content & options] path
-                path (template-path dir path data)
-                options (apply hash-map options)]
-            (.mkdirs (.getParentFile path))
-            (io/copy content (io/file path))
-            (when (:executable options)
-              (.setExecutable path true)))))
-      (println (str "Could not create directory " dir
+          (println (format "  rendered: %s" (template-path dir (first path) data)))
+          (if (string? path)
+            (do (println (format "mkdirs %s"  (template-path dir path data)))
+                (.mkdirs (template-path dir path data)))
+            (let [[path content & options] path
+                  path (template-path dir path data)
+                  options (apply hash-map options)]
+              (.mkdirs (.getParentFile path))
+              (io/copy content (io/file path))
+              (when (:executable options)
+                (.setExecutable path true)))))
+        (println (str "Could not create directory " dir
                       ". Maybe it already exists?"))))))

-
-
+(defn make-pmap
+  [args]
+  (do
+    (let
+        [args (first args)
+         project (first args)
+         [appname appid] (str/split (str project) #":")
+         appid (if (not appid)
+                 (do (println "missing gae app-id; using appname")
+                     appname)
+                 appid)
+         sdk (second args)
+         render (renderer "migae")
+         main-ns (multi-segment (sanitize-ns appname))]
+      {:name appname ;; ":name" key required by leiningen
+       :projdir (str/join "/"
+                          [(System/getProperty "leiningen.original.pwd")
+                           appname])
+       :appname appname
+       :_appname (name-to-path appname)
+       :version "0.1.0-SNAPSHOT"
+       :appid appid
+       :gae-app-version "0-1-0"
+       :raw-name appname
+       :filterclass (str (name-to-path appname) ".reload_filter")
+       :servlets [{:-servlet "request",
+                   :src (str (name-to-path appname) "/request_servlet"),
+                   :ns (str appname ".request-servlet"),
+                   :class (str (name-to-path appname) ".request_servlet"),
+                   :services [{:service "request",
+                               :url-pattern "/request/*"}]}
+                  ;; :action "GET"
+                  ;; :route "/request/:rqst"
+                  ;; :arg {:var "rqst"}}]}
+                  {:-servlet "user",
+                   :src (str (name-to-path appname) "/user_servlet"),
+                   :ns (str appname ".user-servlet"),
+                   :class (str (name-to-path appname) ".user_servlet"),
+                   :services [{:service "prefs",
+                               :url-pattern "/user/prefs"}
+                              {:service "login",
+                               :url-pattern "/user/login"}]}]
+       :display-name (project-name appname)
+       :project (project-name appname)
+       :projroot (name-to-path appname) ;; foo-bar -> foo_bar
+       :aots [{:aot (str appname ".request-servlet")}
+              {:aot (str appname ".user-servlet")}
+              {:aot (str appname ".reload-filter")}]
+       :namespace (str appname ".request")
+       :welcome "index.html"
+       :sdk sdk
+       :war "war"
+       ;; we only install to src dirs, leave config to migae plugin
+       :statics_src "src/main/public"
+       :resources_src "src/main/resource"
+       :year (year)
+       :proj-url "http://example.com/FIXME"
+       :nested-dirs (name-to-path main-ns) ;; foo-bar.core -> foo_bar/core
+       :threads true
+       :sessions true
+       :java-logging "logging.properties"
+       :log4j-logging "log4j.properties"})))
+
+(defn make-servlet
+  [cmdname & args]  ;; cmdname = app | servlet
+  (let [project (first (first args))
+        [projname servlet] (str/split (str project) #":")
+        theservlet (if servlet
+                     (do ; (println "making servlet " servlet)
+                       servlet)
+                     (abort
+                      (str "Syntax: lein new migae servlet <projname>:<servletname>")))
+        ;; TODO: support 'lein new migae servlet <servletname>' from root dir
+        projomap (make-pmap args)
+        pmap (merge projomap {:-servlet theservlet
+                              :_servlet (name-to-path theservlet)
+                              :services {
+                                         :service theservlet
+                                         :url-pattern (str "/" theservlet "/*")}})
+;;        foo (println (:servlet pmap))
+        sname (pmap :appid)
+        render (renderer "migae")
+        ;; servlet (assoc s
+        ;;           :appname (:appname pmap)
+        ;;           :name (:name pmap)
+        ;;           :projroot (:projroot pmap))
+        proj (name-to-path (:appname pmap))
+        tobase (str/join "/"
+                            [(if (= cmdname "app") projname ".")
+                             (name-to-path (render-text
+                                            "src/{{appname}}/{{-servlet}}"
+                                            pmap))])]
+    (do
+      (if (= cmdname "servlet")
+        (do
+          (println (format
+                    "Generating servlet %s in project %s"
+                    (pmap :-servlet)
+                    (pmap :name)))
+          (println "WARNING: you must edit the :servlets section of project.clj")
+          (println
+           (render-text
+            (str "Add this stanza:\n"
+                 "{:servlet \"{{-servlet}}\",\n"
+                 " :src \"{{_appname}}/{{_servlet}}_servlet.clj\"\n"
+                 " :ns \"{{appname}}.{{-servlet}}-servlet\",\n"
+                 " :class \"{{_appname}}.{{_servlet}}_servlet\",\n"
+                 " :filters [{:filter \"reload_filter\"}],\n"
+                 " :services [{:service \"{{-servlet}}\" :url-pattern  \"/{{-servlet}}/*\"}]}\n")
+            pmap))))
+      (binding [*dir* (.getCanonicalPath (io/file
+                                          (System/getProperty
+                                           "leiningen.original.pwd")))]
+        (->files pmap
+                 [(str tobase "_servlet.clj")
+                  (render "servlet.clj" pmap)]
+                 [(str tobase "_impl.clj")
+                  (render "servlet_impl.clj" pmap)])))))
+
+(defn make-app
+  [projname & args]
+  (if (nil? args)
+    (abort (str "missing sdk path!"
+                "Syntax:  lein new migae myapp:gae-app-id path/to/sdk"))
+    (let [pmap (make-pmap args)
+          render (renderer "migae")]
+      (println "Generating migae project:"
+               (pmap :appname)
+               ", app-id:"
+               (pmap :appid)
+               ", template: migae")
+
+      (make-servlet projname (list (str/join ":" [(pmap :appname) "request"])))
+      (make-servlet projname (list (str/join ":" [(pmap :appname) "user"])))
+
+      ;; (doseq [s (:servlets pmap)]
+      ;;   (let [servlet (assoc s
+      ;;                   :appname (:appname pmap)
+      ;;                   :name (:name pmap)
+      ;;                   :projroot (:projroot pmap))
+      ;;         proj (name-to-path (:appname pmap))
+      ;;         toservlet (name-to-path (render-text
+      ;;                                  "src/{{appname}}/{{-servlet}}"
+      ;;                                  servlet))
+      ;;         toimpl (name-to-path (render-text
+      ;;                               "src/{{appname}}/{{-servlet}}"
+      ;;                               servlet))]
+      ;;     (binding [*dir* (.getCanonicalPath (io/file
+      ;;                                         (System/getProperty
+      ;;                                          "leiningen.original.pwd")
+      ;;                                         (:name servlet)))]
+      ;;       (->files servlet
+      ;;                [(str toservlet "_servlet.clj")
+      ;;                 (render "servlet.clj" servlet)]
+      ;;                [(str toimpl "_impl.clj")
+      ;;                 (render "servlet_impl.clj" servlet)]))))
+
+      (binding [*dir* (.getPath
+                       (io/file
+                        (System/getProperty "leiningen.original.pwd")
+                        (:name pmap)))]
+        (->files pmap
+                 ;; to file  		from template
+                 ["project.clj" (render "project.clj" pmap)]
+                 ["README.md" (render "README.md" pmap)]
+                 ["doc/intro.md" (render "intro.md" pmap)]
+                 [".gitignore" (render "gitignore" pmap)]
+
+                 ["src/{{projroot}}/reload_filter.clj"
+                  (render "reloadfilter.clj" pmap)]
+
+                 ;; ["src/main/java/com/google/apphosting/utils/security/SecurityManagerInstaller.java" (render "SecurityManagerInstaller.java" pmap)]
+
+                 ;; NB: treatment of '-', '_', '/', and '.'
+                 ;; "lein new migae foo-bar" yields:
+                 ;; src:  ns foo-bar.core in  src/foo_bar/core.clj
+                 ;; ["src/{{nested-dirs}}.clj" (render "core.clj" pmap)]
+
+                 ;; ;; test: foo-bar.core-test -> foo_bar/core_test.clj
+                 ["test/{{nested-dirs}}_test.clj" (render "core_test.clj" pmap)]
+
+                 ;; app engine config files
+                 ;; copy template w/o macro processing ('pmap' arg)
+                 ;; install in hidden dir?  or etc?
+                 ;; [".{{appname}}/appengine-web.xml.mustache"
+
+                 ["etc/appengine-web.xml.mustache" (render "appengine-web.xml.mustache")]
+                 ["etc/dir-locals.el.mustache" (render "dir-locals.el.mustache")]
+                 ["etc/{{java-logging}}" (render "logging.properties")]
+                 ["etc/{{log4j-logging}}" (render "log4j.properties")]
+                 ["etc/web.xml.mustache" (render "web.xml.mustache")]
+
+                 ;; resources install to source tree
+                 ;; migae plugin "config" task will copy to war tree
+
+                 ["{{statics_src}}/{{welcome}}"
+                  (render "home.html" (conj {:loc "Home"} pmap))]
+
+                 ["{{statics_src}}/html/{{welcome}}"
+                  (render "index.html" (conj {:loc "HTML"} pmap))]
+                 ["{{statics_src}}/404.html"
+                  (render "404.html" pmap)]
+
+                 ["{{statics_src}}/html/a/{{welcome}}"
+                  (render "index.html" (conj {:loc "A"} pmap))]
+                 ["{{statics_src}}/html/b/{{welcome}}"
+                  (render "index.html" (conj {:loc "B"} pmap))]
+                 ["{{statics_src}}/request/{{welcome}}"
+                  (render "index.html" (conj {:loc "Request"} pmap))]
+
+                 ["{{statics_src}}/css/{{project}}.css"
+                  (render "project.css" pmap)]
+                 ["{{statics_src}}/js/{{project}}.js"
+                  (render "project.js" pmap)]
+                 ["{{resources_src}}/favicon.ico"
+                  (render "favicon.ico" pmap)]
+
+                 ;; templates?
+                 ;; ["private/hiccup/{{appname}}.???" (render "..." pmap)]
+
+                 ;; TODO: add a spinner, favicon, or other toy graphic
+                 ;; ["public/img/{{appname}}.js" (render "public/img/foo.png" pmap)]
+                 )))))

 ;; main template entry point
 (defn migae
@@ -51,146 +272,8 @@
   [projname & args]
   ;; projname syntax:  <clj-app>:<gae-app-id>
   (do
-    (if (nil? args)
-      (do (abort "missing sdk path!  Syntax:  lein new migae myapp:gae-app-id path/to/sdk") )
-      (println args))
-    (let
-        [[appname appid] (.split  projname ":")
-         sdk (first args)
-         render (renderer "migae")
-         main-ns (multi-segment (sanitize-ns appname))
-         data {:name appname ;; ":name" key required by leiningen
-               :projdir (clojure.string/join "/"
-                              [(System/getProperty "leiningen.original.pwd")
-                                  appname])
-               :appname appname
-               :version "0.1.0-SNAPSHOT"
-               :gae-app-id appid
-               :gae-app-version "0-1-0"
-               :raw-name appname
-               :filterclass (str (name-to-path appname) ".reload_filter")
-               :servlets [{:servlet "request",
-                           :src (str (name-to-path appname) "/request_servlet"),
-                           :ns (str appname ".request-servlet"),
-                           :class (str (name-to-path appname) ".request_servlet"),
-                           :services [{:service "request",
-                                       :url-pattern "/request/*"}]}
-                                       ;; :action "GET"
-                                       ;; :route "/request/:rqst"
-                                       ;; :arg {:var "rqst"}}]}
-                          {:servlet "user",
-                           :src (str (name-to-path appname) "/user_servlet"),
-                           :ns (str appname ".user-servlet"),
-                           :class (str (name-to-path appname) ".user_servlet"),
-                           :services [{:service "prefs",
-                                       :url-pattern "/user/prefs"}
-                                      {:service "login",
-                                       :url-pattern "/user/login"}]}]
-               :display-name (project-name appname)
-               :project (project-name appname)
-               :projroot (name-to-path appname) ;; foo-bar -> foo_bar
-               :aots [{:aot (str appname ".request-servlet")}
-                      {:aot (str appname ".user-servlet")}
-                      {:aot (str appname ".reload-filter")}]
-               :namespace (str appname ".request")
-               :welcome "index.html"
-               :sdk sdk
-               :war "war"
-               ;; we only install to src dirs, leave config to migae plugin
-               :statics_src "src/main/public"
-               :resources_src "src/main/resource"
-               :year (year)
-               :proj-url "http://example.com/FIXME"
-               :nested-dirs (name-to-path main-ns) ;; foo-bar.core -> foo_bar/core
-               :threads true
-               :sessions true
-               :java-logging "logging.properties"
-               :log4j-logging "log4j.properties"}]
-      (println "Generating an migae project called " appname ", app id " appid ", using the 'migae' template.")
-
-      (println "\nGenerating servlets from template")
-      (doseq [s (:servlets data)]
-        (let [servlet (assoc s
-                        :appname (:appname data)
-                        :name (:name data)
-                        :projroot (:projroot data))
-              proj (name-to-path (:appname data))
-              toservlet (name-to-path (render-text "src/{{src}}" servlet))
-              toimpl (name-to-path (render-text
-                                    "src/{{appname}}/{{servlet}}"
-                                    servlet))]
-;              foo (println (format "foo: %s" toimpl))]
-          (binding [*dir* (.getPath (io/file
-                                     (System/getProperty
-                                      "leiningen.original.pwd")
-                                     (:name servlet)))]
-            (->files servlet
-                     [(str toservlet "-servlet.clj")
-                      (render "servlet.clj" servlet)]
-                     [(str toimpl "_impl.clj")
-                      (render "servlet_impl.clj" servlet)]))))
-
-      (println "\nGenerating other stuff")
-      (binding [*dir* (.getPath (io/file (System/getProperty "leiningen.original.pwd") (:name data)))]
-        (->files data
-                 ;; to file  		from template
-                 ["project.clj" (render "project.clj" data)]
-                 ["README.md" (render "README.md" data)]
-                 ["doc/intro.md" (render "intro.md" data)]
-                 [".gitignore" (render "gitignore" data)]
-
-                 ["src/{{projroot}}/reload_filter.clj"
-                  (render "reloadfilter.clj" data)]
-
-                 ;; ["src/main/java/com/google/apphosting/utils/security/SecurityManagerInstaller.java" (render "SecurityManagerInstaller.java" data)]
-
-                 ;; NB: treatment of '-', '_', '/', and '.'
-                 ;; "lein new migae foo-bar" yields:
-                 ;; src:  ns foo-bar.core in  src/foo_bar/core.clj
-                 ;; ["src/{{nested-dirs}}.clj" (render "core.clj" data)]
-
-                 ;; ;; test: foo-bar.core-test -> foo_bar/core_test.clj
-                 ["test/{{nested-dirs}}_test.clj" (render "core_test.clj" data)]
-
-                 ;; app engine config files
-                 ;; copy template w/o macro processing ('data' arg)
-                 ;; install in hidden dir?  or etc?
-                 ;; [".{{appname}}/appengine-web.xml.mustache"
-
-                 ["etc/appengine-web.xml.mustache" (render "appengine-web.xml.mustache")]
-                 ["etc/dir-locals.el.mustache" (render "dir-locals.el.mustache")]
-                 ["etc/{{java-logging}}" (render "logging.properties")]
-                 ["etc/{{log4j-logging}}" (render "log4j.properties")]
-                 ["etc/web.xml.mustache" (render "web.xml.mustache")]
-
-                 ;; resources install to source tree
-                 ;; migae plugin "config" task will copy to war tree
-
-                 ["{{statics_src}}/{{welcome}}"
-                  (render "home.html" (conj {:loc "Home"} data))]
-
-                 ["{{statics_src}}/html/{{welcome}}"
-                  (render "index.html" (conj {:loc "HTML"} data))]
-                 ["{{statics_src}}/404.html"
-                  (render "404.html" data)]
-
-                 ["{{statics_src}}/html/a/{{welcome}}"
-                  (render "index.html" (conj {:loc "A"} data))]
-                 ["{{statics_src}}/html/b/{{welcome}}"
-                  (render "index.html" (conj {:loc "B"} data))]
-                 ["{{statics_src}}/request/{{welcome}}"
-                  (render "index.html" (conj {:loc "Request"} data))]
-
-                 ["{{statics_src}}/css/{{project}}.css"
-                  (render "project.css" data)]
-                 ["{{statics_src}}/js/{{project}}.js"
-                  (render "project.js" data)]
-                 ["{{resources_src}}/favicon.ico"
-                  (render "favicon.ico" data)]
-
-                 ;; templates?
-                 ;; ["private/hiccup/{{appname}}.???" (render "..." data)]
-
-                 ;; TODO: add a spinner, favicon, or other toy graphic
-                 ;; ["public/img/{{appname}}.js" (render "public/img/foo.png" data)]
-               )))))
+    (cond
+     (= projname "app") (make-app projname args)
+     (= projname "servlet") (make-servlet projname args)
+     :else (println "bad cli"))))
+                                        ; (make-app projname args))))


Rename customer to worker. (In vacation this is called client, but this is a bit ambiguous.)


Reformatting

Reformatting

--- planck-cljs/src/planck/repl.cljs
+++ planck-cljs/src/planck/repl.cljs
@@ -18,7 +18,6 @@
 (defonce st (cljs/empty-state))

 (defn ^:export load-core-analysis-cache [json]
-  ;(println "Loading analysis cache")
   (let [rdr (transit/reader :json)
         cache (transit/read rdr json)]
     (cljs/load-analysis-cache! st 'cljs.core cache)))
@@ -73,7 +72,7 @@
                     :doc      "Prints documentation for a var or special form given its name"}
     pst            {:arglists ([] [e])
                     :doc      "Prints a stack trace of the exception.\n  If none supplied, uses the root cause of the most recent repl exception (*e)"}
-    load-file      {:arglists  ([filename])
+    load-file      {:arglists ([filename])
                     :doc      "Loads a file"}})

 (defn- repl-special-doc [name-symbol]
@@ -149,11 +148,11 @@
   [filename]
   (try
     (let [file-contents (or (js/PLANCK_READ_FILE filename)
-                            (throw (js/Error. (str "Could not load file " filename))))]
+                          (throw (js/Error. (str "Could not load file " filename))))]
       (cljs/eval-str
         st
-       file-contents
-       filename
+        file-contents
+        filename
         {:ns      @current-ns
          :verbose (:verbose @app-env)}
         (fn [{e :error}]
@@ -375,8 +374,7 @@
                          print-error)
                        (catch js/Error e (prn :caught e))))
             load-file (let [filename (second expression-form)]
-                        (process-load-file filename))
-            )
+                        (process-load-file filename)))
           (prn nil))
         (try
           (cljs/eval-str


Fix so that *1 is nil

Fix so that *1 is nil

--- planck-cljs/src/planck/repl.cljs
+++ planck-cljs/src/planck/repl.cljs
@@ -1149,7 +1149,8 @@
      :ex-stack-fn ansi/green
      :err-font ansi/red-font
      :verbose-font ansi/cyan-font
-     :reset-font ansi/reset-font}))
+     :reset-font ansi/reset-font})
+  nil)

 (defn- ^:export wrap-color-err
   []


First section 'Board and tiles'

First section 'Board and tiles'

--- src/literate_2048/core.cljs
+++ src/literate_2048/core.cljs
@@ -6,6 +6,73 @@

 ;; # Board and tiles

+;; The board on which the game is played consist of 16 squares ordered in 4 rows
+;; and 4 columns. People seem to get really mad when they see the same number
+;; over and over again, so let's give the number 4 a better name.
+
+(def
+  ^{:doc "Number of squares on a board's row or column. It is also the count of
+          rows and columns and the square root of the total number of squares."}
+  board-order 4)
+
+;; The choosen representation for the board is a vector of 16 (4*4) elements.
+;; It will contain the squares from the first row, followed by the squares from
+;; the second, and so on. Intuitively, it seems that the natural representation
+;; for such a board is a vector of vectors, but it will make things more
+;; complicated than they need to be.
+
+;; The simplest board, and our starting point, is one that is completely empty.
+;; An empty square is represented by nil.
+
+(def
+  ^{:doc "A vector of board-order^2 nils."}
+  empty-board (vec (repeat (* board-order board-order) nil)))
+
+;; Every time a tile is added to the board, it randomly appears in a empty
+;; square, with a value of either 2 or 4.
+
+;; It's easy to decide the value of the new tile.
+
+(defn rand-val
+  "Returns 2 most of the time, but sometimes it returns 4."
+  []
+  (if (< (rand) 0.8) 2 4))
+
+;; It's also easy to choose the empty square where the tile will be placed: get
+;; the indexes of the nil elements of the board representation, shuffle them and
+;; take the first.
+
+(defn nil-indexes
+  "Returns a set with the indexes of the nil elements of v."
+  [v]
+  (into #{} (for [i (range (count v)) :when (nil? (get v i))] i)))
+
+(defn rand-nil-index
+  "Returns the index of a randomly choosen nil element of v."
+  [v]
+  (-> v nil-indexes shuffle first))
+
+;; Finally, associate the index with a new tile in the board representation. A
+;; function that builds the tile from its value must be provided because the
+;; details about what a tile looks like aren't really important and somebody
+;; else should take care of them.
+
+(defn add-tile
+  "Takes a board and returns a new one with one more tile, where tile-fn is a
+   function that will take a randomly choosen tile value and return a new tile."
+  [tile-fn board]
+  (assoc board (rand-nil-index board) (tile-fn (rand-val))))
+
+;; All the conditions are now met to build a board with two tiles, which is
+;; necessary for the player to make the first move.
+
+(defn initial-board
+  "Returns a board with two (random) tiles, where tile-fn is a function that
+   will take a randomly choosen tile value and return a new tile."
+  [tile-fn]
+  (let [f (partial add-tile tile-fn)]
+    (-> empty-board f f)))
+
 ;; # Tile synthesis

 ;; # Moves


Updated error and logging messages for validation.

--- src/cmr/ingest/services/validation.clj
+++ src/cmr/ingest/services/validation.clj
@@ -1,6 +1,7 @@
 (ns cmr.ingest.services.validation
   "Provides functions to validate concept"
-  (:require [cmr.common.services.errors :as err]))
+  (:require [cmr.common.services.errors :as err]
+            [clojure.string :as s]))

 ;; body element (metadata) of a request arriving at ingest app should be in xml format and mime type
 ;; should be of the items in this def.
@@ -15,14 +16,14 @@
     (if (contains? CMR_VALID_CONTENT_TYPES content-type)
       []
       [(format "Invalid content-type: %s. Valid content-types: %s."
-               content-type CMR_VALID_CONTENT_TYPES)])))
+               content-type (s/join ", " CMR_VALID_CONTENT_TYPES))])))

 (defn- metadata-length-validation
   "Validates the metadata length is not unreasonable."
   [concept]
   (if (> (count (:metadata concept)) 4)
     []
-    ["Invalid XML content."]))
+    ["XML content is too short."]))

 (def concept-validations
   "A list of the functions that can validate concept."


Removed ruggero.clj

Removed ruggero.clj

--- clojure/org/gavrog/clojure/ruggero.clj
+++ clojure/org/gavrog/clojure/ruggero.clj
@@ -1,43 +0,0 @@
-(ns org.gavrog.clojure.ruggero
-  (:use (org.gavrog.clojure
-          [delaney]
-          [delaney2d]
-          [generators :only [results]]
-          [combineTiles :only [combine-tiles]]))
-  (:gen-class))
-
-(def triangle
-  (dsymbol "1.1:6 1:2 4 6,6 3 5:3"))
-
-(def quadrangle
-  (dsymbol "1.1:8 1:2 4 6 8,8 3 5 7:4"))
-
-(defn- orbit-complete? [ds indices D]
-    (empty? (for [D (orbit-elements ds indices [D])
-                  i indices
-                  :when (nil? (s ds i D))] [D i])))
-
-(defn- good-orbit? [ds [i j] D]
-  (or (not (orbit-complete? ds [i j] D))
-      (#{3 4} (r ds i j D))))
-
-(defn- good? [ds]
-  (and (every? #(not= % (s ds 2 %)) (elements ds))
-       (every? (partial good-orbit? ds [1 2]) (orbit-reps ds [1 2]))))
-
-(defn- complete [ds]
-  (let [ops* (ops ds)
-        vs* (into {} (for [i (indices ds) :when (index? ds (inc i))]
-                       [i (into {} (for [D (elements ds)]
-                                     [D (or (v ds i (inc i) D) 1)]))]))]
-    (make-dsymbol (dim ds) (size ds) ops* vs*)))
-
-(defn self-dual-3-4-regular [n]
-  (for [i (range (inc (- n 4)))
-        :let [face-list (apply append (concat (repeat 4 triangle)
-                                              (repeat i quadrangle)))]
-        set (map complete
-                 (results (combine-tiles face-list) (comp good? first)))
-        :when (and (self-dual? set) (proto-spherical? set))
-        ]
-    set))


Ring middleware: Combine single wrappings into a single `facts`

--- test/com/nomistech/clojure_the_language/c_800_libraries/s_800_web/ss_020_ring.clj
+++ test/com/nomistech/clojure_the_language/c_800_libraries/s_800_web/ss_020_ring.clj
@@ -40,42 +40,41 @@
   (instance? java.io.InputStream x))

 ;;;; ___________________________________________________________________________
-;;;; ---- rmp/wrap-params ----
+;;;; ---- Single wrappings ----

-(fact ((-> identity-handler
-           rmp/wrap-params)
-       (make-my-request))
-  => (just {:headers      {"content-type" "application/json; charset=utf-8"}
-            :query-string "q1=a&q2=b"
-            :body         input-stream?
-            :form-params  {}
-            :query-params {"q1" "a"
-                           "q2" "b"}
-            :params       {"q1" "a"
-                           "q2" "b"}}))
+(facts "Single wrappings"
+
+  (fact "`rmp/wrap-params`"
+    ((-> identity-handler
+         rmp/wrap-params)
+     (make-my-request))
+    => (just {:headers      {"content-type" "application/json; charset=utf-8"}
+              :query-string "q1=a&q2=b"
+              :body         input-stream?
+              :form-params  {}
+              :query-params {"q1" "a"
+                             "q2" "b"}
+              :params       {"q1" "a"
+                             "q2" "b"}}))
+
+  (fact "`rmj/wrap-json-params`"
+    ((-> identity-handler
+         rmj/wrap-json-params)
+     (make-my-request))
+    => (just {:headers      {"content-type" "application/json; charset=utf-8"}
+              :query-string "q1=a&q2=b"
+              :body         input-stream?
+              :json-params  {"user" "Fred"}
+              :params       {"user" "Fred"}}))

-;;;; ___________________________________________________________________________
-;;;; ---- rmj/wrap-json-params ----
-
-(fact ((-> identity-handler
-           rmj/wrap-json-params)
-       (make-my-request))
-  => (just {:headers      {"content-type" "application/json; charset=utf-8"}
-            :query-string "q1=a&q2=b"
-            :body         input-stream?
-            :json-params  {"user" "Fred"}
-            :params       {"user" "Fred"}}))
-
-;;;; ___________________________________________________________________________
-;;;; ---- rmj/wrap-json-body ----
-
-(fact ((-> identity-handler
-           (rmj/wrap-json-body {:keywords? true
-                                :bigdecimals? true}))
-       (make-my-request))
-  => {:headers      {"content-type" "application/json; charset=utf-8"}
-      :query-string "q1=a&q2=b"
-      :body         {:user "Fred"}})
+  (fact "`rmj/wrap-json-body`"
+    ((-> identity-handler
+         (rmj/wrap-json-body {:keywords? true
+                              :bigdecimals? true}))
+     (make-my-request))
+    => {:headers      {"content-type" "application/json; charset=utf-8"}
+        :query-string "q1=a&q2=b"
+        :body         {:user "Fred"}}))

 ;;;; ___________________________________________________________________________


Stubs out an empty user profile and complete training functionallity.


cleanup not working stuff

cleanup not working stuff


Sketch of async pipeline.

Sketch of async pipeline.

--- src/connect5_ai/core.clj
+++ src/connect5_ai/core.clj
@@ -1,5 +1,5 @@
 (ns connect5-ai.core
-  (:require [clojure.core.async :as casync]
+  (:require [clojure.core.async :as async]
             clojure.set)
   (:gen-class))

@@ -72,15 +72,18 @@
     ))

 (defn minimax-decision
-  [grid-w grid-h is-first-player state]
+  [grid-w grid-h is-first-player state timeout]

   (println grid-w grid-h is-first-player state)
   (if (and
         is-first-player
         (empty? (state :1)))
+    ; Return a vector
+    ; If the board is empty and we are player 1
     [(long (/ grid-w 2)) (long (/ grid-h 2))]
+    ; Otherwise

-    [2 3]
+
     ;(gen-successors grid-w grid-h is-first-player state)
     ))

@@ -94,5 +97,46 @@
     (minimax-decision (count (first charmat-seq))
                       (count charmat-seq)
                       is-first-player
-                      state)))
+                      state
+                      timeout)))

+(defn chantest
+  []
+
+  (let [c (async/chan (async/sliding-buffer 1))
+        heuristic-c (async/chan (async/sliding-buffer 1))
+        timeout-chan (async/timeout 2000)]
+    (async/go
+      ; Compute layers and feed them to the channel as long as it's opened.
+      (loop [x 0]
+
+        (if ;(not last-chan-op-result)
+            (clojure.core.async.impl.protocols/closed? heuristic-c)
+          (println "Chan c was closed. Has stopped digging down layers")
+          (do
+            ;(Thread/sleep (rand-int 300))
+            (println "Computed configurations of layer " x)
+            (async/>! c x)
+            (recur (inc x))))))
+    (letfn [(chan-taker [] (async/alts!! [timeout-chan c] :priority true))]
+      (async/go
+
+      (loop [[result source] (chan-taker)]
+        (if (not result)
+          (do
+            (println "Chan h was closed. Has stopped minimaxing"))
+          (do
+            (println "Started Calculating heuristic val of layer " result)
+            ;(Thread/sleep (rand-int 600))
+            (println "Done    Calculating heuristic val of layer " result)
+            (async/>! heuristic-c result)
+            (recur (chan-taker)))))))
+    ; Let's block on the timeout channel
+    (async/<!! timeout-chan)
+    ; We must stop this madness, close those chans!
+    (async/close! c)
+    (async/close! heuristic-c)
+    ; We return the last value found in the heuristic-channel (If there is none, we're damned. We be blocking here)
+    ; Todo: Use alts! to get a value and not say here forever.
+    (async/<!! heuristic-c)))
+


Minor: reformat

Minor: reformat

--- test/yadic/core_test.clj
+++ test/yadic/core_test.clj
@@ -162,10 +162,10 @@

 (fact "Destructors aren't called if the instance isn't realised"
   (let [close-order (atom [])
-        activators       (->activators
-                           :a (close-recording close-order
-                                         (concrete "never-activated")))
-        container        (->container activators)]
+        activators  (->activators
+                      :a (close-recording close-order
+                           (concrete "never-activated")))
+        container   (->container activators)]
     (.close container)
     @close-order => []))


Gray out and rearrange code.

Gray out and rearrange code.

--- src/constraint/core.cljs
+++ src/constraint/core.cljs
@@ -11,6 +11,8 @@
     [goog.net.XhrIo :as xhr]
     [cljs.core.async :as async :refer [<! chan close!]]))

+
+
 (defn GET [url]
   (let [ch (chan 1)]
     (xhr/send url
@@ -21,30 +23,43 @@
     ch))

+
 (defn make-triangle-marker [id arrow]
   [:svg:marker
    {:id id
     :viewBox "-5 -5 20 20"
     :refX "5"
     :refY "5"
-    :markerWidth "7"
-    :markerHeight "7"
+    :markerWidth "5"
+    :markerHeight "5"
     :orient "auto"}
    arrow])

+
+(def color->value {:red 1
+                   :blue 2})
+
+(def arrow-path "M0,0 L 10,5 L0,10 z")
+
 (def triangle-marker-ok
   (make-triangle-marker "TriangleOK"
-        [:svg:path {:fill "white" :stroke "black" :d "M0,0 L 10,5 L0,10 z"}]))
+                        [:svg:path {:fill "white"
+                                    :stroke "black"
+                                    :d arrow-path}]))

 (def triangle-marker-not-ok
   (make-triangle-marker "TriangleNotOK"
-    [:svg:path {:fill "black" :stroke "black" :d "M0,0 L 10,5 L0,10 z"}]))
+                        [:svg:path {:fill "black"
+                                    :stroke "black"
+                                    :d arrow-path}]))
+

 (defn make-line-dirs [from to]
   (let [middle (map (comp #(/ % 2) +) from to)
         coords (map (partial string/join ",") [from middle to])]
     (string/join " " (map str ["M" "L" "L"] coords))))
+

 (defn svg-edge [[id [from to color flippable?]]]
@@ -61,14 +76,17 @@
     :opacity 0.6
     }])

-(def color->value {:red 1
-                   :blue 2})
+
+
+

 (defn inflow [edges vertex]
   (let [in-going (for [[_ [_ to color]] edges
                        :when (= to vertex)]
                    (color->value color))]
     (apply + in-going)))
+
+

 (defn svg-vertex [edges id [weight [x y]]]
   (let [vert-inflow (inflow edges id)
@@ -79,7 +97,7 @@
         :r (+ 5 (* weight 10))
         :fill (if (> free 0)
                 "white"
-                "black ")
+                "gray")
         :stroke "black"
         :stroke-width 3
         }]
@@ -90,6 +108,8 @@
        (str free) ]))
   )

+
+
 (defn event->targetid [e]
   (-> e
       (js->clj)
@@ -97,16 +117,20 @@
       (.-id)))

+
 (defn name-edges [bare-edges]
   (let [edge-ids (map (partial str "edge") (range))]
     (into {}
         (map vector edge-ids bare-edges))))
+
+

 (defn ok-to-flip? [{:keys [vertices edges]} [_ to color]]
   (let [edge-value (color->value color)
         to-inflow (inflow edges to)
         to-vertex-value (first (vertices to))]
     (>= (- to-inflow edge-value) to-vertex-value)))
+

 (defn prepare-edge [locations world-state [start end color :as edge]]
@@ -116,14 +140,15 @@
    (ok-to-flip? world-state edge)])

+
 (defn fmap [f m]
   (into {} (for [[k v] m] [k (f v)])))

+
 (defn make-edges [{:keys [vertices edges] :as world-state}]
   (let [locations (mapv second vertices)]
-    (fmap (partial prepare-edge locations world-state) edges)
-    ))
+    (fmap (partial prepare-edge locations world-state) edges)))

@@ -133,9 +158,7 @@
     triangle-marker-ok
     triangle-marker-not-ok]
    (map svg-edge (make-edges world-state))
-   (map (partial svg-vertex edges) (range) vertices)
-
-   ])
+   (map (partial svg-vertex edges) (range) vertices)])

@@ -152,12 +175,15 @@
     edge))

+
 (defn update-state [event world-state]
   (let [clicked-what (event->targetid event)
         constrained-flip (partial flip-edge world-state)]
     (if (re-matches #"edge.*" clicked-what)
       (update-in world-state [:edges clicked-what] constrained-flip)
       world-state)))
+
+

 (go
   (let [vertices (<! (GET "./vertices.edn"))


Update cider-nrepl

Update cider-nrepl

--- roles/clojure/files/profiles.clj
+++ roles/clojure/files/profiles.clj
@@ -10,7 +10,7 @@
                        [org.clojure/tools.nrepl "0.2.7"]
                        [slamhound "1.5.3"]]

-        :plugins [[cider/cider-nrepl "0.9.0"]
+        :plugins [[cider/cider-nrepl "0.9.1-SNAPSHOT"]
                   [codox "0.6.6"]
                   [jonase/eastwood "0.2.1"]
                   [lein-clojars "0.9.1"]


experimenting with an alternative architecture regarding the Sigma react components

--- cljx/plongeur-cljs/src/plongeur/view.cljs
+++ cljx/plongeur-cljs/src/plongeur/view.cljs
@@ -1,9 +1,9 @@
 (ns plongeur.view
-  (:require [cljs.core.async :as a :refer [>! chan pipe]]
+  (:require [cljs.core.async :as a :refer [>! chan pipe close!]]
             [quiescent.core :as q :include-macros true :refer-macros [defcomponent]]
             [sablono.core :refer-macros [html]]
             [plongeur.model :as m]
-            [plongeur.sigma-driver :as s])
+            [plongeur.sigma :as s])
   (:require-macros [cljs.core.async.macros :refer [go]]))

 (defn upgrade-mdl-components
@@ -11,35 +11,53 @@
   []
   (js/setInterval #(.upgradeDom js/componentHandler) 100))

-(def node-1 {:id "n1"
-             :label "hello"
-             :x 10
-             :y 10
-             :size 1
-             :color "#FF0"})

-(defn graph-id [id] (str "graph-" id))
+(let [sigma-state (atom {})]
+  (defcomponent Card
+    :keyfn (fn [[id _]] id)

-(defcomponent Sigma
-  :keyfn      (fn [[id _]] id)
-  :on-mount   (fn [_ [id _] {:keys [sigma-ctrl]}] (go (>! sigma-ctrl (s/ctrl-update id))))
-  :on-unmount (fn [_ [id _] {:keys [sigma-ctrl]}] (go (>! sigma-ctrl (s/ctrl-remove id))))
-  [[id props] {:keys [drop-graph] :as intent-chans}]
-  (html [:div {:class-name "mdl-cell mdl-cell--6-col-desktop mdl-cell--6-col-tablet mdl-cell--6-col-phone"}
-         [:div {:class-name "mdl-card mdl-shadow--2dp"}
+    :on-mount (fn [node [id _] {:keys [sigma-ctx]}]
+                (prn "on-mount" @sigma-state)
+                (swap! sigma-state assoc id {:ch (chan 10)})

-          [:div {:class-name "mdl-card__supporting-text"}
-           [:div {:id (graph-id id)
-                  :class-name "graph"}]]
+                ;TODO explore

-          [:div {:class-name "mdl-card__title"}
-           [:button {:on-click   #(go (>! drop-graph id))
-                     :class-name "mdl-button mdl-js-button mdl-js-ripple-effect"} "delete " id]]
+                ;(go (>! update-sigma [id cmd-chans]))
+                )

-          ]]))
+    :on-unmount (fn [_ [id _] {:keys [sigma-ctx]}]
+                  (prn "on-unmount" @sigma-state)
+                  (swap! sigma-state
+                         (fn [m]
+                           (-> id m :ch close!)
+                           (dissoc m id)))
+
+                  ;(go (>! remove-sigma id))
+                  )
+
+    [[id props] {:keys [drop-graph] :as cmd-chans}]
+    (html [:div {:class-name "mdl-cell mdl-cell--6-col-desktop mdl-cell--6-col-tablet mdl-cell--6-col-phone"}
+           [:div {:class-name "mdl-card mdl-shadow--2dp"}
+
+            [:div {:class-name "mdl-card__supporting-text"}
+
+             ;; Factor out in a React component as minimal as possible.
+             ;; make the sigma state atom scope wrap this component.
+             [:div {:id         (s/graph-id id)
+                    :class-name "graph"}]]
+
+            [:div {:class-name "mdl-card__title"}
+             [:button {:on-click   #(go (>! drop-graph id))
+                       :class-name "mdl-button mdl-js-button mdl-js-ripple-effect"} "delete " id]]
+
+            ]])))
+
+;; TODO
+;; TODO factor out layout components: header, drawer, content, etc...
+;; TODO

 (defcomponent Root
-  [state {:keys [add-graph debug] :as intent-chans}]
+  [state {:keys [add-graph debug] :as cmd-chans}]

   (html [:div {:id "plongeur-main"} ;; extra wrapper for MDL React bug

@@ -72,6 +90,10 @@
                  :href "config.html"}
              [:i {:class-name "material-icons"
                   :role       "presentation"} "reorder"] "Logs"]
+            [:button {:on-click   #(go (>! add-graph :click))
+                      :hidden     (>= (m/graph-count state) 4)
+                      :class-name "mdl-button mdl-js-button mdl-button--fab mdl-button--colored"}
+             [:i {:class-name "material-icons"} "add"]]

             [:div {:class-name "mdl-layout-spacer"}]

@@ -92,58 +114,24 @@
             [:div {:class-name "mdl-grid mdl-cell mdl-cell--9-col-desktop mdl-cell--12-col-tablet mdl-cell--4-col-phone mdl-cell--top"}

              (for [graph-state (m/graphs state)]
-               (Sigma graph-state intent-chans))
+               (Card graph-state cmd-chans))

              ]]]

-          ]])
-
-  #_(html [:div {:id "plongeur-main"}
-         [:div {:id         "layout"
-                :class-name "demo-layout mdl-layout mdl-js-layout mdl-layout--fixed-drawer mdl-layout--fixed-header"}
-
-          [:header {:class-name "demo-header mdl-layout__header mdl-color--grey-100 mdl-color-text--grey-600"}
-           [:div {:class-name "mdl-layout__header-row"}
-            [:span {:class-name "mdl-layout-title"} "Home"]
-            [:div {:class-name "mdl-layout-spacer"}]
-            [:button {:class-name "mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--icon"
-                      :id         "hdrbtn"}
-             [:i {:class-name "material-icons"} "more_vert"]]
-            [:ul {:class-name "mdl-menu mdl-js-menu mdl-js-ripple-effect mdl-menu--bottom-right"
-                  :for        "hdrbtn"}
-             [:li {:class-name "mdl-menu__item"} "About"]
-             [:li {:class-name "mdl-menu__item"} "Contact"]]]]
-
-          [:div {:class-name "demo-drawer mdl-layout__drawer mdl-color--blue-grey-900 mdl-color-text--blue-grey-50"}
-           [:header {:class-name "demo-drawer-header"}
-            [:div {:class-name "demo-avatar-dropdown"}
-             [:span {} "Plongeur"]]]
-           [:nav {:class-name "demo-navigation mdl-navigation mdl-color--blue-grey-800"}
-            [:a {:class-name "mdl-navigation__link"
-                 :href ""}
-             [:i {:class-name "mdl-color-text--blue-grey-400 material-icons"
-                  :role "presentation"} "home"] "home"]
-            [:a {:class-name "mdl-navigation__link"
-                 :href ""}
-             [:i {:class-name "mdl-color-text--blue-grey-400 material-icons"
-                  :role "presentation"} "settings"] "settings"]]]
-
-          [:main {:class-name "mdl-layout__content mdl-color--grey-100"}
-           [:button {:on-click   #(go (>! debug :click))
-                     :class-name "mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent"} "print state"]
-           (for [graph-state (m/graphs state)]
-             (Sigma graph-state intent-chans))
-           [:button {:on-click   #(go (>! add-graph :click))
-                     :hidden     (>= (-> state :graphs count) 4)
-                     :class-name "mdl-button mdl-js-button mdl-button--fab mdl-button--colored"}
-            [:i {:class-name "material-icons"} "add"]]]]])
-
-              )
+          ]]))

 (defn view
   "Returns a stream of view trees, represented as a core.async channel."
-  [states-chan intent-chans]
-  (->> (fn [state] (Root state intent-chans)) ; fn
-       (map)                                  ; xf
-       (chan 10)                              ; ch
-       (pipe states-chan)))+  [states-chan cmd-chans]
+  (->> (fn [state] (Root state cmd-chans)) ; fn
+       (map)                               ; xf
+       (chan 10)                           ; ch
+       (pipe states-chan)))
+
+
+#_(def node-1 {:id "n1"
+               :label "hello"
+               :x 10
+               :y 10
+               :size 1
+               :color "#FF0"})


removed unnecessary prints

removed unnecessary prints


Fix automatic output-to for modules based on module key

--- src/adzerk/boot_cljs/middleware.clj
+++ src/adzerk/boot_cljs/middleware.clj
@@ -30,10 +30,6 @@
 (defn- cljs-edn-path->js-path
   [cljs-edn-path]
   (str (.replaceAll cljs-edn-path "\\.cljs\\.edn$" "") ".js"))
-
-(defn- cljs-edn-path->module-path
-  [cljs-edn-path module-k]
-  (.getPath (io/file (str (.replaceAll cljs-edn-path "\\.cljs\\.edn$" "")) (str (name module-k) ".js"))))

 ;; middleware ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

@@ -105,7 +101,7 @@
                        (map (fn [[k v]]
                               [k (if-let [output-to (:output-to v)]
                                    (assoc v :output-to (util/path tmp-out output-to))
-                                   (assoc v :output-to (util/path tmp-out (cljs-edn-path->module-path (:rel-path main) k))))])
+                                   (assoc v :output-to (util/path (-> ctx :opts :output-dir) (str (name k) ".js"))))])
                             modules))))
     ctx))


executor splits command string

executor splits command string

--- src/riak_mesos/executor.clj
+++ src/riak_mesos/executor.clj
@@ -14,7 +14,7 @@
                                                               :message "Riak Task is running" } ))
                  (frameworkMessage [driver bytes] (let [command-string (read-string (String. bytes "UTF-8"))]
                                                     (println "[frameworkMessage] Running command " command-string )
-                                                    (future (apply clojure.java.shell/sh  command-string ))))))
+                                                    (future (apply clojure.java.shell/sh  (clojure.string/split command-string #"\s+") ))))))


api: parse time intervals as provided by grafana

--- src/io/cyanite/api.clj
+++ src/io/cyanite/api.clj
@@ -2,6 +2,7 @@
   "Cyanite's 'HTTP interface"
   (:require [com.stuartsierra.component :as component]
             [cheshire.core              :as json]
+            [clj-time.core              :as t]
             [io.cyanite.engine.rule     :as rule]
             [io.cyanite.engine          :as engine]
             [io.cyanite.engine.queue    :as q]
@@ -11,16 +12,48 @@
             [io.cyanite.query           :as query]
             [io.cyanite.http            :as http]
             [io.cyanite.utils           :refer [nbhm assoc-if-absent! now!]]
+            [clj-time.coerce            :refer [to-epoch]]
             [clojure.tools.logging      :refer [info debug error]]
             [clojure.string             :refer [lower-case blank?]]))
+
+
+(defn sub-time
+  [s]
+  (let [[_ value unit] (re-find #"^([0-9]+)([a-z])" s)]
+    (when-not (and value unit)
+      (throw (ex-info (str "invalid time interval: " s) {:value value
+                                                         :unit unit})))
+    (when (and value unit)
+      (to-epoch
+       (t/minus (t/now)
+                ((case unit
+                   "s" t/seconds
+                   "m" t/minutes
+                   "h" t/hours
+                   "d" t/days
+                   "w" t/weeks
+                   t/seconds)
+                 (Long/valueOf value)))))))

 (defn parse-time
   "Parse an epoch into a long"
   [time-string]
-  (try (Long/parseLong time-string)
-       (catch NumberFormatException _
-         (error "wrong time format: " time-string)
-         nil)))
+  (cond
+    (nil? time-string)
+    nil
+
+    (= time-string "now")
+    (now!)
+
+    (.startsWith time-string "-")
+    (sub-time (.substring time-string 1))
+
+
+    :else
+    (try (Long/parseLong time-string)
+         (catch NumberFormatException _
+           (error "wrong time format: " time-string)
+           nil))))

 (def routes
   "Dead simple router"


Use some-> instead of when-let

Use some-> instead of when-let


implemented task  analyze-categories

implemented task  analyze-categories

--- src/distillery/tasks.clj
+++ src/distillery/tasks.clj
@@ -40,6 +40,19 @@
   controls whether `pmap` or `map` is returned."
   []
   (if (cfg/value :parallel-proc) pmap map))
+(def ^:private filter-map
+  {:not-short proc/not-short?
+   :noun proc/noun?
+   :min-confidence proc/min-confidence?
+   :good-confidence proc/good-confidence?
+   :no-punctuation proc/no-punctuation?
+   :not-in-blacklist bl/not-in-blacklist?})
+
+(defn- word-predicate
+  "Create the word predicate for the video index."
+  [{:keys [configuration] :as job}]
+  (let [filters (map #(% filter-map) (cfg/value :index-filter configuration))]
+    (partial multi-filter (filter #(not (nil? %)) filters))))

 ;; ## Task Functions
@@ -59,6 +72,8 @@

 ;; ### Preprocessing, Analysis

+;; #### Categories
+
 (defn- load-category-resource
   "Loads a single resource for a category."
   [{:keys [id]} {:keys [type url] :as resource}]
@@ -89,11 +104,43 @@
      (doall (map #(load-category-resources %) categories)))))

+(defn- build-category-words
+  [{:keys [id words] :as category}]
+  (trace-message "Building words for category '" id "'")
+  (assoc category :words
+    (map-indexed
+     (fn [i w] {:no i
+                :text w
+                :lexical-form w
+                :confidence 1})
+     words)))
+
+
+(defn- build-category-index
+  [job category]
+  (trace-message "Building index for category '" (:id category) "'")
+  (let [index (proc/category-index category :predicate (word-predicate job))]
+    (assoc category :index index)))
+
+
 (defn analyze-categories
   "Analyzes the categories and generates the index structures."
   [job]
-  (println "TODO: tasks/analyze-categories")
-  job)
+  (trace-block
+   "Analyzing categories"
+   (let [job* (update-in
+               job [:categories]
+               (fn [categories]
+                 (vec ((map-fn)
+                       (fn [category]
+                         (build-category-index
+                          job
+                          (build-category-words category)))
+                       categories))))]
+     job*)))
+
+
+;; #### Speech Recognition Results

 (defn- load-speech-recognition-result
@@ -126,21 +173,6 @@
       :word-count (count (proc/words results))
       :confidence (mean (map :confidence results))
       :duration duration)))
-
-
-(def ^:private filter-map
-  {:not-short proc/not-short?
-   :noun proc/noun?
-   :min-confidence proc/min-confidence?
-   :good-confidence proc/good-confidence?
-   :no-punctuation proc/no-punctuation?
-   :not-in-blacklist bl/not-in-blacklist?})
-
-(defn- word-predicate
-  "Create the word predicate for the video index."
-  [{:keys [configuration] :as job}]
-  (let [filters (map #(% filter-map) (cfg/value :index-filter configuration))]
-    (partial multi-filter (filter #(not (nil? %)) filters))))

 (defn- build-video-index


Fix unfold's type signature to be manageable

--- src/useful/seq.clj
+++ src/useful/seq.clj
@@ -123,26 +123,21 @@
   seed value into a (possibly infinite) lazy sequence of output
   values.

-  Next and done? are functions that operate on a seed. next should
+  Next is a function that operate on a seed: it should
   return a pair, [value new-seed]; the value half of the pair is
-  inserted into the resulting list, while the new-seed is used to
+  inserted into the resulting list, while the new seed is used to
   continue unfolding. Notably, the value is never passed as an
-  argument to either next or done?.
-
-  If done? is omitted, the sequence will be unfolded forever, for
-  example
+  argument to next. If nil is returned instead of a pair, the resulting
+  sequence will terminate.
+
   (defn fibs []
     (unfold (fn [[a b]]
               [a [b (+ a b)]])
             [0 1]))"
-  ([next seed]
-     (unfold next (constantly false) seed))
-  ([next done? seed]
-     (lazy-loop [seed seed]
-       (when-not (done? seed)
-         (let [[value new-seed] (next seed)]
-           (cons value
-                 (lazy-recur new-seed)))))))
+  [next seed]
+  (lazy-loop [seed seed]
+    (when-let [[val seed] (next seed)]
+      (cons val (lazy-recur seed)))))

 (defn take-shuffled
   "Lazily take (at most) n elements at random from coll, without


not important

not important


minor

minor

--- cljs-server/cljs_cheatsheet_server/core.cljs
+++ cljs-server/cljs_cheatsheet_server/core.cljs
@@ -2,18 +2,17 @@
   (:require-macros
     [hiccups.core :as hiccups])
   (:require
-    [cljs.reader :refer [read-string]]
     [clojure.string :refer [blank? join replace]]
     [cljs-cheatsheet.util :refer [docs-href js-log log]]
     [hiccups.runtime :as hiccupsrt]))

-;; The main purpose of this file is to produce public/index.html
-
-;; NOTE: this file is pretty messy; it could stand to be cleaned up and
-;;       organized into namespaces
+;; This file produces:
+;; - public/index.html
+;; - symbols.json
+
+;; NOTE: this file is pretty messy; it could stand to be cleaned up some

 (def fs (js/require "fs"))
-(def marked (js/require "marked"))

 (def html-encode js/goog.string.htmlEscape)


update the example closure pact test

update the example closure pact test

--- pact-jvm-consumer-junit/src/test/java/au/com/dius/pact/consumer/ExampleClojureConsumerPactTest.clj
+++ pact-jvm-consumer-junit/src/test/java/au/com/dius/pact/consumer/ExampleClojureConsumerPactTest.clj
@@ -17,7 +17,9 @@
                             .toFragment)
         config (MockProviderConfig. 23456 "localhost")]
     (is (= (ConsumerPactTest/PACT_VERIFIED)
-          (.runConsumer consumer-fragment config
-            #(is (= 200
+        (.runConsumer consumer-fragment config
+          (proxy [TestRun] []
+            (run [_] (
+               #(is (= 200
                    (:status
-                     @(http/get (str (.url config) "/sample"))))))))))
+                     @(http/get (str (.url config) "/sample")))))))))))))


Cast env numerics to Integer

Cast env numerics to Integer

--- server/src/patavi/server/handlers.clj
+++ server/src/patavi/server/handlers.clj
@@ -15,11 +15,11 @@
 (def service-status-uri (str base "status#"))
 (def silence-timeout
   (if (env :patavi-task-silence-timeout)
-    (env :patavi-task-silence-timeout)
+    (Integer. (env :patavi-task-silence-timeout))
     (throw (RuntimeException. "PATAVI_TASK_SILENCE_TIMEOUT not set"))))
 (def global-timeout
   (if (env :patavi-task-global-timeout)
-    (env :patavi-task-global-timeout)
+    (Integer. (env :patavi-task-global-timeout))
     (throw (RuntimeException. "PATAVI_TASK_GLOBAL_TIMEOUT not set"))))

 (defn- current-time []


also load all the rope stuff

also load all the rope stuff

--- src/engine/repl_init.clj
+++ src/engine/repl_init.clj
@@ -6,4 +6,4 @@
 (set-loggers! :root
               {:pattern "%d %-5p [%t]: %m%n" :level :debug :out *out*})

-(require 'engine.core 'engine.client 'engine.client.commands 'engine.server.rope)
+(require 'engine.core 'engine.client 'engine.client.commands 'engine.server.rope 'engine.devel.rope)


Remove extraneous function.

Remove extraneous function.

--- src/flatland/handler.clj
+++ src/flatland/handler.clj
@@ -73,15 +73,12 @@
   ;; using a regex here to avoid parsing the markdown html back into hiccup data
   (clojure.string/replace template #"

" content))

-(defn- render-post-with-template
-  [name]
-  (render-with-template template (render-post name)))
-
 (defn- render-index
   []
   (render-with-template template (html (for [post (map #(get posts %) (keys posts))]
                                          [:section {:class "post"}
-                                          [:h3 (:title post)]
+                                          [:h3
+                                           [:a {:href (str (:base-url config) "posts/" ())}] (:title post)]
                                           [:p (:content post)]]))))

 (defroutes app


playing around with constrained records.  doesn't work yet

--- src/fogus/me/trammel.clj
+++ src/fogus/me/trammel.clj
@@ -257,3 +257,27 @@

   (sqr 0)
 )
+
+(defmacro defconstrainedrecord
+  [name slots & etc]s
+  (let [fields   (->> slots (partition 2) (map first) vec)
+        defaults (->> slots (partition 2) (map second))]
+    `(do
+      (defrecord ~name
+         ~fields
+         )
+       (defconstrainedfn ~(symbol (str "new-" name))
+         [& {:keys ~fields :as kwargs#}]
+         :body
+         (-> (~(symbol (str name \.)) ~@defaults)
+             (merge kwargs#))
+         ~@etc)
+       ~name)))
+
+(comment
+  (defconstrainedrecord Foo [a b]
+    :requires (every? number? [a b])
+    :body
+    Object
+    (toString [this] (str "record Foo has " a " and " b)))
+)


Remove old comments

Remove old comments

--- src/graphql_clj/spec.clj
+++ src/graphql_clj/spec.clj
@@ -72,7 +72,7 @@
   ([name] (str/replace name #"\!$" ""))
   ([namespace name] (keyword namespace (remove-required name))))

-(defn- to-type-name [{:keys [type-name required]}] ;; TODO required is not supported for non-scalar types
+(defn- to-type-name [{:keys [type-name required]}]
   (if (and required (base-type-names (name type-name))) (add-required type-name) (name type-name)))

 (defn- spec-namespace [{:keys [schema-hash statement-hash]} path] ;; TODO make schema vs. statement hash decision upstream
@@ -224,7 +224,7 @@
     (register-type-field n s)))

 (defn- safe-parent-node [path s]
-  (get-type-node (named-spec s (butlast path)) s))          ;; TODO we have the parent node, can we use it instead?
+  (get-type-node (named-spec s (butlast path)) s))

 (defn- resolve-path [path]
   (if-let [t (some-> path second meta :type-name)]
@@ -239,7 +239,7 @@

                      ;; Ignore hierarchy for inline fragments
                      (= :inline-fragment (:node-type parent))
-                     [(last (butlast path)) (last path)]    ;; TODO is this the same case as the parent type name?
+                     [(last (butlast path)) (last path)]

                      parent-type-name
                      [parent-type-name (last path)]


Remove cruft

Remove cruft

--- src/atom_finder/substring-frequency.clj
+++ src/atom_finder/substring-frequency.clj
@@ -1,55 +1,12 @@
-(= (subs-freq "aaa" 3)  ([\a 3 ([\a 2 ([\a 1])])]))
-(= (subs-freq "aab" 3)  ([\a 2 ([\a 1] [\b 1])] [\b 1]))
-(= (subs-freq "abc" 3)  ([\a 1]))
-
-(defrecord FreqNode [element count children])
-
-
-(def test-node (->FreqNode \a 2 {\a (->FreqNode \a 1 {})}))
-(-> test-node
-    :children
-    (get \a)
-    :children)
-
-
-
-(defn inc-add
-  "If a child exists, increment it, otherwise add it"
-  [node element]
-  (update-in node [:children element]
-             #(if (nil? (:count %1))
-                (->FreqNode element 1 {})
-                (update %1 :count inc))))
-
-(inc-add (inc-add test-node \a) \a)
-
-;; (defn substring-freq
-;;   "Count the occurences of every substring below length m in string s"
-;;   ([str m]
-;;    (substring-freq (rest str) m
-;;                    (let [root (->FreqNode (first str) 1 {})]
-;;                      (for [lifetime (range 50)] [lifetime root]))))
-
-;;   ([str m nodes]
-;;    (let [char (first str)]
-;;      (for [node nodes]
-;;        (inc-add node (:children node))
-
-;;        )
-
-
-;;      ))))
-
-
 (defn all-subs [str m]
   (let [str-len (count str)]
     (for [start (range 0 str-len)
-          end   (range (+ start 1) (min (+ start m 1) str-len))]
+          end   (range (+ start 1) (min (+ start m 1) (+ str-len 1)))]
       (do
         (prn [start end])
         (subs str start end)))))

 (defn subs-freq [str max-len]
-  (frequencies (all-subs str max-len)))
+  (into (sorted-map) (frequencies (all-subs str max-len))))

 (subs-freq "aabc" 8)


distinguish vosotros vosotras ustedes

distinguish vosotros vosotras ustedes

--- src/babel/english/lexicon-verbcoach.clj
+++ src/babel/english/lexicon-verbcoach.clj
@@ -2378,7 +2378,45 @@
              :sem {:human true
                    :reflexive false
                    :pred :voi}
-             :subcat '()}}]
+             :subcat '()}}
+
+             {:english {:note "v ♂"}
+               :synsem {:cat :noun
+                        :pronoun true
+                        :reflexive false
+                        :case :top ;; see comment in "it" about :case.
+                        :agr {:person :2nd
+                              :gender :masc
+                              :number :plur}
+                        :sem {:human true
+                              :reflexive false
+                              :pred :voi}
+                        :subcat '()}}
+
+              {:english {:note "v ♀"}
+                :synsem {:cat :noun
+                          :pronoun true
+                          :reflexive false
+                          :case :top ;; see comment in "it" about :case.
+                          :agr {:person :2nd
+                                :gender :fem
+                                :number :plur}
+                          :sem {:human true
+                                :reflexive false
+                                :pred :voi}
+                          :subcat '()}}
+
+              {:english {:note "u"}
+               :synsem {:cat :noun
+                       :pronoun true
+                       :reflexive false
+                       :case :top ;; see comment in "it" about :case.
+                       :agr {:person :2nd
+                             :number :plur}
+                       :sem {:human true
+                             :reflexive false
+                             :pred :voi}
+                       :subcat '()}}]

    "your"
    (map #(unify %


Throw an exception instead of segfaulting

--- src/tensorflow_clj/core.clj
+++ src/tensorflow_clj/core.clj
@@ -30,9 +30,13 @@

 (defn run-and-fetch [name]
   (with-open [sess (org.tensorflow.Session. graph)]
-    (-> sess (.runner)
-      (.fetch (name name))
-      (.run))))
+    (let [runner (.runner sess)]
+      (print (-> runner
+               (.feed (name name) (tensor 234.0))
+               (.fetch (name name))
+               (.run)
+               (.get 0)
+               (.toString))))))

 (defn -main
   "I don't do a whole lot ... yet."


optimize acker by removing atoms and reflection

--- src/clj/backtype/storm/daemon/acker.clj
+++ src/clj/backtype/storm/daemon/acker.clj
@@ -1,7 +1,7 @@
 (ns backtype.storm.daemon.acker
   (:import [backtype.storm.task OutputCollector TopologyContext IBolt])
   (:import [backtype.storm.tuple Tuple Fields])
-  (:import [backtype.storm.utils TimeCacheMap])
+  (:import [backtype.storm.utils TimeCacheMap MutableObject])
   (:import [java.util List Map])
   (:use [backtype.storm config util log])
   (:gen-class
@@ -25,16 +25,17 @@
   )

 (defn mk-acker-bolt []
-  (let [output-collector (atom nil)
-        pending (atom nil)]
+  (let [output-collector (MutableObject.)
+        pending (MutableObject.)]
     (reify IBolt
       (^void prepare [this ^Map storm-conf ^TopologyContext context ^OutputCollector collector]
-               (reset! output-collector collector)
-               (reset! pending (TimeCacheMap. (.maxTopologyMessageTimeout context)))
+               (.setObject output-collector collector)
+               (.setObject pending (TimeCacheMap. (.maxTopologyMessageTimeout context)))
                )
       (^void execute [this ^Tuple tuple]
              (let [id (.getValue tuple 0)
-                   ^TimeCacheMap pending @pending
+                   ^TimeCacheMap pending (.getObject pending)
+                   ^OutputCollector output-collector (.getObject output-collector)
                    curr (.get pending id)
                    curr (condp = (.getSourceStreamId tuple)
                             ACKER-INIT-STREAM-ID (-> curr
@@ -48,7 +49,7 @@
                  (cond (= 0 (:val curr))
                        (do
                          (.remove pending id)
-                         (acker-emit-direct @output-collector
+                         (acker-emit-direct output-collector
                                             (:spout-task curr)
                                             ACKER-ACK-STREAM-ID
                                             [id]
@@ -56,16 +57,16 @@
                        (:failed curr)
                        (do
                          (.remove pending id)
-                         (acker-emit-direct @output-collector
+                         (acker-emit-direct output-collector
                                             (:spout-task curr)
                                             ACKER-FAIL-STREAM-ID
                                             [id]
                                             ))
                        ))
-               (.ack ^OutputCollector @output-collector tuple)
+               (.ack output-collector tuple)
                ))
       (^void cleanup [this]
-        (.cleanup @pending))
+        (.cleanup (.getObject pending)))
       )))

 (defn -init []


REFACTOR Move in bound value

REFACTOR Move in bound value

I don't know why I had made an extra let. Probably a leftover. Get rid
of it.

--- src/clj/theatralia/database/txd_gen.clj
+++ src/clj/theatralia/database/txd_gen.clj
@@ -17,13 +17,12 @@
 ;;;; Generators for adding materials

 (defn get-present-tags [db tags owner-eid]
-  (let [tags-s (set tags)]
-    (dezip (d/q '[:find ?e ?t
-                  :in $ ?ts ?o
-                  :where [?e :tag/owner ?o]
-                         [?e :tag/text ?t]
-                         [(contains? ?ts ?t)]]
-                db tags owner-eid))))
+  (dezip (d/q '[:find ?e ?t
+                :in $ ?ts ?o
+                :where [?e :tag/owner ?o]
+                       [?e :tag/text ?t]
+                       [(contains? ?ts ?t)]]
+              db (set tags) owner-eid)))

 (defn add-tags-txd [db tags owner-eid]
   "Generates a transaction data structure for adding tags for user with


fix layer rendering bug

fix layer rendering bug

--- src/cljs/infinitelives/pixi/canvas.cljs
+++ src/cljs/infinitelives/pixi/canvas.cljs
@@ -119,11 +119,12 @@

   ;(.log js/console (str layers))
   (let [
-        ;stage (js/PIXI.Stage. background)
+        stage (js/PIXI.Container. background)
         containers (map #(js/PIXI.Container.) layers)
+        ;; _ (doall (map #(.addChild stage %) containers))
         ]
     {
-     ;:stage stage
+     :stage stage
      :layers layers
      :layer
      (into {}
@@ -164,7 +165,7 @@
   :height        height of new canvas
   "
   [opts]
-  (let [{:keys [renderer canvas layer layers] :as world}
+  (let [{:keys [renderer canvas layer layers stage] :as world}
         (into (make opts)
               (make-stage opts))]
     ;; add the stages to the canvas
@@ -172,20 +173,23 @@
      (map
       (fn [[name layer-obj]]
         (log "adding to:" (str stage) " layer:" (str layer-obj))
-        ;(.addChild stage layer-obj)
+        (.addChild stage layer-obj)
         (center-container! canvas layer-obj)
         )
       layer))

     ;; do the first render
-    (doall (for [l layers] (.render renderer (l layer))))
-    ;(.render renderer stage)
+    ;(doall (for [l layers] (.render renderer (l layer))))
+    (.render renderer stage)

     (let [
           render-fn (fn []

-                      ;(.render renderer stage)
-                      (doall (for [l layers] (.render renderer (l layer))))
+                      (.render renderer stage)
+                      ;; (doall (for [l layers]
+                      ;;          (do
+                      ;;            (.log js/console "rendering:" l)
+                      ;;            (.render renderer (l layer)))))

                       )
           resize-fn (fn [width height]


Fixed problem with loading a route.

Fixed problem with loading a route.

--- src/cljs/wombats_web_client/routes.cljs
+++ src/cljs/wombats_web_client/routes.cljs
@@ -9,16 +9,11 @@
               [wombats-web-client.events.user :refer [sign-out-event]]
               [wombats-web-client.utils.auth :refer [user-is-coordinator?]]))

-(defn hook-browser-navigation! []
-  (doto (History.)
-    (events/listen
-     EventType/NAVIGATE
-     (fn [event]
-       (secretary/dispatch! (.-token event))))
-    (.setEnabled true)))
+(defonce history (pushy/pushy secretary/dispatch!
+                              (fn [x]
+                                (when (secretary/locate-route x) x))))

 (defn app-routes []
-  ;; --------------------
   ;; define routes here

   (defroute "/" []
@@ -39,9 +34,4 @@
   (defroute "/account" []
     (re-frame/dispatch [:set-active-panel :account-panel]))

-  (def history (pushy/pushy secretary/dispatch!
-                            (fn [x] (when (secretary/locate-route x) x))))
-
-  ;; --------------------
-  (pushy/start! history)
-  (hook-browser-navigation!))
+  (pushy/start! history))


Improve authentication abstraction and multiple backend handling.

--- src/clojure/catacumba/handlers/auth.clj
+++ src/clojure/catacumba/handlers/auth.clj
@@ -47,10 +47,10 @@
 (defprotocol IAuthentication
   "Protocol that defines unfied workflow steps for
   all authentication backends."
-  (^:private parse [_ request]
+  (-parse [_ request]
     "Parse token (from cookie, session or any other
     http header) and return it.")
-  (^:private authenticate [_ context token]
+  (-authenticate [_ context token]
     "Given a request and parsed data (from previous step), tries
     authenticate the current request and return the user entity.
     This function should return a IPromise instance."))
@@ -85,9 +85,9 @@
     :or {token-name "Token"}}]
   (reify
     IAuthentication
-    (parse [_ context]
+    (-parse [_ context]
       (parse-authorization-header context token-name))
-    (authenticate [_ context token]
+    (-authenticate [_ context token]
       (p/promise (fn [resolve]
                    (try+
                     (resolve (jws/unsign token secret options))
@@ -102,9 +102,9 @@
     :or {token-name "Token"}}]
   (reify
     IAuthentication
-    (parse [_ context]
+    (-parse [_ context]
       (parse-authorization-header context token-name))
-    (authenticate [_ context token]
+    (-authenticate [_ context token]
       (p/promise (fn [resolve]
                    (try+
                     (resolve (jwe/decrypt token secret options))
@@ -119,31 +119,28 @@
   []
   (reify
     IAuthentication
-    (parse [_ context]
+    (-parse [_ context]
       (:identity @(:session context)))
-    (authenticate [_ context data]
+    (-authenticate [_ context data]
       (p/resolved data))))

 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 ;; Handlers
 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

-;; TODO: remove unnecesary promise/callback chaining
-
 (defn- do-auth
   "Perform an asynchronous recursive loop over all
   provided backends and tries to authenticate with
   all them in order."
-  [context backends callback]
-  (if-let [backend (first backends)]
-    (let [last? (empty? (rest backends))
-          token (parse backend context)]
-      (if (and (nil? token) last?)
-        (callback {})
-        (-> (authenticate backend context token)
+  [context callback [backend & backends]]
+  (if backend
+    (let [token (-parse backend context)]
+      (if (nil? token)
+        (do-auth context callback backends)
+        (-> (-authenticate backend context token)
             (p/then (fn [ue]
                       (if (nil? ue)
-                        (do-auth context (rest backends) callback)
+                        (do-auth context callback backends)
                         (callback {:identity ue}))))
             (p/catch (fn [e] (callback {}))))))
     (callback {})))
@@ -155,7 +152,8 @@
   (fn [context]
     (p/promise
      (fn [next]
-       (do-auth context backends #(next (ct/delegate %)))))))
+       (let [callback #(next (ct/delegate %))]
+         (do-auth context callback backends))))))

 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 ;; Adapters


Allow return efficiently files as response and body values.

--- src/clojure/catacumba/impl/handlers.clj
+++ src/clojure/catacumba/impl/handlers.clj
@@ -86,6 +86,10 @@
             (.next ctx (Registry/single data))))
         (.next ctx))))

+  java.nio.file.Path
+  (-handle-response [path ^DefaultContext context]
+    (-send path (:catacumba/context context)))
+
   String
   (-handle-response [data ^DefaultContext context]
     (-send data (:catacumba/context context)))
@@ -130,6 +134,10 @@
   (-send [data ^Context ctx]
     (let [^Response response (.getResponse ctx)]
       (.send response ^bytes data)))
+
+  java.nio.file.Path
+  (-send [path ^Context ctx]
+    (.sendFile ctx path))

   String
   (-send [data ^Context ctx]


optionally don't print program name on error/help

--- src/clojure/zensols/actioncli/parse.clj
+++ src/clojure/zensols/actioncli/parse.clj
@@ -41,6 +41,12 @@
   with [[set-program-name]]."
   []
   @program-name-inst)
+
+(defn- program-fmt []
+  (let [name (program-name)]
+    (if name
+      (str name ": ")
+      "")))

 (defn set-program-name
   "Set the program name used for info/error message."
@@ -79,7 +85,7 @@
   ([usage-format]
    (fn [action-names]
      (->> (format usage-format
-                  (program-name)
+                  (or (program-name) "")
                   (if-not action-names
                     ""
                     (->> action-names
@@ -165,10 +171,10 @@
     (if *log-error* (log/error e "action line parse error"))
     (if (instance? java.io.FileNotFoundException e)
       (binding [*out* *err*]
-        (println (format "%s: io error: %s" (program-name) msg)))
+        (println (format "%sio error: %s" (program-fmt) msg)))
       (binding [*out* *err*]
-        (println (format "%s: error: %s"
-                         (program-name)
+        (println (format "%serror: %s"
+                         (program-fmt)
                          (if ex-data
                            (.getMessage e)
                            (.toString e)))))))
@@ -194,7 +200,7 @@
   singleton then only print one in the common usage format."
   [errors]
   (if (= (count errors) 1)
-    (format "%s: %s" (program-name) (first errors))
+    (str (program-fmt) (first errors))
     (str "The following errors occurred while parsing your action:\n\n"
          (s/join \newline errors))))


Switched to use all cores for encoding

Switched to use all cores for encoding

--- src/video_server/ffmpeg.clj
+++ src/video_server/ffmpeg.clj
@@ -25,6 +25,7 @@
       (json/read-str (:out exec) :key-fn keyword))))

 (defn detect-interlace
+  "Performs interlace detection, returning true if present."
   [input]
   (let [output (:err (exec "ffmpeg" "-y" "-ss" 300 "-i" input "-f" "matroska"
                            "-t" 120 "-an" "-sn" "-vf" "idet" "/dev/null"))]
@@ -42,6 +43,7 @@
       (when-not (.endsWith crop ":0:0") crop))))

 (defn deinterlace
+  "Returns an updated spec with option to deinterlace the video."
   [spec]
   (merge spec
          (when (detect-interlace (:input spec))
@@ -114,6 +116,7 @@
         (first audio)))) ; TODO: check language

 (defn audio-codec-options
+  "Returns the encoding options for the specified codec."
   [index codec]
   (case codec
     "aac" ["-q:a" 100 (str "-ac:a:" index) 2 "-strict" "-2"]
@@ -121,6 +124,7 @@
     nil))

 (defn audio-title-options
+  "Returns the encoding options for adding a title to an audio track."
   [index codec lang chans]
   [(str "-metadata:s:a:" index) (str "title=" (audio-title codec lang chans))])

@@ -151,6 +155,12 @@
     (for [stream subtitle-streams]
       ["-map" (str "0:" (:index stream)) "-c:s" "copy"])))

+(defn format-options
+  "Returns the ffmpeg options for the type of output file."
+  [{:keys [format]}]
+  (when (#{:m4v :mp4} format)
+    ["-movflags" "faststart"]))
+
 (defn encode-cmd
   "Returns the ffmpeg command for encoding a video."
   [spec]
@@ -160,6 +170,7 @@
    (audio-options spec)
    (subtitle-options spec)
    "-f" (ffmpeg-format (:format spec))
-   "-movflags" "+faststart"
+   (format-options spec)
+   "-threads" 0
    (:output spec)])


Fix handler not returning state in certain situations

--- src/braid/client/state/helpers.cljs
+++ src/braid/client/state/helpers.cljs
@@ -170,14 +170,15 @@

 (defn maybe-create-thread [state thread-id group-id]
   (let [state (update-in state [:user :open-thread-ids] #(conj % thread-id))]
-    (when-not (get-in state [:threads thread-id])
+    (if-not (get-in state [:threads thread-id])
       (-> state
           (assoc-in [:threads thread-id] {:id thread-id
                                           :group-id group-id
                                           :messages []
                                           :tag-ids #{}
                                           :mentioned-ids #{}})
-          (update-in [:group-threads group-id] #(conj (set %) thread-id))))))
+          (update-in [:group-threads group-id] #(conj (set %) thread-id)))
+      state)))

 (defn add-message [state message]
   (-> state


added bang for Markdown docs

added bang for Markdown docs

--- src/xebang/models/bangs.clj
+++ src/xebang/models/bangs.clj
@@ -14,6 +14,7 @@
    '!html       "http://devdocs.io/#q=html {{{s}}}"
    '!jquery     "http://devdocs.io/#q=jquery {{{s}}}"
    '!underscore "http://devdocs.io/#q=underscore {{{s}}}"
+   '!markdown   "http://daringfireball.net/projects/markdown/syntax#{{{s}}}"
    '!namecheap  "http://www.namecheap.com/domains/domain-name-search/results.aspx?domain={{{s}}}&tlds=&searchall=&type=single&"})

 (def mock-config


removing color from logging

removing color from logging

--- src/celestial/puppet_standalone.clj
+++ src/celestial/puppet_standalone.clj
@@ -57,7 +57,7 @@
    (task run-puppet
       (let [{:keys [module]} args]
         (run (str (<< "cd /tmp/~(module :name)") " && "
-          (as-root remote (<< "./scripts/run.sh ~(args-from args) --detailed-exitcodes || [ $? -eq 2 ]"))))))
+          (as-root remote (<< "./scripts/run.sh ~(args-from args) --detailed-exitcodes --color=false || [ $? -eq 2 ]"))))))

    (task cleanup-tmp
       (let [{:keys [module]} args]


Extra/Stats, cron fix

Extra/Stats, cron fix

--- src/clj/salava/extra/stats/cron.clj
+++ src/clj/salava/extra/stats/cron.clj
@@ -13,16 +13,17 @@
                                    :source (get-in ctx [:config :core :site-url])
                                    :ts (System/currentTimeMillis)})
           checksum (u/hmac-sha256-hex payload (get-in ctx [:config :factory :secret]))
-          url (str (get-in ctx [:config :factory :url]) "/c/badge/passport_stats?&c=" checksum)]
-      (http/http-post url {:body payload}))))
+          url (str (get-in ctx [:config :factory :url]) "/c/badge/passport_stats?c=" checksum)]
+      (http/http-post url {:body payload :throw-exceptions false}))))

 (defn- id->assertion-url [ctx badge-hits]
   (let [db-conn (:connection (u/get-db ctx))
         sql "SELECT assertion_url AS url FROM user_badge WHERE id = ?"]
     (reduce (fn [coll id]
-              (if-let [[a-url] (some->> (jdbc/query db-conn [sql id]) first :url (re-find #"^https?://[^\?&;#]+/v[0-9]/assertion/\w+\.json"))]
-                (assoc coll a-url (get badge-hits id))
-                coll))
+              (let [a-url (some->> (jdbc/query db-conn [sql id]) first :url)]
+                (if (and a-url (re-find #"^https?://[^\?&;#]+/v[0-9]/assertion/\w+\.json" a-url))
+                  (assoc coll a-url (get badge-hits id))
+                  coll)))
             {} (keys badge-hits))))

 (defn- hit-count [filename services]


Don't use frame specific naming in coll->chan

--- src/cljs/asciinema_player/core.cljs
+++ src/cljs/asciinema_player/core.cljs
@@ -53,20 +53,20 @@
        (loop [coll coll
               virtual-time 0
               wall-time (elapsed-time-since start)
-              pending-diff init]
-         (if-let [[delay diff] (first coll)]
+              acc init]
+         (if-let [[delay data] (first coll)]
            (let [new-virtual-time (+ virtual-time delay)
                  ahead (- new-virtual-time wall-time)]
              (if (pos? ahead)
                (do
-                 (when-not (empty? pending-diff)
-                   (>! ch pending-diff))
+                 (when-not (empty? acc)
+                   (>! ch acc))
                  (<! (timeout (* 1000 ahead)))
-                 (>! ch diff)
+                 (>! ch data)
                  (recur (rest coll) new-virtual-time (elapsed-time-since start) init))
-               (recur (rest coll) new-virtual-time wall-time (reducer pending-diff diff)))))
-         (when-not (empty? pending-diff)
-           (>! ch pending-diff)))
+               (recur (rest coll) new-virtual-time wall-time (reducer acc data)))))
+         (when-not (empty? acc)
+           (>! ch acc)))
        (close! ch))
      ch)))


Catch and return js eval exceptions. Refs #CLJS-45

--- src/cljs/clojure/browser/repl2.cljs
+++ src/cljs/clojure/browser/repl2.cljs
@@ -26,7 +26,8 @@
   "Process a single block of JavaScript received from the server"
   [connection block]
   (log-obj (str "evaluating: " block))
-  (let [result (js* "eval(~{block})")]
+  (let [result (try (js* "eval(~{block})")
+                    (catch js/Error e (pr-str e)))]
     (log-obj (str "result: " result))
     (reset! result-state result)))


Update hint location

Update hint location

--- src/clojure/nightcode/shortcuts.clj
+++ src/clojure/nightcode/shortcuts.clj
@@ -65,6 +65,7 @@
 (defn toggle-hint
   "Shows or hides the given hint."
   [hint show?]
+  (.refreshLocation hint)
   (if (and show? (is-visible? (.getAttachedComponent hint)))
     (s/show! hint)
     (s/hide! hint)))


Minor reformatting.

Minor reformatting.

--- src/clojush/instructions/genome.clj
+++ src/clojush/instructions/genome.clj
@@ -1,6 +1,4 @@
-
-
-(ns clojush.instructions.genome
+ (ns clojush.instructions.genome
   (:use [clojush pushstate globals args random]
         clojush.instructions.common
         clojush.pushgp.genetic-operators))
@@ -72,10 +70,10 @@
              (push-item (assoc genome
                           index
                           (random-plush-instruction-map
-                                    [(nth @global-atom-generators atom-gen)]
-                                    {:epigenetic-markers @global-epigenetic-markers
-                                     :close-parens-probabilities @global-close-parens-probabilities
-                                     :silent-instruction-probability @global-silent-instruction-probability}))
+                            [(nth @global-atom-generators atom-gen)]
+                            {:epigenetic-markers @global-epigenetic-markers
+                             :close-parens-probabilities @global-close-parens-probabilities
+                             :silent-instruction-probability @global-silent-instruction-probability}))
                         :genome)))
       state)))

@@ -272,13 +270,15 @@
   autoconstructive_integer_rand
   ;; pushes a constant integer, but is replaced with integer_rand during
   ;; nondetermistic autoconstruction
-  ^{:stack-types [:genome :integer]} (fn [state] (push-item 0 :integer state)))
+  ^{:stack-types [:genome :integer]}
+  (fn [state] (push-item 0 :integer state)))

 (define-registered
   autoconstructive_boolean_rand
   ;; pushes false, but is replaced with boolean_rand during
   ;; nondetermistic autoconstruction
-  ^{:stack-types [:genome :boolean]} (fn [state] (push-item false :boolean state)))
+  ^{:stack-types [:genome :boolean]}
+  (fn [state] (push-item false :boolean state)))

 (define-registered
   genome_uniform_instruction_mutation
@@ -350,8 +350,9 @@
              (pop-item :genome)
              (push-item (vec (:genome (uniform-tag-mutation
                                         {:genome genome}
-                                        (merge @push-argmap {:uniform-mutation-rate rate
-                                                             :uniform-mutation-tag-gaussian-standard-deviation stdev}))))
+                                        (merge @push-argmap
+                                               {:uniform-mutation-rate rate
+                                                :uniform-mutation-tag-gaussian-standard-deviation stdev}))))
                         :genome)))
       state)))

@@ -369,8 +370,9 @@
              (pop-item :genome)
              (push-item (vec (:genome (uniform-string-mutation
                                         {:genome genome}
-                                        (merge @push-argmap {:uniform-mutation-rate rate1
-                                                             :uniform-mutation-string-char-change-rate rate2}))))
+                                        (merge @push-argmap
+                                               {:uniform-mutation-rate rate1
+                                                :uniform-mutation-string-char-change-rate rate2}))))
                         :genome)))
       state)))

@@ -514,4 +516,3 @@
                                         @push-argmap)))
                         :genome)))
       state)))
-


CMR-132: Added get-concept for Oracle.

CMR-132: Added get-concept for Oracle.

--- src/cmr/metadata_db/data/oracle.clj
+++ src/cmr/metadata_db/data/oracle.clj
@@ -21,6 +21,17 @@
 (def db-sid (get (System/getenv) "MDB_DB_SID" "orcl"))

 ;;; Utility methods
+
+(defn clob-to-string
+  "Turn an Oracle Clob into a String"
+  [clob]
+  (with-open [rdr (java.io.BufferedReader. (.getCharacterStream clob))]
+    (apply str (line-seq rdr))))
+
+(defn fix-metadata-field
+  "Convert the metadata field from a CLOB to a string."
+  [concept]
+  (assoc concept :metadata (clob-to-string (:metadata concept))))

 (defn reset-database
   "Delete everything from the concpet table."
@@ -96,7 +107,31 @@

   (get-concept
-    [this concept-id revision-id])
+    [this concept-id revision-id]
+    (let [{:keys [db]} this]
+      (if revision-id
+        (let [concept (first (j/query db ["SELECT concept_type, native_id, provider_id, metadata, format, revision
+                                          AS revision_id
+                                          FROM METADATA_DB.concept
+                                          WHERE concept_id = ? AND revision = ?"
+                                          concept-id
+                                          revision-id]))]
+          (if (nil? concept)
+            (errors/throw-service-error :not-found
+                                        "Could not find concept with concept-id of %s and revision %s."
+                                        concept-id
+                                        revision-id)
+            (fix-metadata-field concept)))
+        (let [concept (first (j/query db ["SELECT concept_type, native_id, provider_id, metadata, format, revision
+                                          FROM METADATA_DB.concept
+                                          WHERE concept_id = ?
+                                          ORDER BY revision DESC" concept-id]))]
+          (if (nil? concept)
+            (errors/throw-service-error :not-found
+                                        "Could not find concept with concept-id of %s."
+                                        concept-id)
+            (fix-metadata-field concept))))))
+

   (get-concepts
     [this concept-id-revision-id-tuples])
@@ -116,7 +151,6 @@
 (defn create-db
   "Creates the db needed for clojure.java.jdbc library."
   []
-  (println "CREATING ORACLE DB")
   (map->OracleStore {:db {:classname "oracle.jdbc.driver.OracleDriver"
                           :subprotocol "oracle"
                           :subname (format "thin:@%s:%s:%s" db-host db-port db-sid)


add search functionality

add search functionality

--- src_cljs/rrms/corecljs.cljs
+++ src_cljs/rrms/corecljs.cljs
@@ -26,6 +26,7 @@
                           :total-pages 1
                           :page-location nil
                           :villages {}
+                          :is-searched-results false
                           :user nil}))

@@ -166,6 +167,18 @@
                                                     (c/from-string (.-date %)))) data)))

+(defn get-search-url [mn dt]
+  (let [mnv (st/blank? mn)
+        dtv (st/blank? dt)
+        purl (str "http://localhost:9000/mutations/search?")]
+    (cond (and (not mnv) dtv ) (str purl "mutationNumber=" mn)
+          (and mnv (not dtv))  (str purl  "value=" dt)
+          :else (str purl "mutationNumber="mn"&value="dt))))
+
+(defn get-index-url [is-searched-results sel-page mn dt]
+  (cond (= true is-searched-results)(str (get-search-url mn dt)"&pageIndex="sel-page"&pageSize=10")
+        :else (str "http://localhost:9000/mutations?pageIndex="sel-page "&pageSize=10")))
+
 (defn get-new-page-data [data current-page total-pages]
   (js/console.log total-pages)
   (let [pag-start (* 10 (dec current-page))
@@ -196,17 +209,18 @@
 (def pager-elem (r/adapt-react-class (aget js/ReactBootstrap "Pagination")))

 (defn set-pager-data [sel-page-no]
-  (let [onres (fn[json]
+  (let [mt (.-value (.getElementById js/document "mutationnumber"))
+        v (.-value (.getElementById js/document "dt"))
+        onres (fn[json]
                 (let [dt (getdata json)]
                   (set-key-value :mutations (.-data dt))
                   (set-key-value :total-pages (get-total-rec-no (.-pagesCount dt)))
-
                   (set-key-value :page-location
                                  [render-mutations (get-value! :mutations)])))]
-    (http-get (str "http://localhost:9000/mutations?pageIndex="(dec (get-value! :current-page)) "&pageSize=10")
+    (http-get (get-index-url (get-value! :is-searched-results)
+                             (dec (get-value! :current-page))
+                             mt v)
               onres)))
-
-

 (defn pager [value total-rec]
   [pager-elem {:bsSize "large"
@@ -236,21 +250,30 @@
 (defn cancel [event]
   (secretary/dispatch! "/"))

+;;...... Side Tab Events .........
+
+(defn mut-click [event]
+  (secretary/dispatch! "/"))
+
+(defn rev-click [event]
+  (secretary/dispatch! "/revenue"))
+
+;;.............. End of Tab Events ......
+
 (defn search [event]
-  (let [dt1 (.-value (.getElementById js/document "dt1"))
-        dt2 (.-value (.getElementById js/document "dt2"))
-        dt  (.-value (.getElementById js/document "dt"))]
-
-    (do (set-key-value :mutations
-                       (clj->js
-                        (filter-data (get-value! :mutations)
-                                     (c/from-string dt1)
-                                     (c/from-string dt2) dt)))
-        (set-key-value :current-page 1)
-        (set-key-value :page-location
-                       [render-mutations
-                        (get-new-page-data (get-value! :mutations)
-                                           (get-value! :current-page))]))))
+  (let [mn  (.-value (.getElementById js/document "mutationnumber"))
+        dt  (.-value (.getElementById js/document "dt"))
+        onres (fn [json] (let [data (getdata json)]
+                          (set-key-value :mutations (.-data data))
+                          (set-key-value :total-pages
+                                         (get-total-rec-no (.-pagesCount data)))
+                          (js/console.log (get-value! :total-pages))
+                          (set-key-value :page-location
+                                         [render-mutations (get-value! :mutations)])))]
+    (set-key-value :current-page 1)
+    (set-key-value :is-searched-results true)
+    (http-get (str (get-search-url mn dt) "&pageIndex=0&pageSize=10")
+              onres)))

 ;; ========================================================================================
 ;; Add-update-form creation validation
@@ -451,11 +474,12 @@
   (let [onres (fn [json]
                 (let [mt (getdata json)]
                   (set-key-value :mutations (.-data mt))
-                  (set-key-value :pagesCount (get-total-rec-no
-                                              (.-pagesCount mt)))
+                  (set-key-value :total-pages (get-total-rec-no
+                                               (.-pagesCount mt)))
                   (set-key-value :current-page 1)
                   (set-key-value :page-location
                                  [render-mutations (get-value! :mutations)])))]
+    (set-key-value :is-searched-results false)
     (http-get "http://localhost:9000/mutations?pageIndex=0&pageSize=10" onres)))

 (defn render-mutations [mutations]
@@ -542,6 +566,7 @@
                   (set-key-value :mutations (.-data dt))
                   (set-key-value :total-pages (get-total-rec-no (.-pagesCount dt)))
                   (set-key-value :page-location  [render-mutations (get-value! :mutations)])))]
+    (set-key-value :is-searched-results false)
     (http-get (str "http://localhost:9000/mutations?pageIndex="(dec (get-value! :current-page))"&pageSize=10") onres)))

 (defroute mutations-list "/mutations" []
@@ -550,6 +575,7 @@
                   (set-key-value :mutations (.-data dt))
                   (set-key-value :total-pages (get-total-rec-no (.-pagesCount dt)))
                   (set-key-value :page-location  [render-mutations (get-value! :mutations)])))]
+    (set-key-value :is-searched-results false)
     (http-get (str "http://localhost:9000/mutations?pageIndex="(dec (get-value! :current-page))"&pageSize=10") onres)))

@@ -561,12 +587,15 @@

 (defroute documents-path1 "/mutations/update/:id" [id]
   (let [onres (fn[json](
-                        (set-key-value :villages (getdata json))
-                        (set-page! [mutation-update-template id
-                                    (first (filter (fn[obj]
-                                                     (=(.-id obj) (.parseInt js/window id))) (get-value! :mutations)))])))]
+                       (set-key-value :villages (getdata json))
+                       (set-page! [mutation-update-template id
+                                   (first (filter (fn[obj]
+                                                    (=(.-id obj) (.parseInt js/window id))) (get-value! :mutations)))])))]
     (http-get "http://localhost:9000/villages" onres)))

+
+(defroute revenue-list "/revenue" []
+  )

 (defroute "*" []


Use ab-test-treatment function

Use ab-test-treatment function

--- src-cljs/frontend/components/build_head.cljs
+++ src-cljs/frontend/components/build_head.cljs
@@ -367,9 +367,7 @@
                          "https://circleci.com/docs/test-metadata/#metadata-collection-in-custom-test-steps")
         track-junit #((om/get-shared owner :track-event) {:event-type :set-up-junit-clicked
                                                           :properties {:language language
-                                                                       :ab-test-treatment (if (feature/enabled? :junit-button)
-                                                                                :junit-button
-                                                                                :junit-banner)}})]
+                                                                       :ab-test-treatment (feature/ab-test-treatment :junit-button)}})]
     (if (feature/enabled? :junit-button)
       (button/link (open-ext {:href junit-link
                               :class "junit-link"
@@ -499,9 +497,7 @@
     om/IDidMount
     (did-mount [_]
       ((om/get-shared owner :track-event) {:event-type :set-up-junit-impression
-                                           :properties {:ab-test-treatment (if (feature/enabled? :junit-button)
-                                                                               :junit-button
-                                                                               :junit-banner)}}))
+                                           :properties {:ab-test-treatment (feature/ab-test-treatment :junit-button)}}))
     om/IRender
     (render [_]
       (let [source-hash (->> tests