(ns clojurewerkz.cassaforte.ns-utils)

(defmacro defalias ^:private [sym v]
  `(intern *ns* (with-meta ~sym (meta ~sym)) (deref ~v)))

(defn alias-ns
  "Alias all the vars from namespace to the curent namespace"
  [ns-name]
  (require ns-name)
  (doseq [[n v] (ns-publics (the-ns ns-name))]
    (defalias n v)))

(ns clojurewerkz.cassaforte.ns-utils)

(defn defalias
  "Create a var with the supplied name in the current namespace, having the same
  metadata and root-binding as the supplied var."
  [name ^clojure.lang.Var var]
  (apply intern *ns* (with-meta name (merge (meta var)
                                            (meta name)))
         (when (.hasRoot var) [@var])))

(defn alias-ns
  "Alias all the vars from namespace to the curent namespace"
  [ns-name]
  (require ns-name)
  (doseq [[n v] (ns-publics (the-ns ns-name))]
    (defalias n v)))

Fix defalias to support docstrings

Fix defalias to support docstrings


(defproject ring/ring-jetty-adapter "1.9.0"
  :description "Ring Jetty adapter."
  :url "https://github.com/ring-clojure/ring"
  :scm {:dir ".."}
  :license {:name "The MIT License"
            :url "http://opensource.org/licenses/MIT"}
  :dependencies [[org.clojure/clojure "1.7.0"]
                 [ring/ring-core "1.9.0"]
                 [ring/ring-servlet "1.9.0"]
                 [org.eclipse.jetty/jetty-server "9.4.31.v20200723"]]
  :aliases {"test-all" ["with-profile" "default:+1.8:+1.9:+1.10" "test"]}
  :profiles
  {:dev  {:dependencies [[clj-http "3.10.0"]
                         [less-awful-ssl "1.0.6"]]
          :jvm-opts ["-Dorg.eclipse.jetty.server.HttpChannelState.DEFAULT_TIMEOUT=500"]}
   :1.8  {:dependencies [[org.clojure/clojure "1.8.0"]]}
   :1.9  {:dependencies [[org.clojure/clojure "1.9.0"]]}
   :1.10 {:dependencies [[org.clojure/clojure "1.10.2"]]}})

(defproject ring/ring-jetty-adapter "1.9.0"
  :description "Ring Jetty adapter."
  :url "https://github.com/ring-clojure/ring"
  :scm {:dir ".."}
  :license {:name "The MIT License"
            :url "http://opensource.org/licenses/MIT"}
  :dependencies [[org.clojure/clojure "1.7.0"]
                 [ring/ring-core "1.9.0"]
                 [ring/ring-servlet "1.9.0"]
                 [org.eclipse.jetty/jetty-server "9.4.36.v20210114"]]
  :aliases {"test-all" ["with-profile" "default:+1.8:+1.9:+1.10" "test"]}
  :profiles
  {:dev  {:dependencies [[clj-http "3.10.0"]
                         [less-awful-ssl "1.0.6"]]
          :jvm-opts ["-Dorg.eclipse.jetty.server.HttpChannelState.DEFAULT_TIMEOUT=500"]}
   :1.8  {:dependencies [[org.clojure/clojure "1.8.0"]]}
   :1.9  {:dependencies [[org.clojure/clojure "1.9.0"]]}
   :1.10 {:dependencies [[org.clojure/clojure "1.10.2"]]}})

Update Jetty dependency to 9.4.36.v20210114


(ns docker-clojure.dockerfile
  (:require
   [clojure.java.shell :refer [sh]]
   [clojure.string :as str]
   [docker-clojure.dockerfile.boot :as boot]
   [docker-clojure.dockerfile.lein :as lein]
   [docker-clojure.dockerfile.tools-deps :as tools-deps]))

(defn build-dir [{:keys [base-image build-tool]}]
  (str/join "/" ["target"
                 (str/replace base-image ":" "-")
                 build-tool]))

(defn contents [{:keys [maintainer build-tool] :as variant}]
  (str/join "\n"
            (concat [(format "FROM %s" (:base-image variant))
                     (format "LABEL maintainer=\"%s\"" maintainer)
                     ""]
                    (case build-tool
                      "boot" (boot/contents variant)
                      "lein" (lein/contents variant)
                      "tools-deps" (tools-deps/contents variant)))))

(defn write-file [dir file variant]
  (let [{:keys [exit err]} (sh "mkdir" "-p" dir)]
    (if (zero? exit)
      (spit (str/join "/" [dir file])
            (contents variant))
      (throw (ex-info (str "Error creating directory " dir)
                      {:error err})))))

(defn clean-all []
  (sh "sh" "-c" "rm -rf target/*"))

(ns docker-clojure.dockerfile
  (:require
   [clojure.java.shell :refer [sh]]
   [clojure.string :as str]
   [docker-clojure.dockerfile.boot :as boot]
   [docker-clojure.dockerfile.lein :as lein]
   [docker-clojure.dockerfile.tools-deps :as tools-deps]))

(defn build-dir [{:keys [base-image build-tool]}]
  (str/join "/" ["target"
                 (str/replace base-image ":" "-")
                 build-tool]))

(defn contents [{:keys [maintainer build-tool] :as variant}]
  (str/join "\n"
            (concat [(format "FROM %s" (:base-image variant))
                     ""]
                    (case build-tool
                      "boot" (boot/contents variant)
                      "lein" (lein/contents variant)
                      "tools-deps" (tools-deps/contents variant)))))

(defn write-file [dir file variant]
  (let [{:keys [exit err]} (sh "mkdir" "-p" dir)]
    (if (zero? exit)
      (spit (str/join "/" [dir file])
            (contents variant))
      (throw (ex-info (str "Error creating directory " dir)
                      {:error err})))))

(defn clean-all []
  (sh "sh" "-c" "rm -rf target/*"))

Stop adding maintainer label per Docker recs


(ns warreq.kea.calc.math
  (:require [clojure.math.numeric-tower :refer [expt]]
            [warreq.kea.calc.util :as u]
            [neko.notify :refer [toast]])
  (:import java.math.BigDecimal))

(defn rpn
  "Evaluate an expression composed in Reverse Polish Notation and return the
  result. `rpn` may optionally take a stack as a separate parameter, which may
  contain a partially resolved expression."
  ([e]
   (rpn e '()))
  ([e s]
   (if (empty? e)
     (first s)
     (if (number? (first e))
       (recur (rest e)
              (conj s (first e)))
       (recur (rest e)
              (conj (drop 2 s) (eval (conj (reverse (take 2 s)) (first e)))))))))

(defn floating-division [x y]
  (if (not= ^BigDecimal y BigDecimal/ZERO)
    (.divide ^BigDecimal x ^BigDecimal y java.math.RoundingMode/HALF_UP)
    (do (u/vibrate! 500)
        (toast "Cannot divide by 0."))))

(defn op-alias [op]
  (case op
    "^" expt
    "÷" floating-division
    "×" *
    (resolve (symbol op))))

(ns warreq.kea.calc.math
  (:require [clojure.math.numeric-tower :refer [expt]]
            [warreq.kea.calc.util :as u]
            [neko.notify :refer [toast]])
  (:import java.math.BigDecimal))

(defn rpn
  "Evaluate an expression composed in Reverse Polish Notation and return the
  result. `rpn` may optionally take a stack as a separate parameter, which may
  contain a partially resolved expression."
  ([e]
   (rpn e '()))
  ([e s]
   (if (empty? e)
     (first s)
     (if (number? (first e))
       (recur (rest e)
              (conj s (first e)))
       (recur (rest e)
              (conj (drop 2 s) (eval (conj (reverse (take 2 s)) (first e)))))))))

(defn floating-division [x y]
  (if (not= ^BigDecimal y BigDecimal/ZERO)
    (.divide ^BigDecimal x ^BigDecimal y 2 java.math.RoundingMode/HALF_EVEN)
    (do (u/vibrate! 500)
        (toast "Cannot divide by 0."))))

(defn op-alias [op]
  (case op
    "^" expt
    "÷" floating-division
    "×" *
    (resolve (symbol op))))

Fix division to round to at least 2 decimal places


(ns com.wsscode.common.async-cljs)

(defmacro if-cljs
  [then else]
  (if (:ns &env) then else))

(defmacro go-catch [& body]
  `(async/go
     (try
       ~@body
       (catch :default e# e#))))

(defmacro <!p [promise]
  `(consumer-pair (cljs.core.async/<! (promise->chan ~promise))))

(defmacro <? [ch]
  `(throw-err (cljs.core.async/<! ~ch)))

(defmacro <?maybe [x]
  `(let [res# ~x]
     (if (chan? res#) (<? res#) res#)))

(defmacro <!maybe [x]
  `(let [res# ~x]
     (if (chan? res#) (cljs.core.async/<! res#) res#)))

(defmacro let-chan
  "Handles a possible channel on value."
  [[name value] & body]
  `(let [res# ~value]
     (if (chan? res#)
       (go-catch
         (let [~name (<? res#)]
           ~@body))
       (let [~name res#]
         ~@body))))

(defmacro go-promise [& body]
  `(let [ch# (cljs.core.async/promise-chan)]
     (async/go
       (let [res# (try
                    ~@body
                    (catch :default e# e#))]
         (cljs.core.async/put! ch# res#)))
     ch#))

(ns com.wsscode.common.async-cljs
  (:require [cljs.core.async :as async]))

(defmacro if-cljs
  [then else]
  (if (:ns &env) then else))

(defmacro go-catch [& body]
  `(async/go
     (try
       ~@body
       (catch :default e# e#))))

(defmacro <!p [promise]
  `(consumer-pair (cljs.core.async/<! (promise->chan ~promise))))

(defmacro <? [ch]
  `(throw-err (cljs.core.async/<! ~ch)))

(defmacro <?maybe [x]
  `(let [res# ~x]
     (if (chan? res#) (<? res#) res#)))

(defmacro <!maybe [x]
  `(let [res# ~x]
     (if (chan? res#) (cljs.core.async/<! res#) res#)))

(defmacro let-chan
  "Handles a possible channel on value."
  [[name value] & body]
  `(let [res# ~value]
     (if (chan? res#)
       (go-catch
         (let [~name (<? res#)]
           ~@body))
       (let [~name res#]
         ~@body))))

(defmacro go-promise [& body]
  `(let [ch# (cljs.core.async/promise-chan)]
     (async/go
       (let [res# (try
                    ~@body
                    (catch :default e# e#))]
         (cljs.core.async/put! ch# res#)))
     ch#))

Fix async require on async cljs

Fix async require on async cljs


(ns user
  (:use
    clojure.repl
    io.aviso.repl
    speclj.config))

(install-pretty-exceptions)

(alter-var-root #'default-config assoc :color true :reporters ["documentation"])

(ns user
  (:use
    clojure.repl
    io.aviso.repl
    io.aviso.logging
    speclj.config))

(install-pretty-exceptions)
(install-pretty-logging)
(install-uncaught-exception-handler)

(alter-var-root #'default-config assoc :color true :reporters ["documentation"])

Enable pretty hooks for logging

Enable pretty hooks for logging


;; Copyright 2015 Andrey Antukh <niwi@niwi.nz>
;;
;; Licensed under the Apache License, Version 2.0 (the "License")
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;;     http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.

(ns continuo.postgresql
  "A postgresql transactor main namespace.")

(load "postgresql/connection")
(load "postgresql/bootstrap")

;; Copyright 2015 Andrey Antukh <niwi@niwi.nz>
;;
;; Licensed under the Apache License, Version 2.0 (the "License")
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;;     http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.

(ns continuo.postgresql
  "A postgresql transactor main namespace."
  (:require [continuo.postgresql.connection]
            [continuo.postgresql.bootstrap]))

Replace load with simple require directives.


(ns berry.parsing.context-handler)

(def begin {
            :start-line 1
            :start-column 1
            :current-line 1
            :current-column 1
            :offset 0})

(defn ++
  [{current-column :current-column
    offset :offset
    :as context}]
  (merge context {
                  :current-column (inc current-column)
                  :offset (inc offset)}))

(defn --
  [{current-column :current-column
    offset :offset
    :as context}]
  (merge context {
                  :current-column (dec current-column)
                  :offset (dec offset)}))

(ns berry.parsing.context-handler)

(def begin {
            :start-line 1
            :start-column 1
            :current-line 1
            :current-column 1
            :offset 0})

(defn- apply-to
  [transform {current-column :current-column
              offset :offset
              :as context}]
  (assoc context
         :current-column (transform current-column)
         :offset (transform offset)))

(def ++ (partial apply-to inc))

(def -- (partial apply-to dec))

Reduce code duplication by using a partial function.


(ns nightweb.core
  (:use splendid.jfx
        nightweb.page)
  (:import javafx.scene.layout.VBox
           javafx.scene.layout.HBox
           javafx.scene.control.TabPane
           javafx.scene.control.Tab
           javafx.scene.web.WebView
           javafx.scene.layout.Priority
           javafx.scene.control.Button
           javafx.scene.control.TextField
           javafx.geometry.Insets
           net.i2p.router.Router)
  (:gen-class))

(defn start-browser
  "Launch the JavaFX browser (non-blocking)."
  []
  (jfx (let [window (VBox.)
             tab-view (VBox.)
             nav-bar (HBox.)
             back-btn (Button. "<-")
             for-btn (Button. "->")
             reload-btn (Button. "Reload")
             url-field (TextField.)
             tab-bar (TabPane.)
             main-tab (Tab. "Main Page")
             add-tab (Tab. "+")
             web-view (WebView.)]
         (.setPadding nav-bar (Insets. 4))
         (.setSpacing nav-bar 2)
         (add nav-bar [back-btn for-btn reload-btn url-field])
         (HBox/setHgrow url-field Priority/ALWAYS)
         (add tab-view [nav-bar web-view])
         (.setClosable add-tab false)
         (.setContent main-tab tab-view)
         (.add (.getTabs tab-bar) main-tab)
         (.add (.getTabs tab-bar) add-tab)
         (.load (.getEngine web-view) "http://localhost:8080")
         (VBox/setVgrow tab-bar Priority/ALWAYS)
         (add window [tab-bar])
         (show window))))

(defn start-router
  "Launch the router (blocking)."
  []
  (Router/main nil))

(defn -main
  "Launch everything."
  [& args]
  (start-web-server)
  (start-browser)
  (comment (start-router)))

(ns nightweb.core
  (:use nightweb.page
        nightweb.browser)
  (:import net.i2p.router.Router)
  (:gen-class))

(defn start-router
  "Launch the router (blocking)."
  []
  (Router/main nil))

(defn -main
  "Launch everything."
  [& args]
  (start-web-server)
  (start-browser)
  (comment (start-router)))

Add ability to create tabs.

Add ability to create tabs.


(ns cards.util
  (:require [om.dom :as dom]))

(defn update-cb-info [tag state & params]
  (println "update-cb-info" tag state params)
  (swap! state (fn [state] (-> state
                               (update-in [:callbacks tag :counter] inc)
                               (assoc-in [:callbacks tag :params] params)))))

(defn render-cb-info [tag state label]
  (let [{:keys [counter params]} (get-in @state [:callbacks tag])]
    (dom/div #js {:style #js {:marginTop "1rem"}}
      (dom/strong nil "Callback info: " label)
      (dom/div nil (str "Triggered " (or counter 0) " times"))
      (dom/div nil "Parameters: " (dom/code nil (str params))))))

(ns cards.util
  (:require [om.dom :as dom]))

(defn update-cb-info [tag state & params]
  (swap! state (fn [state] (-> state
                               (update-in [:callbacks tag :counter] inc)
                               (assoc-in [:callbacks tag :params] params)))))

(defn render-cb-info [tag state label]
  (let [{:keys [counter params]} (get-in @state [:callbacks tag])]
    (dom/div #js {:style #js {:marginTop "1rem"}}
      (dom/strong nil "Callback info: " label)
      (dom/div nil (str "Triggered " (or counter 0) " times"))
      (dom/div nil "Parameters: " (dom/code nil (str params))))))

Remove debug message from update-cb-info in devcards


(use '[clojure.string :only (split-lines split join capitalize)])

(defn read-tabular-file [filename]
  (let [data (slurp filename)
        lines (split-lines data)
        split-by-tab #(split % #"\t")]
    (map split-by-tab lines)))

(defn nameify [s]
  (let [words (split s #" ")
        word-names (map capitalize words)]
    (join " " word-names)))

(defn convert-player [country data]
  (let [shirt (data 0)]
    {
      :id (str country "_" shirt)
      :country (nameify country)
      :name (nameify (data 1))
      :shirt_number shirt
      :date_of_birth (data 2)
      :position (data 3)
      :club (data 4)
      :height (data 5)
    }))

(def raw (read-tabular-file "2010/brazil.data"))

(println (convert-player "brazil" (first raw)))

(use '[clojure.string :only (split-lines split join capitalize)])

(defn read-tabular-file [filename]
  (let [data (slurp filename)
        lines (split-lines data)
        split-by-tab #(split % #"\t")]
    (map split-by-tab lines)))

(defn nameify [s]
  (let [words (split s #" ")
        word-names (map capitalize words)]
    (join " " word-names)))

(defn iso-date [s]
  (let [[day month year] (split s #"/")]
    (format "%s-%s-%s" year month day)))

(defn convert-player [country data]
  (let [shirt (data 0)]
    {
      :id (str country "_" shirt)
      :country (nameify country)
      :name (nameify (data 1))
      :shirt_number shirt
      :date_of_birth (iso-date (data 2))
      :position (data 3)
      :club (data 4)
      :height (data 5)
    }))

(def raw (read-tabular-file "2010/brazil.data"))

(println (convert-player "brazil" (first raw)))

Convert date into iso date

Convert date into iso date


{:user {:signing {:gpg-key "8ED1CE42"}

        :dependencies [[alembic "0.2.1"]
                       [clj-stacktrace "0.2.7"]
                       [criterium "0.4.2"]
                       [org.clojure/tools.namespace "0.2.5"]
                       [slamhound "1.5.3"]
                       [spyscope "0.1.4"]]

        :plugins [[cider/cider-nrepl "0.7.0"]
                  [codox "0.6.6"]
                  [jonase/eastwood "0.1.4"]
                  [lein-ancient "0.5.5" :exclusions [commons-codec]]
                  [lein-cljsbuild "1.0.3"]
                  [lein-clojars "0.9.1"]
                  [lein-cloverage "1.0.2"]
                  [lein-difftest "2.0.0"]
                  [lein-kibit "0.0.8"]
                  [lein-marginalia "0.7.1"]
                  [lein-pprint "1.1.1"]
                  [lein-swank "1.4.4"]]

        :injections [(require
                      '[alembic.still :refer [distill]]
                      '[clojure.repl :refer [source]]
                      '[clojure.tools.namespace.repl :as repl]
                      '[criterium.core :refer [bench quick-bench]]
                      'spyscope.core)]

        :aliases {"slamhound" ["run" "-m" "slam.hound"]}
        :search-page-size 50}}

{:user {:signing {:gpg-key "8ED1CE42"}

        :dependencies [[alembic "0.2.1"]
                       [clj-stacktrace "0.2.7"]
                       [criterium "0.4.2"]
                       [org.clojure/tools.namespace "0.2.5"]
                       [slamhound "1.5.3"]
                       [spyscope "0.1.4"]]

        :plugins [[cider/cider-nrepl "0.8.0-SNAPSHOT"]
                  [codox "0.6.6"]
                  [jonase/eastwood "0.1.4"]
                  [lein-ancient "0.5.5" :exclusions [commons-codec]]
                  [lein-cljsbuild "1.0.3"]
                  [lein-clojars "0.9.1"]
                  [lein-cloverage "1.0.2"]
                  [lein-difftest "2.0.0"]
                  [lein-kibit "0.0.8"]
                  [lein-marginalia "0.7.1"]
                  [lein-pprint "1.1.1"]
                  [lein-swank "1.4.4"]]

        :injections [(require
                      '[alembic.still :refer [distill]]
                      '[clojure.repl :refer [source]]
                      '[clojure.tools.namespace.repl :as repl]
                      '[criterium.core :refer [bench quick-bench]]
                      'spyscope.core)]

        :aliases {"slamhound" ["run" "-m" "slam.hound"]}
        :search-page-size 50}}

Use snapshot version of cider-nrepl

Use snapshot version of cider-nrepl


{:user {:ultra {:color-scheme :solarized_dark
                :stacktraces  true}
        :plugins [[lein-try "0.4.3"]
                  [lein-ancient "0.6.10-SNAPSHOT"]
                  [lein-kibit "0.1.2"]
                  [jonase/eastwood "0.2.3"]
                  ;[venantius/ultra "0.5.0"]
                 ]}}

{:user {:ultra {:color-scheme :solarized_dark
                :stacktraces  true
                :repl true
                :java true
                :tests true}
        :plugins [[lein-try "0.4.3"]
                  [lein-ancient "0.6.10-SNAPSHOT"]
                  [lein-kibit "0.1.2"]
                  [jonase/eastwood "0.2.3"]
                  ;[venantius/ultra "0.5.1"]
                 ]
        :repl-options {:init (set! *print-length* 42)}
	}}

Add some pretty print configuration for lein


(ns incise.watcher
  (:require [taoensso.timbre :refer [error]]
            [clojure.stacktrace :refer [print-stack-trace]]
            [watchtower.core :refer [watcher rate file-filter extensions
                                     on-change]]))

(defn log-exceptions [func]
  "Log (i.e. print) exceptions received from the given function."
  (let [out *out*
        err *err*]
    (fn [& args]
      (binding [*out* out
                *err* err]
        (try
          (apply func args)
          (catch Exception e
            (error (with-out-str (print-stack-trace e)))))))))

(defn per-change [change-fn]
  (fn [files]
    (doseq [file files]
      (change-fn file))))

(defn watch
  [change-fn]
  (watcher ["resources/posts/" "resources/pages/"]
           (rate 300)
           (on-change (-> change-fn
                          per-change
                          log-exceptions))))

(def watching nil)

(defn start-watching [& args]
  (alter-var-root #'watching (fn [& _] (apply watch args))))

(defn stop-watching []
  (when watching
    (future-cancel watching)))

(ns incise.watcher
  (:require [taoensso.timbre :refer [error]]
            [clojure.stacktrace :refer [print-cause-trace]]
            [watchtower.core :refer [watcher rate file-filter extensions
                                     on-change]]))

(defn log-exceptions [func]
  "Log (i.e. print) exceptions received from the given function."
  (let [out *out*
        err *err*]
    (fn [& args]
      (binding [*out* out
                *err* err]
        (try
          (apply func args)
          (catch Exception e
            (error (with-out-str (print-cause-trace e)))))))))

(defn per-change [change-fn]
  (fn [files]
    (doseq [file files]
      (change-fn file))))

(defn watch
  [change-fn]
  (watcher ["resources/posts/" "resources/pages/"]
           (rate 300)
           (on-change (-> change-fn
                          per-change
                          log-exceptions))))

(def watching nil)

(defn start-watching [& args]
  (alter-var-root #'watching (fn [& _] (apply watch args))))

(defn stop-watching []
  (when watching
    (future-cancel watching)))

Use print-cause-trace instead of print-stack-trace.


(ns com.wsscode.pathom.test
  (:require [com.wsscode.pathom.core :as p]))

(defn self-reader [{:keys [ast query] :as env}]
  (if query
    (p/join env)
    (name (:key ast))))

#?(:clj
   (defn sleep-reader [{:keys [ast query] :as env}]
     (if-let [time (p/ident-value env)]
       (do
         (Thread/sleep time)
         (if query
           (p/join env)
           (name (first (:key ast)))))
       ::p/continue)))

(defn repeat-reader [env]
  (if-let [key (p/ident-key env)]
    (if (some-> (name key) (.startsWith "repeat."))
      (p/join-seq env (map (constantly {}) (range (p/ident-value env))))
      ::p/continue)
    ::p/continue))

(ns com.wsscode.pathom.test
  (:require [com.wsscode.pathom.core :as p]
            [clojure.string :as str]))

(defn self-reader [{:keys [ast query] :as env}]
  (if query
    (p/join env)
    (name (:key ast))))

#?(:clj
   (defn sleep-reader [{:keys [ast query] :as env}]
     (if-let [time (p/ident-value env)]
       (do
         (Thread/sleep time)
         (if query
           (p/join env)
           (name (first (:key ast)))))
       ::p/continue)))

(defn repeat-reader [env]
  (if-let [key (p/ident-key env)]
    (if (some-> (name key) (str/starts-with? "repeat."))
      (p/join-seq env (map (constantly {}) (range (p/ident-value env))))
      ::p/continue)
    ::p/continue))

Use idiomatic clojure for str/starts-with?


(ns servisne-info.tasks.daily-report
  (:require [servisne-info.logging :as l]
            [servisne-info.notifications :refer [send-daily-report-email]]
            [servisne-info.repository :as repo]
            [servisne-info.tasks.task-definition :refer [deftask]]))

(defn- format-event-data [event]
  (l/format-data (dissoc event :_id)))

(defn send-daily-report []
  (let [events (repo/find-events-for-yesterday)]
    (send-daily-report-email (map format-event-data events))))

(def send-daily-report-task
  (deftask "send daily report"
    (send-daily-report)))

(ns servisne-info.tasks.daily-report
  (:require [servisne-info.logging :as l]
            [servisne-info.notifications :refer [send-daily-report-email]]
            [servisne-info.repository :as repo]
            [servisne-info.tasks.task-definition :refer [deftask]]))

(defn- format-event-data [event]
  (l/format-data (dissoc event :_id :created-at)))

(defn send-daily-report []
  (let [events (repo/find-events-for-yesterday)]
    (send-daily-report-email (map format-event-data events))))

(def send-daily-report-task
  (deftask "send daily report"
    (send-daily-report)))

Remove created-at from daily report

Remove created-at from daily report


(ns planck.themes
  (:require [planck.from.io.aviso.ansi :as ansi]))

(def ^:private colorize-fn-dumb identity)
(def ^:private colorize-off-dumb "")

(def ^:private dumb
  {:results-fn   colorize-fn-dumb
   :ex-msg-fn    colorize-fn-dumb
   :ex-stack-fn  colorize-fn-dumb
   :err-font     colorize-off-dumb
   :verbose-font colorize-off-dumb
   :reset-font   colorize-off-dumb})

(def ^:private theme-ansi-base
  {:reset-font ansi/reset-font})

(def ^:private light
  (merge theme-ansi-base
    {:results-fn   ansi/blue
     :ex-msg-fn    ansi/bold-red
     :ex-stack-fn  ansi/green
     :err-font     ansi/red-font
     :verbose-font ansi/white-font}))

(def ^:private dark
  (merge theme-ansi-base
    {:results-fn   ansi/blue
     :ex-msg-fn    ansi/bold-red
     :ex-stack-fn  ansi/green
     :err-font     ansi/red-font
     :verbose-font ansi/white-font}))

(def ^:private themes
  {:plain dumb
   :light light
   :dark  dark})

(defn get-theme
  [theme-id]
  (get themes theme-id dumb))

(ns planck.themes
  (:require [planck.from.io.aviso.ansi :as ansi]))

(def ^:private colorize-fn-dumb identity)
(def ^:private colorize-off-dumb "")

(def ^:private dumb
  {:results-fn   colorize-fn-dumb
   :ex-msg-fn    colorize-fn-dumb
   :ex-stack-fn  colorize-fn-dumb
   :err-font     colorize-off-dumb
   :verbose-font colorize-off-dumb
   :reset-font   colorize-off-dumb})

(def ^:private theme-ansi-base
  {:reset-font ansi/reset-font})

(def ^:private light
  (merge theme-ansi-base
    {:results-fn   ansi/blue
     :ex-msg-fn    ansi/bold-red
     :ex-stack-fn  ansi/green
     :err-font     ansi/red-font
     :verbose-font ansi/white-font}))

(def ^:private dark
  (merge theme-ansi-base
    {:results-fn   ansi/bold-blue
     :ex-msg-fn    ansi/bold-red
     :ex-stack-fn  ansi/green
     :err-font     ansi/red-font
     :verbose-font ansi/white-font}))

(def ^:private themes
  {:plain dumb
   :light light
   :dark  dark})

(defn get-theme
  [theme-id]
  (get themes theme-id dumb))

Make results more readible in dark theme


(ns spec-tools.core-test
  (:require #?(:clj [clojure.test :refer [deftest testing is]]
               :cljs [cljs.test :as test :refer-macros [deftest testing is]])))

(deftest a-test
  (is (= 1 1)))

(ns spec-tools.core-test
  (:require [clojure.test :refer [deftest testing is]]))

(deftest a-test
  (is (= 1 1)))

Simplify ns-form, thanks to class!

Simplify ns-form, thanks to class!


(defproject {{name}} "0.1.0-SNAPSHOT"
  :description "FIXME: write description"
  :url "http://example.com/FIXME"
  :license {:name "Eclipse Public License"
            :url "http://www.eclipse.org/legal/epl-v10.html"}
  :dependencies [[org.clojure/clojure "1.6.0"]
  				      [quil "2.2.0-SNAPSHOT"]
  				      [org.clojure/clojurescript "0.0-2268"]]

  :plugins [[lein-cljsbuild "1.0.3"]]
  :hooks [leiningen.cljsbuild]

  :cljsbuild
  {:builds [{:source-paths ["src"]
             :compiler
             {:output-to "web/js/main.js"
              :optimizations :whitespace
              :pretty-print true}}]})

(defproject {{name}} "0.1.0-SNAPSHOT"
  :description "FIXME: write description"
  :url "http://example.com/FIXME"
  :license {:name "Eclipse Public License"
            :url "http://www.eclipse.org/legal/epl-v10.html"}
  :dependencies [[org.clojure/clojure "1.6.0"]
  				      [quil "2.2.0-SNAPSHOT"]
  				      [org.clojure/clojurescript "0.0-2268"]]

  :plugins [[lein-cljsbuild "1.0.3"]]
  :hooks [leiningen.cljsbuild]

  :cljsbuild
  {:builds [{:source-paths ["src"]
             :compiler
             {:output-to "web/js/main.js"
              :externs ["externs/processing-externs.js"]
              :optimizations :whitespace
              :pretty-print true}}]})

Set :externs value for :advanced compilation.


(ns ^{:clojure.tools.namespace.repl/load false}
    nrepl
    (:require
     [clojure.tools.nrepl.server :as nrepl.server]
     [cider.nrepl]
     [cemerick.piggieback]
     [refactor-nrepl.middleware :as refactor.nrepl]))

(defn start-nrepl
  []
  (let [server
        (nrepl.server/start-server
          :handler
          (apply nrepl.server/default-handler

                 (conj (map #'cider.nrepl/resolve-or-fail cider.nrepl/cider-middleware)
                       #'refactor.nrepl/wrap-refactor
                       #'cemerick.piggieback/wrap-cljs-repl
                       )))]
    (spit ".nrepl-port" (:port server))
    (println "nREPL port:" (:port server))
    server))

(def server (start-nrepl))

(ns ^{:clojure.tools.namespace.repl/load false}
    nrepl
    (:require
     [clojure.tools.nrepl.server :as nrepl.server]
     [cider.nrepl]
     [cemerick.piggieback]
     [refactor-nrepl.middleware :as refactor.nrepl]))

(defn start-nrepl
  [opts]
  (let [server
        (nrepl.server/start-server
          :port (:port opts)
          :handler
          (apply nrepl.server/default-handler

                 (conj (map #'cider.nrepl/resolve-or-fail cider.nrepl/cider-middleware)
                       #'refactor.nrepl/wrap-refactor
                       #'cemerick.piggieback/wrap-cljs-repl
                       )))]
    (spit ".nrepl-port" (:port server))
    (println "nREPL port:" (:port server))
    server))

(def server (start-nrepl {:port 5600}))

Use port 5600, as before

Use port 5600, as before


(ns advent2017.core)

(defn read-puzzle
  ([name]
   (read-puzzle name identity))
  ([name xform]
   (-> (clojure.java.io/file (str "../2017/" name))
       (slurp)
       xform)))

(defn enumerate [xs]
  (map vector (range) xs))

(defn ->lines [s]
  (clojure.string/split s #"\n"))

(defn ->words [s]
  (clojure.string/split s #"\s+"))

(defn ->numbers [xs]
  (map #(Integer/parseInt %) xs))

(def lines->numbers (partial map words->numbers))

(defn csv->numbers [s]
  (->numbers (clojure.string/split s #",")))

(defn manhattan-distance
  ([[x2 y2]]
   (manhattan-distance [0 0] [x2 y2]))
  ([[x1 y1] [x2 y2]]
   (+ (Math/abs (- x1 x2))
      (Math/abs (- y1 y2)))))

(defn bfs-lazy [tree pred f]
  ((fn step [queue]
     (lazy-seq
      (when (seq queue)
        (let [[[node & children] depth] (peek queue)
              xs (step (into (pop queue)
                             (map vector children (repeat (inc depth)))))]
          (if (pred node depth children)
            (cons (f node depth children) xs)
            xs)))))
   (conj clojure.lang.PersistentQueue/EMPTY [tree 0])))

(ns advent2017.core)

(defn read-puzzle
  ([name]
   (read-puzzle name identity))
  ([name xform]
   (-> (clojure.java.io/file (str "../2017/" name))
       (slurp)
       xform)))

(defn enumerate [xs]
  (map vector (range) xs))

(defn ->lines [s]
  (clojure.string/split s #"\n"))

(defn ->words [s]
  (clojure.string/split s #"\s+"))

(defn ->numbers [xs]
  (map #(Integer/parseInt %) xs))

(def lines->numbers (comp (partial map (comp ->numbers ->words))
                          ->lines))

(defn csv->numbers [s]
  (->numbers (clojure.string/split s #",")))

(defn manhattan-distance
  ([[x2 y2]]
   (manhattan-distance [0 0] [x2 y2]))
  ([[x1 y1] [x2 y2]]
   (+ (Math/abs (- x1 x2))
      (Math/abs (- y1 y2)))))

(defn bfs-lazy [tree pred f]
  ((fn step [queue]
     (lazy-seq
      (when (seq queue)
        (let [[[node & children] depth] (peek queue)
              xs (step (into (pop queue)
                             (map vector children (repeat (inc depth)))))]
          (if (pred node depth children)
            (cons (f node depth children) xs)
            xs)))))
   (conj clojure.lang.PersistentQueue/EMPTY [tree 0])))

Fix a bug in `lines->numbers`.

Fix a bug in `lines->numbers`.


(defproject wort "0.1.0-SNAPSHOT"
  :description "FIXME: write description"
  :url "http://example.com/FIXME"
  :license {:name "Eclipse Public License"
            :url "http://www.eclipse.org/legal/epl-v10.html"}
  :dependencies [[org.clojure/clojure "1.8.0"]
                 [org.clojure/data.json "0.2.6"]
                 [com.amazonaws/aws-lambda-java-core "1.0.0"]
                 [uswitch/lambada "0.1.2"]
                 [pjstadig/humane-test-output "0.8.2"]
                 [compojure "1.6.0"]
                 [deraen/sass4clj "0.3.1"]
                 [ring/ring-defaults "0.2.1"]]
  :sass {:source-paths ["resources/public/css/scss"]
             :target-path "resources/public/css"
             :output-style :compressed}
  :ring {:handler wort.handler/app}
  :injections [(require 'pjstadig.humane-test-output)
               (pjstadig.humane-test-output/activate!)]
  :plugins [[lein-cljfmt "0.5.6"]
	        [lein-ring "0.12.1"]
            [deraen/lein-sass4clj "0.3.1"]]
  :main ^:skip-aot wort.core
  :target-path "target/%s"
  :profiles {:uberjar {:aot :all}})

(defproject wort "0.1.0-SNAPSHOT"
  :description "FIXME: write description"
  :url "http://example.com/FIXME"
  :license {:name "Eclipse Public License"
            :url "http://www.eclipse.org/legal/epl-v10.html"}
  :dependencies [[org.clojure/clojure "1.8.0"]
                 [org.clojure/data.json "0.2.6"]
                 [com.amazonaws/aws-lambda-java-core "1.0.0"]
                 [uswitch/lambada "0.1.2"]
                 [pjstadig/humane-test-output "0.8.2"]
                 [compojure "1.6.0"]
                 [deraen/sass4clj "0.3.1"]
                 [org.slf4j/slf4j-log4j12 "1.7.9"]
                 [ring/ring-defaults "0.2.1"]]
  :sass {:source-paths ["resources/public/css/scss"]
             :target-path "resources/public/css"
             :output-style :compressed}
  :ring {:handler wort.handler/app}
  :injections [(require 'pjstadig.humane-test-output)
               (pjstadig.humane-test-output/activate!)]
  :plugins [[lein-cljfmt "0.5.6"]
	        [lein-ring "0.12.1"]
            [deraen/lein-sass4clj "0.3.1"]]
  :main ^:skip-aot wort.core
  :target-path "target/%s"
  :profiles {:uberjar {:aot :all}})

Add explicit dependency to fix sass4clj internal broken dep


(ns {{ns-name}}.routes
  (:require
   [bidi.bidi :as bidi]
   [pushy.core :as pushy]
   [re-frame.core :as re-frame]
   [{{ns-name}}.events :as events]))

(defmulti panels identity)
(defmethod panels :default [] [:div "No panel found for this route."])

(def routes
  (atom
    ["/" {""      :home
          "about" :about}]))

(defn parse
  [url]
  (bidi/match-route @routes url))

(defn url-for
  [& args]
  (apply bidi/path-for (into [@routes] args)))

(defn dispatch
  [route]
  (let [panel (keyword (str (name (:handler route)) "-panel"))]
    (re-frame/dispatch [::events/set-active-panel panel])))

(def history
  (pushy/pushy dispatch parse))

(defn navigate!
  [handler]
  (pushy/set-token! history (url-for handler)))

(defn start!
  []
  (pushy/start! history))

(re-frame/reg-fx
  :navigate
  (fn [handler]
    (navigate! handler)))

(ns {{ns-name}}.routes
  (:require
   [bidi.bidi :as bidi]
   [pushy.core :as pushy]
   [re-frame.core :as re-frame]
   [{{ns-name}}.events :as events]))

(defmulti panels identity)
(defmethod panels :default [] [:div "No panel found for this route."])

(def routes
  (atom
    ["/" {""      :home
          "about" :about}]))

(defn parse
  [url]
  (bidi/match-route @routes url))

(defn url-for
  [& args]
  (apply bidi/path-for (into [@routes] args)))

(defn dispatch
  [route]
  (let [panel (keyword (str (name (:handler route)) "-panel"))]
    (re-frame/dispatch [::events/set-active-panel panel])))

(defonce history
  (pushy/pushy dispatch parse))

(defn navigate!
  [handler]
  (pushy/set-token! history (url-for handler)))

(defn start!
  []
  (pushy/start! history))

(re-frame/reg-fx
  :navigate
  (fn [handler]
    (navigate! handler)))

Use `defonce` instead of `def`

Use `defonce` instead of `def`

Fixes navigation breaking when hot code reloading.


(ns onyx.log.notify-join-cluster-test
  (:require [onyx.extensions :as extensions]
            [onyx.log.entry :refer [create-log-entry]]
            [midje.sweet :refer :all]))

(def entry (create-log-entry :notify-join-cluster {:observer :d :subject :a}))

(def f (partial extensions/apply-log-entry entry))

(def rep-diff (partial extensions/replica-diff entry))

(def rep-reactions (partial extensions/reactions entry))

(def old-replica {:pairs {:a :b :b :c :c :a} :prepared {:a :d} :peers [:a :b :c]})

(let [new-replica (f old-replica)
      diff (rep-diff old-replica new-replica)
      reactions (rep-reactions old-replica new-replica diff {:id :d})]
  (fact diff => {:observer :d :subject :b :accepted-joiner :d :accepted-observer :a})
  (fact reactions => [{:fn :accept-join-cluster :args diff :immediate? true}])
  (fact (rep-reactions old-replica new-replica diff {:id :a}) => nil)
  (fact (rep-reactions old-replica new-replica diff {:id :b}) => nil)
  (fact (rep-reactions old-replica new-replica diff {:id :c}) => nil))

(ns onyx.log.notify-join-cluster-test
  (:require [onyx.extensions :as extensions]
            [onyx.log.entry :refer [create-log-entry]]
            [onyx.messaging.aeron :as aeron]
            [com.stuartsierra.component :as component]
            [midje.sweet :refer :all]))

(def peer-config
  (:peer-config (read-string (slurp (clojure.java.io/resource "test-config.edn")))))

(def messaging
  (aeron/aeron {:opts peer-config}))

(component/start messaging)
(try
  (let [entry (create-log-entry :notify-join-cluster {:observer :d :subject :a})
        f (partial extensions/apply-log-entry entry)
        rep-diff (partial extensions/replica-diff entry)
        rep-reactions (partial extensions/reactions entry)
        old-replica {:pairs {:a :b :b :c :c :a} :prepared {:a :d} :peers [:a :b :c]}
        new-replica (f old-replica)
        diff (rep-diff old-replica new-replica)
        reactions (rep-reactions old-replica new-replica diff {:id :d :messenger messaging})]
    (fact diff => {:observer :d :subject :b :accepted-joiner :d :accepted-observer :a})
    (fact reactions => [{:fn :accept-join-cluster :args diff :immediate? true :site-resources {:aeron/port 40201}}])
    (fact (rep-reactions old-replica new-replica diff {:id :a}) => nil)
    (fact (rep-reactions old-replica new-replica diff {:id :b}) => nil)
    (fact (rep-reactions old-replica new-replica diff {:id :c}) => nil))

  (finally
    (component/stop messaging)))

Add messaging to notify-join test. Switch defs to let


(ns lo-cash.core
  (:require [clojure.browser.repl :as repl]))

(defn -main []
  (.log js/console "connecting...")
  (repl/connect "http://localhost:9000/repl"))

(defn obj-select
  "Selects the given keys from a JS object and returns a keywordized map"
  [obj [& keys]]
  (into {}
    (map #([(keyword %) (aget obj %)])
         keys)))

(defn obj-selectv
  "Selects the given keys from a JS object and returns a vector of their values"
  [obj [& keys]]
  (mapv #(aget obj %) keys))

(ns lo-cash.core
  (:require [clojure.browser.repl :as repl]))

(defn -main []
  (.log js/console "connecting...")
  (repl/connect "http://localhost:9000/repl"))

(defn obj-select
  "Selects the given keys from a JS object and returns a keywordized map"
  [obj & keys]
  (into {}
    (map (fn [k]
           [(keyword k) (aget obj (name k))])
         keys)))

(defn obj-selectv
  "Selects the given keys from a JS object and returns a vector of their values"
  [obj & keys]
  (mapv #(aget obj (name %)) keys))

Fix and change obj-select(v) functions, now more keyword-y


(ns guangyin.internal.types
  (:import (guangyin.internal.types ObjectWrapper TemporalAmountWrapper
                                    TemporalAccessorWrapper TemporalWrapper)))

(defmethod print-method ObjectWrapper
  [obj writer]
  (print-method @obj writer))

(defn wrapped-instance?
  [^Class c x]
  (or (instance? c x) ; FIXME This should be removed
      (and (instance? ObjectWrapper x)
           (instance? c @x))))

(defmacro wrap-object
  [& body]
  `(ObjectWrapper. (do ~@body)))

(defmacro wrap-temporal-accessor
  [keymap & body]
  `(TemporalAccessorWrapper. ~keymap (do ~@body)))

(defmacro wrap-temporal
  [keymap & body]
  `(TemporalWrapper. ~keymap (do ~@body)))

(defmacro wrap-temporal-amount
  [keymap & body]
  `(TemporalAmountWrapper. ~keymap (do ~@body)))

(ns guangyin.internal.types
  (:import (guangyin.internal.types ObjectWrapper TemporalAmountWrapper
                                    TemporalAccessorWrapper TemporalWrapper)))

(defmethod print-method ObjectWrapper
  [obj writer]
  (print-method @obj writer))

(defn wrapped-instance?
  [^Class c x]
  (or (instance? c x) ; FIXME This should be removed
      (and (instance? ObjectWrapper x)
           (instance? c @x))))

(defn unwrap
  [x]
  (if (instance? ObjectWrapper x) @x x))

(defmacro wrap-object
  [& body]
  `(ObjectWrapper. (do ~@body)))

(defmacro wrap-temporal-accessor
  [keymap & body]
  `(TemporalAccessorWrapper. ~keymap (do ~@body)))

(defmacro wrap-temporal
  [keymap & body]
  `(TemporalWrapper. ~keymap (do ~@body)))

(defmacro wrap-temporal-amount
  [keymap & body]
  `(TemporalAmountWrapper. ~keymap (do ~@body)))

Add unwrap function to be used for arguments.


(ns klangmeister.test.processing
  (:require [cljs.test :refer-macros [deftest testing is]]
            [klangmeister.processing :as processing]
            [klangmeister.framework :as framework]
            [klangmeister.compile.eval :as eval]
            [klangmeister.actions :as action]))

(def ignore! (constantly nil))

(deftest stopping
  (testing
    (is
      (=
       (framework/process (action/->Stop :foo) ignore! {:foo {:looping? true}})
       {:foo {:looping? false}}))
    (is
      (=
       (framework/process (action/->Stop :foo) ignore! {:foo {:looping? false}})
       {:foo {:looping? false}}))))

(deftest refreshing
  (testing
    (is
      (=
       (framework/process (action/->Refresh "(phrase [1] [69])" :foo) ignore! {})
       {:foo {:value [{:time 0 :pitch 69 :duration 1}] :text "(phrase [1] [69])" :error nil}}))
    (is
      ((comp :error :foo)
       (framework/process (action/->Refresh "(phrase [1] [6" :foo) ignore! {})))))

(ns klangmeister.test.processing
  (:require [cljs.test :refer-macros [deftest testing is]]
            [klangmeister.processing :as processing]
            [klangmeister.framework :as framework]
            [klangmeister.compile.eval :as eval]
            [klangmeister.actions :as action]))

(def ignore! (constantly nil))

(deftest stopping
  (testing
    (is
      (=
       (framework/process (action/->Stop :foo) ignore! {:foo {:looping? true}})
       {:foo {:looping? false}}))
    (is
      (=
       (framework/process (action/->Stop :foo) ignore! {:foo {:looping? false}})
       {:foo {:looping? false}}))))

(deftest refreshing
  (testing
    (is
      (=
       (framework/process (action/->Refresh "(phrase [1] [69])" :foo) ignore! {})
       {:foo {:value [{:time 0 :pitch 69 :duration 1}] :text "(phrase [1] [69])" :error nil}}))
    (is
      ((comp :error :foo)
       (framework/process (action/->Refresh "(phrase [1] [6" :foo) ignore! {})))
    (is
      (=
       (-> (framework/process (action/->Refresh "(phrase [1] [6" :foo) ignore! {:foo {:value [{:time 0 :pitch 69 :duration 1}]}})
           :foo
           :value)
       [{:time 0 :pitch 69 :duration 1}]))))

Test that the value remains unchanged when there's an error.


(ns analyze-data.tf-idf.inverse-document-frequency)

(defn document-frequency
  "Return a map from term to number of documents it appears in."
  [tf-corpus]
  (let [count-term (fn [m term] (assoc m term (inc (get m term 0))))
        term-keys (mapcat keys tf-corpus)]
    (reduce count-term {} term-keys)))

(defn calc-inverse-document-frequency
  "Calculate inverse document frequency.

  num-documents: the total number of documents
  num-documents-with-term: the number of documents containing the term we are
                           calculating for"
  [num-documents num-documents-with-term]
  (Math/log (/ num-documents num-documents-with-term)))

(defn inverse-document-frequency
  "Given
  tf-corpus: a sequence of term-frequency maps where each one represents a
             single document

  Return a map from term to its inverse document frequency (as defined at
  https://en.wikipedia.org/wiki/Tf–idf#Inverse_document_frequency_2)."
  [tf-corpus]
  (let [num-documents (count tf-corpus)
        document-frequencies (document-frequency tf-corpus)
        assoc-idf (fn [m term num-documents-with-term]
                    (assoc m
                           term
                           (calc-inverse-document-frequency
                             num-documents
                             num-documents-with-term)))]
    (reduce-kv assoc-idf {} document-frequencies)))

(ns analyze-data.tf-idf.inverse-document-frequency)

(defn document-frequency
  "Return a map from term to number of documents it appears in."
  [term-frequency-corpus]
  (let [count-term (fn [m term] (assoc m term (inc (get m term 0))))
        term-keys (mapcat keys term-frequency-corpus)]
    (reduce count-term {} term-keys)))

(defn calc-inverse-document-frequency
  "Calculate inverse document frequency.

  num-documents: the total number of documents
  num-documents-with-term: the number of documents containing the term we are
                           calculating for"
  [num-documents num-documents-with-term]
  (Math/log (/ num-documents num-documents-with-term)))

(defn inverse-document-frequency
  "Given
  term-frequency-corpus: a sequence of term-frequency maps where each one
                         represents a single document

  Return a map from term to its inverse document frequency (as defined at
  https://en.wikipedia.org/wiki/Tf–idf#Inverse_document_frequency_2)."
  [term-frequency-corpus]
  (let [num-documents (count term-frequency-corpus)
        document-frequencies (document-frequency term-frequency-corpus)
        assoc-idf (fn [m term num-documents-with-term]
                    (assoc m
                           term
                           (calc-inverse-document-frequency
                             num-documents
                             num-documents-with-term)))]
    (reduce-kv assoc-idf {} document-frequencies)))

Rename tf-corpus variable to term-frequency-corpus.


(ns whitman.core
  (:require [whitman.config :as config]
            [whitman.crawler :as crawler]
            [whitman.db :as db]
            [whitman.writer :as writer])
  (:gen-class))

(defn exit [code msg]
  (binding [*out* *err*]
    (do (println msg)
        (System/exit code))))

(defn do-crawl [cfg writer]
  (let [users (crawler/records cfg)
        docs (map #(crawler/sample-docs cfg %) users)]
    (doseq [d docs] (writer/write writer cfg (:query d) (:insert d)))))

(defn writer [args]
  :db)

(defn -main [& args]
  (if (< (count args) 1)
    (exit 1 "No configuration file specified")
    (do-crawl (config/read-config (last args)) (writer args))))

(ns whitman.core
  (:require [whitman.config :as config]
            [whitman.crawler :as crawler]
            [whitman.db :as db]
            [whitman.writer :as writer])
  (:gen-class))

(defn exit [code msg]
  (binding [*out* *err*]
    (do (println msg)
        (System/exit code))))

(defn do-crawl [cfg writer]
  (let [users (crawler/records cfg)
        docs (map #(crawler/sample-docs cfg %) users)]
    (doseq [d docs] (writer/write writer cfg (:query d) (:insert d)))))

(defn writer [args]
  (case (nth args 0)
    "-d"      :console
    "--debug" :console
    :db))

(defn -main [& args]
  (if (< (count args) 1)
    (exit 1 "No configuration file specified")
    (do-crawl (config/read-config (last args)) (writer args))))

Print output to console when running with debug flags

Closes #2.


(ns mdr2.dtb
  "Functions to query DAISY Talking Books"
  (:require [clojure.data.xml :as xml]
            [clojure.java.io :refer [file]])
  (:import javax.sound.sampled.AudioSystem))

(defn file-audio-length
  "Get the length of the audio in seconds for a given audio file"
  [file]
  ;; see http://stackoverflow.com/questions/3009908/how-do-i-get-a-sound-files-total-time-in-java
  (let [stream (AudioSystem/getAudioInputStream file)
        format (.getFormat stream)
        frameRate (.getFrameRate format)
        frames (.getFrameLength stream)
        durationInSeconds (/ frames frameRate)]
    durationInSeconds))

(defn audio-file? [file]
  (and (.isFile file)
       (.endsWith ".wav" (.getName file))))

(defn audio-length [dtb]
  (let [audio-files (filter audio-file? (file-seq (file dtb)))]
    (reduce + (map file-audio-length audio-files))))

(ns mdr2.dtb
  "Functions to query DAISY Talking Books"
  (:require [clojure.data.xml :as xml]
            [clojure.java.io :refer [file]])
  (:import javax.sound.sampled.AudioSystem))

(defn file-audio-length
  "Get the length of the audio in seconds for a given audio file"
  [file]
  ;; see http://stackoverflow.com/questions/3009908/how-do-i-get-a-sound-files-total-time-in-java
  (let [stream (AudioSystem/getAudioInputStream file)
        format (.getFormat stream)
        frameRate (.getFrameRate format)
        frames (.getFrameLength stream)
        durationInSeconds (/ frames frameRate)]
    durationInSeconds))

(defn wav-file? [file]
  (and (.isFile file)
       (.endsWith (.getName file) ".wav")))

(defn audio-length [dtb]
  (let [audio-files (filter wav-file? (file-seq (file dtb)))]
    (reduce + (map file-audio-length audio-files))))

Fix a problem in the wav-file? function

Fix a problem in the wav-file? function


(ns caesium.magicnonce.secretbox-test
  (:require [caesium.magicnonce.secretbox :as ms]
            [caesium.crypto.secretbox :as s]
            [caesium.crypto.secretbox-test :as st]
            [clojure.test :refer [deftest is]]
            [caesium.util :as u]))

(deftest xor-test
  (let [one (byte-array [1 0 1])
        two (byte-array [0 1 0])
        out (byte-array [0 0 0])]
    (is (identical? (#'ms/xor! out one two) out))
    (is (u/array-eq (byte-array [1 1 1]) out)))
  (let [one (byte-array [1 0 1])
        two (byte-array [0 1 0])]
    (is (identical? (#'ms/xor-inplace! one two) one))
    (is (u/array-eq (byte-array [1 1 1]) one))))

(deftest secretbox-pfx-test
  (let [nonce (byte-array (range s/noncebytes))
        ctext (ms/secretbox-pfx st/ptext nonce st/secret-key)]
    (is (= (+ s/noncebytes
              (alength ^bytes st/ptext)
              s/macbytes)
           (alength ^bytes ctext)))))

(ns caesium.magicnonce.secretbox-test
  (:require [caesium.magicnonce.secretbox :as ms]
            [caesium.crypto.secretbox :as s]
            [caesium.crypto.secretbox-test :as st]
            [clojure.test :refer [deftest is]]
            [caesium.util :as u]))

(deftest xor-test
  (let [one (byte-array [1 0 1])
        two (byte-array [0 1 0])
        out (byte-array [0 0 0])]
    (is (identical? (#'ms/xor! out one two) out))
    (is (u/array-eq (byte-array [1 1 1]) out)))
  (let [one (byte-array [1 0 1])
        two (byte-array [0 1 0])]
    (is (identical? (#'ms/xor-inplace! one two) one))
    (is (u/array-eq (byte-array [1 1 1]) one))))

(deftest secretbox-pfx-test
  (let [nonce (byte-array (range s/noncebytes))
        ctext (ms/secretbox-pfx st/ptext nonce st/secret-key)]
    (is (= (+ s/noncebytes
              (alength ^bytes st/ptext)
              s/macbytes)
           (alength ^bytes ctext)))
    (is (= (range s/noncebytes)
           (take s/noncebytes ctext)))))

Test what the nonce is

Test what the nonce is


(ns bob (:require [clojure.string :as str]))

(defn response-for [x]
	(cond
		(str/blank? x) "Fine, be that way."
		(= (str/upper-case x) x) "Woah, chill out!"
		(= \? (get x (- (count x) 1))) "Sure."
		:else "Whatever."
	)
)

(ns bob (:require [clojure.string :as str]))

(defn response-for [x]
	(cond
		(str/blank? x) "Fine, be that way."
		(= (str/upper-case x) x) "Woah, chill out!"
		(= \? (last x)) "Sure."
		:else "Whatever."
	)
)

Use more clojure idomatic _last_ function.


(defproject io.nervous/fink-nottle "0.1.0"
  :description "Asynchronous Clojure client for the Amazon SNS service"
  :url "https://github.com/nervous-systems/fink-nottle"
  :license {:name "Unlicense" :url "http://unlicense.org/UNLICENSE"}
  :scm {:name "git" :url "https://github.com/nervous-systems/fink-nottle"}
  :deploy-repositories [["clojars" {:creds :gpg}]]
  :signing {:gpg-key "moe@nervous.io"}
  :global-vars {*warn-on-reflection* true}
  :source-paths ["src" "test"]
  :dependencies [[org.clojure/clojure    "1.6.0"]
                 [org.clojure/core.async "0.1.346.0-17112a-alpha"]
                 [org.clojure/data.codec "0.1.0"]

                 [io.nervous/eulalie     "0.3.2"]
                 [io.nervous/glossop     "0.1.0"]

                 [prismatic/plumbing     "0.4.1"]
                 [cheshire               "5.5.0"]]
  :exclusions [[org.clojure/clojure]])

(defproject io.nervous/fink-nottle "0.1.1"
  :description "Asynchronous Clojure client for the Amazon SNS service"
  :url "https://github.com/nervous-systems/fink-nottle"
  :license {:name "Unlicense" :url "http://unlicense.org/UNLICENSE"}
  :scm {:name "git" :url "https://github.com/nervous-systems/fink-nottle"}
  :deploy-repositories [["clojars" {:creds :gpg}]]
  :signing {:gpg-key "moe@nervous.io"}
  :global-vars {*warn-on-reflection* true}
  :source-paths ["src" "test"]
  :dependencies [[org.clojure/clojure    "1.6.0"]
                 [org.clojure/core.async "0.1.346.0-17112a-alpha"]
                 [org.clojure/data.codec "0.1.0"]

                 [io.nervous/eulalie     "0.3.2"]
                 [io.nervous/glossop     "0.1.0"]

                 [prismatic/plumbing     "0.4.1"]
                 [cheshire               "5.5.0"]]
  :exclusions [[org.clojure/clojure]])

Bump version number to 0.1.1

Bump version number to 0.1.1


(defproject basex "0.1.0-SNAPSHOT"
  :description "FIXME: write description"
  :url "http://example.com/FIXME"
  :license {:name "Eclipse Public License"
            :url "http://www.eclipse.org/legal/epl-v10.html"}

  :java-source-paths  ["src/main/java"]
  :source-paths ["src/main/clojure"]

  :dependencies [[org.clojure/clojure "1.5.1"] ]

  :profiles { :dev { :repositories { "BaseX Maven Repository" "http://files.basex.org/maven" }
                     :dependencies [[org.basex/basex "7.8.2"]
                                    [midje "1.5.1"]
                                    [lein-midje "3.0.0"]
                                    [me.raynes/fs "1.4.4"]]}})

(defproject basex "0.1.0-SNAPSHOT"
  :description "FIXME: write description"
  :url "http://example.com/FIXME"
  :license {:name "Eclipse Public License"
            :url "http://www.eclipse.org/legal/epl-v10.html"}

  :java-source-paths  ["src/main/java"]
  :source-paths ["src/main/clojure"]

  :dependencies [[org.clojure/clojure "1.5.1"] ]

  :profiles { :dev { :repositories { "BaseX Maven Repository" "http://files.basex.org/maven" }
                     :plugins [[lein-midje "3.0.0"]]
                     :dependencies [[org.basex/basex "7.8.2"]
                                    [midje "1.5.1"]
                                    [me.raynes/fs "1.4.4"]]}})

Move lein-midje into dev plugins

Move lein-midje into dev plugins


(defproject suricatta "0.1.0-SNAPSHOT"
  :description "High level sql toolkit for clojure (backed by jooq library)"
  :url "http://example.com/FIXME"
  :license {:name "Apache 2.0"
            :url "http://www.apache.org/licenses/LICENSE-2.0.txt"}
  :dependencies [[org.clojure/clojure "1.7.0-alpha2"]
                 [org.jooq/jooq "3.4.2"]
                 [clojure.jdbc "0.3.0-SNAPSHOT"]
                 [postgresql "9.3-1101.jdbc41"]
                 [com.h2database/h2 "1.3.176"]])

(defproject suricatta "0.1.0-SNAPSHOT"
  :description "High level sql toolkit for clojure (backed by jooq library)"
  :url "http://example.com/FIXME"
  :license {:name "Apache 2.0"
            :url "http://www.apache.org/licenses/LICENSE-2.0.txt"}
  :dependencies [[org.clojure/clojure "1.6.0"]
                 [org.jooq/jooq "3.4.2"]
                 [clojure.jdbc "0.3.0-SNAPSHOT"]
                 [postgresql "9.3-1101.jdbc41"]
                 [com.h2database/h2 "1.3.176"]])

Set clojure version to the las stable: 1.6.0


(ns nightmod.utils
  (:require [clojure.java.io :as io])
  (:import [java.text SimpleDateFormat]))

(def ^:const properties-file ".properties")

(def main-dir (atom nil))
(def project-dir (atom nil))
(def error (atom nil))

(defn get-data-dir
  []
  (let [home-dir (System/getProperty "user.home")
        app-name "Nightmod"
        app-name-lower (clojure.string/lower-case app-name)
        osx-dir (io/file home-dir "Library" "Application Support" app-name)
        win-dir (io/file home-dir "AppData" "Roaming" app-name)]
    (.getCanonicalPath
      (cond
        (.exists (.getParentFile osx-dir)) osx-dir
        (.exists (.getParentFile win-dir)) win-dir
        :else (if-let [config-dir (System/getenv "XDG_CONFIG_HOME")]
                (io/file config-dir app-name-lower)
                (io/file home-dir ".config" app-name-lower))))))

(defn format-date
  [unix-time]
  (.format (SimpleDateFormat. "yyyy.MM.dd HH:mm:ss") unix-time))

(defn new-project!
  [template]
  (let [project-name (str (System/currentTimeMillis))
        project-file (io/file @main-dir project-name)]
    (.mkdirs project-file)
    (doseq [f (-> (io/resource template) io/file .listFiles)]
      (io/copy f (io/file project-file (.getName f))))
    (.getCanonicalPath project-file)))

(ns nightmod.utils
  (:require [clojure.java.io :as io])
  (:import [java.text SimpleDateFormat]))

(def ^:const properties-file ".properties")

(def main-dir (atom nil))
(def project-dir (atom nil))
(def error (atom nil))

(defn get-data-dir
  []
  (.getCanonicalPath (io/file (System/getProperty "user.home") "nightmod")))

(defn format-date
  [unix-time]
  (.format (SimpleDateFormat. "yyyy.MM.dd HH:mm:ss") unix-time))

(defn new-project!
  [template]
  (let [project-name (str (System/currentTimeMillis))
        project-file (io/file @main-dir project-name)]
    (.mkdirs project-file)
    (doseq [f (-> (io/resource template) io/file .listFiles)]
      (io/copy f (io/file project-file (.getName f))))
    (.getCanonicalPath project-file)))

Simplify location of data dir

Simplify location of data dir


(ns frontend.utils)

(defmacro inspect
  "prints the expression '<name> is <value>', and returns the value"
  [value]
  `(do
     (let [name# (quote ~value)
           result# ~value]
       (print (pr-str name#) "is" (pr-str result#))
       result#)))

(defmacro timing
  "Evaluates expr and prints the label and the time it took.
  Returns the value of expr."
  {:added "1.0"}
  [label expr]
  `(let [global-start# (or (aget js/window "__global_time")
                          (aset js/window "__global_time" (.getTime (js/Date.))))
         start# (.getTime (js/Date.))
         ret# ~expr
         global-time# (- (.getTime (js/Date.)) global-start#)]
     (aset js/window "__global_time" (.getTime (js/Date.)))
     (prn (str ~label " elapsed time: " (- (.getTime (js/Date.)) start#) " ms, " global-time# " ms since last"))
     ret#))

(defmacro swallow-errors
  "wraps errors in a try/catch statement, logging issues to the console
   and optionally rethrowing them if configured to do so."
  [action]
  `(try ~action
        (catch js/Error e#
          (merror e#)
          (when (:rethrow-errors? initial-query-map)
            (js* "debugger;")
            (throw e#)))))

Add macro to DRY up exception handling in channel code.


(ns leipzig-live.core
    (:require [reagent.core :as reagent :refer [atom]]
              [reagent.session :as session]
              [secretary.core :as secretary :include-macros true]
              [accountant.core :as accountant]
              [cljs.js :as cljs]))

;; -------------------------
;; Model
(defonce music (atom "7"))

;; -------------------------
;; Behaviour
(defonce compiler-state (cljs/empty-state))
(defn evaluate
  [expr-str]
  (cljs/eval-str
    compiler-state
    expr-str
    nil
    {:eval cljs/js-eval}
    #(print-str expr-str " evaluates to " %)))

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

(defn home-page []
  [:div [:h1 "Welcome to Leipzig Live!"]
   [:div [:input {:type "text"
                  :value (-> music deref print-str)
                  :on-change #(reset! music (-> % .-target .-value))}]]
   [:div
    (evaluate @music)]])

(defn current-page []
  [:div [(session/get :current-page)]])

;; -------------------------
;; Routes

(secretary/defroute "/" []
  (session/put! :current-page #'home-page))

;; -------------------------
;; Initialize app

(defn mount-root []
  (reagent/render [current-page] (.getElementById js/document "app")))

(defn init! []
  (accountant/configure-navigation!)
  (accountant/dispatch-current!)
  (mount-root))

(ns leipzig-live.core
    (:require [reagent.core :as reagent :refer [atom]]
              [reagent.session :as session]
              [secretary.core :as secretary :include-macros true]
              [accountant.core :as accountant]
              [cljs.js :as cljs]))

;; -------------------------
;; Model
(defonce music (atom ""))

;; -------------------------
;; Behaviour
(defn identify
  "Hack to make literal values still evaluate."
  [expr-str]
  (str "(identity " expr-str ")"))

(defonce compiler-state (cljs/empty-state))
(defn evaluate
  [expr-str]
    (cljs/eval-str
      compiler-state
      (identify expr-str)
      nil
      {:eval cljs/js-eval}
      #(:value %)))

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

(defn home-page []
  [:div [:h1 "Welcome to Leipzig Live!"]
   [:div [:input {:type "text"
                  :value (-> music deref print-str)
                  :on-change #(reset! music (-> % .-target .-value))}]]
   [:div
    (evaluate @music)]])

(defn current-page []
  [:div [(session/get :current-page)]])

;; -------------------------
;; Routes

(secretary/defroute "/" []
  (session/put! :current-page #'home-page))

;; -------------------------
;; Initialize app

(defn mount-root []
  (reagent/render [current-page] (.getElementById js/document "app")))

(defn init! []
  (accountant/configure-navigation!)
  (accountant/dispatch-current!)
  (mount-root))

Make the REPL work with literals.

Make the REPL work with literals.


(ns dasha.core)

(defn log
  [data]
  (.log js/console (str data)))

(log "test")

(ns dasha.core
  (:require-macros
   [cljs.core.async.macros :as asyncm :refer (go go-loop)])
  (:require
   ;; <other stuff>
   [cljs.core.async :as async :refer (<! >! put! chan)]
   [taoensso.sente  :as sente :refer (cb-success?)]))

(defn log
  [data]
  (.log js/console (str data)))

(defn route-receive
  [[event data]]
  (log (str "received " event " with data: " data))
    )

(defn route-event
  [[event-id data :as all]]
  (case event-id
    :chsk/state (log (str "first open: " (:first-open? data)))
    :chsk/recv (route-receive data)
    (log (str "undefined event: " all))))

(let [{:keys [chsk ch-recv send-fn state]}
      (sente/make-channel-socket! "/chsk" ; Note the same path as before
       {:type :auto ; e/o #{:auto :ajax :ws}
       })]
  (def chsk       chsk)
  (def ch-chsk    ch-recv) ; ChannelSocket's receive channel
  (def chsk-send! send-fn) ; ChannelSocket's send API fn
  (def chsk-state state)   ; Watchable, read-only atom

  (go
     (while true
       (route-event (:event (<! ch-recv)))))

  )

Test web socket connection works

Test web socket connection works


(ns tensorflow-clj.core
  (:gen-class))

(def ^:dynamic graph nil)

(defmacro with-graph [& body]
  `(binding [graph (org.tensorflow.Graph.)]
     (try
       ~@body
       (finally
         (.close graph)))))

(defn- build-op [op-type op-name attr-map]
  (let [ob (.opBuilder graph op-type (name op-name))]
    (doseq [[attr-name attr-value] attr-map]
      (.setAttr ob attr-name attr-value))
    (-> ob (.build) (.output 0))))

(defn tensor [value]
  (org.tensorflow.Tensor/create value))

(defn constant [name value]
  (let [t (tensor value)]
    (build-op "Const" name {"dtype" (.dataType t) "value" t})))

(defn variable [name]
  (build-op "Variable" name
    {"dtype" org.tensorflow.DataType/DOUBLE
     "shape" (org.tensorflow.Shape/scalar)}))

(defn run-and-fetch [name]
  (with-open [sess (org.tensorflow.Session. graph)]
    (-> sess (.runner)
      (.fetch (name name))
      (.run))))

(defn -main
  "I don't do a whole lot ... yet."
  [& args]
  (println "Hello, World!"))

(ns tensorflow-clj.core
  (:gen-class))

(def ^:dynamic graph nil)

(defmacro with-graph [& body]
  `(binding [graph (org.tensorflow.Graph.)]
     (try
       ~@body
       (finally
         (.close graph)))))

(defn- build-op [op-type op-name attr-map]
  (let [ob (.opBuilder graph op-type (name op-name))]
    (doseq [[attr-name attr-value] attr-map]
      (.setAttr ob attr-name attr-value))
    (-> ob (.build) (.output 0))))

(defn tensor [value]
  (org.tensorflow.Tensor/create value))

(defn constant [name value]
  (let [t (tensor value)]
    (build-op "Const" name {"dtype" (.dataType t) "value" t})))

(defn variable [name]
  (build-op "Variable" name
    {"dtype" org.tensorflow.DataType/DOUBLE
     "shape" (org.tensorflow.Shape/scalar)}))

(defn run-and-fetch [name]
  (with-open [sess (org.tensorflow.Session. graph)]
    (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."
  [& args]
  (println "Hello, World!"))

Throw an exception instead of segfaulting


{:name "aggregate"
 :path ""
 :func (let [result (volatile! [])]
         (fn[data]
           (if (pg/eoi? data)
             @result
             (do
               (vswap! result (fn[resval] (conj resval data)))
               (pg/need)))))

 :description "Streaming aggregation. Takes a stream of data and constructs a vector containing all data. This is mostly for aggregating result maps of upstream nodes. Similar to eager seqs in that all data will be used at once. BE CAREFUL."
 }

{:name "aggregate"
 :path ""
 :func (let [result (volatile! [])]
         (fn[data]
           (if (and (pg/eoi? data) (pg/done? data))
             @result
             (do
               (vswap! result (fn[resval] (conj resval data)))
               (pg/need)))))

 :description "Streaming aggregation. Takes a stream of data and constructs a vector containing all data. This is mostly for aggregating result maps of upstream nodes. Similar to eager seqs in that all data will be used at once. BE CAREFUL."
 }

Make sure only return on final done, not just eoi!


(defproject shrimp "0.1.0-SNAPSHOT"
            :description "Demo project for Goby."
            :dependencies [[org.clojure/clojure "1.6.0"]
                           [org.clojure/clojurescript "0.0-2511"]
                           [org.clojure/core.async "0.1.346.0-17112a-alpha"]
                           [goby "0.1.0"]
                           [weasel "0.4.2"]]
            :plugins [[lein-cljsbuild "1.0.3"]
                      [jarohen/simple-brepl "0.1.2"]]
            :source-paths ["src"]
            :brepl {:ip "127.0.0.1"}
            :cljsbuild {:builds {:dev
                                  {:source-paths ["src"
                                                  "dev-src"]
                                   :compiler     {:output-to     "js/main.js"
                                                  :optimizations :whitespace
                                                  :static-fns    false
                                                  :externs       ["externs.js"]
                                                  :pretty-print  true}}
                                 :rel
                                  {:source-paths ["src"
                                                  "rel-src"]
                                   :compiler     {:output-to     "js/main.js"
                                                  :optimizations :advanced
                                                  :static-fns    true
                                                  :externs       ["externs.js"]
                                                  :pretty-print  false
                                                  :pseudo-names  false}}}})

(defproject shrimp "0.1.0-SNAPSHOT"
            :description "Demo project for Goby."
            :dependencies [[org.clojure/clojure "1.6.0"]
                           [org.clojure/clojurescript "0.0-2665"]
                           [org.clojure/core.async "0.1.346.0-17112a-alpha"]
                           [goby "0.1.0"]
                           [weasel "0.5.0"]]
            :plugins [[lein-cljsbuild "1.0.3"]
                      [jarohen/simple-brepl "0.2.1"]]
            :source-paths ["src"]
            :brepl {:ip "127.0.0.1"}
            :cljsbuild {:builds {:dev
                                  {:source-paths ["src"
                                                  "dev-src"]
                                   :compiler     {:output-to     "js/main.js"
                                                  :optimizations :whitespace
                                                  :static-fns    false
                                                  :externs       ["externs.js"]
                                                  :pretty-print  true}}
                                 :rel
                                  {:source-paths ["src"
                                                  "rel-src"]
                                   :compiler     {:output-to     "js/main.js"
                                                  :optimizations :advanced
                                                  :static-fns    true
                                                  :externs       ["externs.js"]
                                                  :pretty-print  false
                                                  :pseudo-names  false}}}})

Update to ClojureScript 0.0-2665. Also update simple-brepl and Weasel to compatible versions.


(ns circle.logging
  (:import (org.apache.log4j Logger
			     BasicConfigurator
                             EnhancedPatternLayout
			     Level
                             ConsoleAppender
                             SimpleLayout)
	   (org.apache.log4j.spi RootLogger))
  (:import (org.apache.log4j.rolling TimeBasedRollingPolicy
                                     RollingFileAppender))
  (:import org.apache.commons.logging.LogFactory))

(defn set-level [logger level]
  (. (Logger/getLogger logger) (setLevel level)))

(defn init []
  (let [rolling-policy (doto (TimeBasedRollingPolicy.)
                         (.setActiveFileName  "circle.log" )
                         (.setFileNamePattern "circle-%d{yyyy-MM-dd}.log.gz")
                         (.activateOptions))
        layout (EnhancedPatternLayout. "%p [%d] %t - %c - %m%n")
        rolling-log-appender (doto (RollingFileAppender.)
                               (.setRollingPolicy rolling-policy)
                               (.setLayout layout)
                               (.activateOptions))]
    (doto (Logger/getRootLogger)
      (.removeAllAppenders)
      (.addAppender rolling-log-appender)
      (.addAppender (ConsoleAppender. layout))))
  (. (Logger/getRootLogger) (setLevel Level/DEBUG))
  (set-level "jclouds.wire" Level/OFF)
  (set-level "jclouds.headers" Level/OFF)
  (set-level "jclouds.signature" Level/OFF))

(ns circle.logging
  (:import (org.apache.log4j Logger
			     BasicConfigurator
                             EnhancedPatternLayout
			     Level
                             ConsoleAppender
                             SimpleLayout)
	   (org.apache.log4j.spi RootLogger))
  (:import (org.apache.log4j.rolling TimeBasedRollingPolicy
                                     RollingFileAppender))
  (:import org.apache.commons.logging.LogFactory))

(defn set-level [logger level]
  (. (Logger/getLogger logger) (setLevel level)))

(defn init []
  (let [rolling-policy (doto (TimeBasedRollingPolicy.)
                         (.setActiveFileName  "circle.log" )
                         (.setFileNamePattern "circle-%d{yyyy-MM-dd}.log.gz")
                         (.activateOptions))
        layout (EnhancedPatternLayout. "%p [%d] %t - %c - %m%n")
        rolling-log-appender (doto (RollingFileAppender.)
                               (.setRollingPolicy rolling-policy)
                               (.setLayout layout)
                               (.activateOptions))]
    (doto (Logger/getRootLogger)
      (.removeAllAppenders)
      (.addAppender rolling-log-appender)
      (.addAppender (ConsoleAppender. layout))))
  (. (Logger/getRootLogger) (setLevel Level/INFO))
  (set-level "jclouds.wire" Level/OFF)
  (set-level "jclouds.headers" Level/OFF)
  (set-level "jclouds.signature" Level/OFF))

Raise the log level to info

Raise the log level to info


(ns discuss.texts.lib
  (:require [cljs.spec.alpha :as s]
            [clojure.string :as string]
            [discuss.translations :refer [translate] :rename {translate t}]))

(defn join-with-and
  "Join collection of strings with `and`."
  [col]
  (string/join (str " <i>" (t :common :and) "</i> ") col))
(s/fdef join-with-and
  :args (s/cat :col (s/coll-of string?))
  :ret string?)

(ns discuss.texts.lib
  (:require [cljs.spec.alpha :as s]
            [clojure.string :as string]
            [goog.string :refer [format]]
            [goog.string.format]
            [discuss.translations :refer [translate] :rename {translate t}]))

(defn join-with-and
  "Join collection of strings with `and`."
  [col]
  (string/join (str " " (t :common :and) " ") col))
(s/fdef join-with-and
  :args (s/cat :col (s/coll-of string?))
  :ret string?)

;; -----------------------------------------------------------------------------
;; Highlight strings with html classes

(defn highlight-premise [premise]
  (format "%s" premise))

(defn highlight-conclusion [premise]
  (format "%s" premise))

(defn highlight-undercut [premise]
  (format "%s" premise))

Add fns to highlight text passages

Add fns to highlight text passages


(let [dev-deps '[[speclj "2.3.0"]]]

  (defproject reply "0.2.0-SNAPSHOT"
    :description "REPL-y: A fitter, happier, more productive REPL for Clojure."
    :dependencies [[org.clojure/clojure "1.4.0"]
                   [jline/jline "2.10"]
                   [org.thnetos/cd-client "0.3.6"]
                   [clj-stacktrace "0.2.4"]
                   [org.clojure/tools.nrepl "0.2.1"]
                   [org.clojure/tools.cli "0.2.1"]
                   [com.cemerick/drawbridge "0.0.6"]
                   [trptcolin/versioneer "0.1.0"]
                   [clojure-complete "0.2.2"]
                   [org.clojars.trptcolin/sjacket "0.1.0.3"
                    :exclusions [org.clojure/clojure]]]
    :profiles {:dev {:dependencies ~dev-deps}}
    :dev-dependencies ~dev-deps
    :plugins ~dev-deps
    :aot [reply.reader.jline.JlineInputReader]
    :source-path "src/clj"
    :java-source-path "src/java"
    :test-path "spec"
    :source-paths ["src/clj"]
    :java-source-paths ["src/java"]
    :test-paths ["spec"]
    :main ^{:skip-aot true} reply.ReplyMain))

(let [dev-deps '[[speclj "2.3.0"]]]

  (defproject reply "0.2.0-SNAPSHOT"
    :description "REPL-y: A fitter, happier, more productive REPL for Clojure."
    :dependencies [[org.clojure/clojure "1.4.0"]
                   [jline/jline "2.10"]
                   [org.thnetos/cd-client "0.3.6"]
                   [clj-stacktrace "0.2.4"]
                   [org.clojure/tools.nrepl "0.2.1"]
                   [org.clojure/tools.cli "0.2.1"]
                   [com.cemerick/drawbridge "0.0.6"]
                   [trptcolin/versioneer "0.1.0"]
                   [clojure-complete "0.2.2"]
                   [org.clojars.trptcolin/sjacket "0.1.0.3"
                    :exclusions [org.clojure/clojure]]]
    :profiles {:dev {:dependencies ~dev-deps}}
    :dev-dependencies ~dev-deps
    :plugins ~dev-deps
    :aot [reply.reader.jline.JlineInputReader]
    :source-path "src/clj"
    :java-source-path "src/java"
    :test-path "spec"
    :source-paths ["src/clj"]
    :java-source-paths ["src/java"]
    :test-paths ["spec"]
    :repl-options {:init-ns user}
    :main ^{:skip-aot true} reply.ReplyMain))

Add repl options since :main is bad w/ classnames


(defproject buddy/buddy-sign "0.5.0-SNAPSHOT"
  :description "High level message signing"
  :url "https://github.com/funcool/buddy-sign"
  :license {:name "BSD (2-Clause)"
            :url "http://opensource.org/licenses/BSD-2-Clause"}
  :dependencies [[org.clojure/clojure "1.6.0"]
                 [com.taoensso/nippy "2.8.0"]
                 [buddy/buddy-core "0.5.0-SNAPSHOT"]
                 [slingshot "0.12.2"]
                 [cats "0.4.0"]
                 [clj-time "0.9.0"]
                 [cheshire "5.4.0"]]
  :source-paths ["src"]
  :javac-options ["-target" "1.7" "-source" "1.7" "-Xlint:-options"]
  :test-paths ["test"])

(defproject buddy/buddy-sign "0.5.0-SNAPSHOT"
  :description "High level message signing"
  :url "https://github.com/funcool/buddy-sign"
  :license {:name "BSD (2-Clause)"
            :url "http://opensource.org/licenses/BSD-2-Clause"}
  :dependencies [[org.clojure/clojure "1.6.0"]
                 [com.taoensso/nippy "2.8.0"]
                 [buddy/buddy-core "0.5.0"]
                 [slingshot "0.12.2"]
                 [cats "0.4.0"]
                 [clj-time "0.9.0"]
                 [cheshire "5.4.0"]]
  :source-paths ["src"]
  :javac-options ["-target" "1.7" "-source" "1.7" "-Xlint:-options"]
  :test-paths ["test"])

Set buddy-core dependency to 0.5.0.

Set buddy-core dependency to 0.5.0.


(defproject uxbox-backend "0.1.0-SNAPSHOT"
  :description "UXBox backend."
  :url "http://uxbox.github.io"
  :license {:name "MPL 2.0" :url "https://www.mozilla.org/en-US/MPL/2.0/"}
  :source-paths ["src"]
  :javac-options ["-target" "1.8" "-source" "1.8" "-Xlint:-options"]
  :jvm-opts ["-Dclojure.compiler.direct-linking=true"]
  :dependencies [[org.clojure/clojure "1.8.0" :scope "provided"]
                 [org.slf4j/slf4j-simple "1.7.18"]
                 [bouncer "1.0.0"]
                 [mount "0.1.10"]
                 [environ "1.0.2"]
                 [buddy/buddy-sign "0.9.0"]
                 [buddy/buddy-hashers "0.11.0"]
                 [com.github.spullara.mustache.java/compiler "0.9.1"]
                 [org.postgresql/postgresql "9.4.1208" :scope "provided"]
                 [niwinz/migrante "0.1.0"]
                 [funcool/suricatta "0.8.1"]
                 [funcool/promesa "0.8.1"]
                 [hikari-cp "1.6.1"]
                 [funcool/catacumba "0.11.2"]])

(defproject uxbox-backend "0.1.0-SNAPSHOT"
  :description "UXBox backend."
  :url "http://uxbox.github.io"
  :license {:name "MPL 2.0" :url "https://www.mozilla.org/en-US/MPL/2.0/"}
  :source-paths ["src"]
  :javac-options ["-target" "1.8" "-source" "1.8" "-Xlint:-options"]
  :jvm-opts ["-Dclojure.compiler.direct-linking=true"]
  :dependencies [[org.clojure/clojure "1.8.0" :scope "provided"]
                 [org.slf4j/slf4j-simple "1.7.18"]
                 [bouncer "1.0.0"]
                 [mount "0.1.10"]
                 [environ "1.0.2"]
                 [buddy/buddy-sign "0.9.0"]
                 [buddy/buddy-hashers "0.11.0"]
                 [com.github.spullara.mustache.java/compiler "0.9.1"]
                 [org.postgresql/postgresql "9.4.1208" :scope "provided"]
                 [niwinz/migrante "0.1.0"]
                 [funcool/suricatta "0.8.1"]
                 [funcool/promesa "0.8.1"]
                 [hikari-cp "1.6.1"]
                 [funcool/catacumba "0.11.3-SNAPSHOT"]])

Set 0.11.3-SNAPSHOT version of catacumba.


(defproject prismatic/fnhouse "0.1.0-SNAPSHOT"
  :description "Transform lightly-annotated functions into a full-fledged web service"
  :license {:name "Eclipse Public License - v 1.0"
            :url "http://www.eclipse.org/legal/epl-v10.html"
            :distribution :repo}
  :url "https://github.com/Prismatic/fnhouse"
  :dependencies [[prismatic/plumbing "0.2.1"]]
  :profiles {:dev {:dependencies [[org.clojure/clojure "1.5.1"]]
                   :warn-on-reflection true}
             :1.4 {:dependencies [[org.clojure/clojure "1.4.0"]]}}
  :lein-release {:deploy-via :shell
                 :shell ["lein" "deploy" "clojars"]}
  :aliases {"all" ["with-profile" "dev:dev,1.4"]})

(defproject prismatic/fnhouse "0.1.0-SNAPSHOT"
  :description "Transform lightly-annotated functions into a full-fledged web service"
  :license {:name "Eclipse Public License - v 1.0"
            :url "http://www.eclipse.org/legal/epl-v10.html"
            :distribution :repo}
  :url "https://github.com/Prismatic/fnhouse"
  :dependencies [[prismatic/plumbing "0.2.2"]]
  :profiles {:dev {:dependencies [[org.clojure/clojure "1.5.1"]]
                   :warn-on-reflection true}
             :1.6 {:dependencies [[org.clojure/clojure "1.6.0-RC1"]]}}
  :aliases {"all" ["with-profile" "dev:dev,1.6"]}
  :lein-release {:deploy-via :shell
                 :shell ["lein" "deploy" "clojars"]})

Bump plumbing dep and test on Clojure 1.6


(defproject com.hypirion/inlein-repl "0.1.0"
  :description "Base repl dependencies for inlein."
  :url "http://inlein.org"
  :license {:name "Eclipse Public License"
            :url "http://www.eclipse.org/legal/epl-v10.html"}
  :source-paths []
  :dependencies [[org.clojure/clojure "1.8.0"]
                 [net.cgrand/parsley "0.9.3" :exclusions [org.clojure/clojure]]
                 [reply "0.3.7" :exclusions [ring/ring-core
                                             com.cemerick/drawbridge]]])

(defproject com.hypirion/inlein-repl "0.2.0-SNAPSHOT"
  :description "Base repl dependencies for inlein."
  :url "http://inlein.org"
  :license {:name "Eclipse Public License"
            :url "http://www.eclipse.org/legal/epl-v10.html"}
  :source-paths []
  :dependencies [[org.clojure/clojure "1.8.0"]
                 [net.cgrand/parsley "0.9.3" :exclusions [org.clojure/clojure]]
                 [reply "0.3.7" :exclusions [ring/ring-core
                                             com.cemerick/drawbridge]]])

Bump repl dependencies back to snapshot

Bump repl dependencies back to snapshot


(ns {{name}}.core
  (:require-macros [retro-fever.macros :refer [game]])
  (:require [retro-fever.core :as core]
            [retro-fever.input :as input]
            [retro-fever.sprite :as sprite]
            [retro-fever.asset :as asset]))

(defonce game-state (atom {})) ; Atom to store the game state

(defn update-fn []) ; Update function called on each iteration in the game loop

(defn render-fn [context]) ; Render function called on each iteration in the game loop

(defn load-resources []) ; Function to load all the game resources

(defn setup []) ; Function to setup initial game state

(defn ^:export init [] ; The entry point into the game from the HTML page
  (.log js/console "Launching game")

  (core/init-canvas "game-canvas" 640 480) ; Initialize canvas on HTML page
  (input/init) ; Initialize input devices

  (load-resources) ; Load game resources, such as images and animations
  (core/setup setup) ; Setup the initial game state
  (game core/game-loop update-fn render-fn 60) ; Create and start the game loop
)

(ns {{name}}.core
  (:require-macros [retro-fever.macros :refer [game]])
  (:require [retro-fever.core :as core]
            [retro-fever.input :as input]
            [retro-fever.sprite :as sprite]
            [retro-fever.asset :as asset]))

(enable-console-print!)

(defonce game-state (atom {})) ; Atom to store the game state

(defn update-fn []) ; Update function called on each iteration in the game loop

(defn render-fn [context]) ; Render function called on each iteration in the game loop

(defn load-resources []) ; Function to load all the game resources

(defn setup []) ; Function to setup initial game state

(defn ^:export init [] ; The entry point into the game from the HTML page
  (.log js/console "Launching game")

  (core/init-canvas "game-canvas" 640 480) ; Initialize canvas on HTML page
  (input/init) ; Initialize input devices

  (load-resources) ; Load game resources, such as images and animations
  (core/setup setup) ; Setup the initial game state
  (game core/game-loop update-fn render-fn 60) ; Create and start the game loop
)

Enable console print for easier browser debugging


(def start-t (System/currentTimeMillis))

(defsensor math {:poll-interval (seconds 10)}
  {:sine (Math/sin (/ (- (System/currentTimeMillis) start-t) (minutes 1)))
   :cosine (Math/cos (/ (- (System/currentTimeMillis) start-t) (minutes 1))) })

(defsensor steps-ascending {:poll-interval (seconds 5)}
  (+ 2.3
     (mod (/ (- (System/currentTimeMillis) start-t) (minutes 4))
          3)))

(def start-t (System/currentTimeMillis))

(defn random-sampler [ ]
  (let [current (atom 0.0)]
    (fn [ ]
      (swap! current #(+ % (/ (+ (Math/random) (Math/random)) 2) -0.5)))))

(def rs-0 (random-sampler))
(def rs-1 (random-sampler))
(def rs-2 (random-sampler))

(defsensor random-unconstrained {:poll-interval (seconds 10)}
  (rs-0))

(defsensor random-positive {:poll-interval (seconds 10)}
  (+ 0.1 (Math/abs (rs-1))))

(defsensor random-negative {:poll-interval (seconds 10)}
  (- -0.1 (Math/abs (rs-2))))

(defsensor math {:poll-interval (seconds 10)}
  {:sine (+ 0.3 (Math/sin (/ (- (System/currentTimeMillis) start-t) (minutes 1))))
   :cosine (Math/cos (/ (- (System/currentTimeMillis) start-t) (minutes 1))) })

(defsensor steps-ascending {:poll-interval (seconds 5)}
  (+ 2.3
     (mod (/ (- (System/currentTimeMillis) start-t) (minutes 4))
          3)))

Add some random walk series to the test agent to help test autoscale behavior.


;; Copyright © 2016-2017, JUXT LTD.

(ns tick.deprecated.schedule-test
  (:require
   [clojure.test :refer :all]
   [tick.deprecated.timeline :refer [periodic-seq timeline]]
   [tick.core :refer [seconds millis]]
   [tick.deprecated.clock :refer [clock-ticking-in-seconds just-now]]
   [tick.deprecated.schedule :as sched]))

(deftest ^:deprecated schedule-test
  (let [a (atom 0)
        f (fn [dt] (swap! a inc))
        clk (clock-ticking-in-seconds)
        now (just-now clk)
        timeline (take 10 (timeline (periodic-seq now (millis 10))))]
    @(sched/start (sched/schedule f timeline) clk)
    (is (= @a 10))))

(deftest ^:deprecated simulate-test
  (let [a (atom 0)
        f (fn [dt] (swap! a inc))
        clk (clock-ticking-in-seconds)
        now (just-now clk)
        timeline (take 1000 (timeline (periodic-seq now (seconds 1))))]
    @(sched/start (sched/simulate f timeline) clk)
    (is (= @a 1000))))

;; Copyright © 2016-2017, JUXT LTD.

(ns tick.deprecated.schedule-test
  (:require
   [clojure.test :refer :all]
   [tick.deprecated.timeline :refer [periodic-seq timeline]]
   [tick.core :refer [seconds millis]]
   [tick.deprecated.clock :refer [clock-ticking-in-seconds just-now]]
   [tick.deprecated.schedule :as sched]))

#_(deftest ^:deprecated schedule-test
  (let [a (atom 0)
        f (fn [dt] (swap! a inc))
        clk (clock-ticking-in-seconds)
        now (just-now clk)
        timeline (take 10 (timeline (periodic-seq now (millis 10))))]
    @(sched/start (sched/schedule f timeline) clk)
    (is (= @a 10))))

#_(deftest ^:deprecated simulate-test
  (let [a (atom 0)
        f (fn [dt] (swap! a inc))
        clk (clock-ticking-in-seconds)
        now (just-now clk)
        timeline (take 1000 (timeline (periodic-seq now (seconds 1))))]
    @(sched/start (sched/simulate f timeline) clk)
    (is (= @a 1000))))

Disable schedule test as it is hanging the test runner


(ns subman.core
  (:gen-class)
  (:require [compojure.handler :as handler]
            [overtone.at-at :as at-at]
            [org.httpkit.server :as server]
            [hiccup.middleware :refer [wrap-base-url]]
            [ring.middleware.reload :refer [wrap-reload]]
            [subman.routes :as routes]
            [subman.filler :as filler]
            [subman.const :as const]
            [subman.models :as models]))

(def app (-> (handler/site routes/main-routes)
             wrap-base-url
             wrap-reload))

(defn init-pool []
  (let [pool (at-at/mk-pool)]
    (at-at/every const/update-period
                 (fn [] (println "start update")
                   filler/update-all
                   models/update-total-count
                   (println "update finished"))
                 pool)))

(defn -main [& args]
  (try (models/create-index)
    (catch Exception e (println e)))
  (models/update-total-count)
  (future (init-pool))
  (let [port (Integer/parseInt
              (or (System/getenv "PORT") const/default-port))]
    (server/run-server app {:port port})))

(ns subman.core
  (:gen-class)
  (:require [compojure.handler :as handler]
            [overtone.at-at :as at-at]
            [org.httpkit.server :as server]
            [hiccup.middleware :refer [wrap-base-url]]
            [ring.middleware.reload :refer [wrap-reload]]
            [subman.routes :as routes]
            [subman.filler :as filler]
            [subman.const :as const]
            [subman.models :as models]))

(def app (-> (handler/site routes/main-routes)
             wrap-base-url
             wrap-reload))

(defn init-pool []
  (let [pool (at-at/mk-pool)]
    (at-at/every const/update-period
                 (fn [] (println "start update")
                   (filler/update-all)
                   (models/update-total-count)
                   (println "update finished"))
                 pool)))

(defn -main [& args]
  (try (models/create-index)
    (catch Exception e (println e)))
  (models/update-total-count)
  (future (init-pool))
  (let [port (Integer/parseInt
              (or (System/getenv "PORT") const/default-port))]
    (server/run-server app {:port port})))

Fix actual calling upddate methods

Fix actual calling upddate methods


(ns discuss.config)

(def project "discuss")

(def user "Q2hyaXN0aWFu")

(def api {:host "http://localhost:4284/"
          :init "api/"
          :base "api/"
          :add  {:add-start-statement "add/start_statement"
                 :add-start-premise   "add/start_premise"
                 :add-justify-premise "add/justify_premise"}})

(ns discuss.config)

(def project "discuss")

(def user "Q2hyaXN0aWFu")

(def api {:host "http://localhost:4284/"
          :init "api/"
          :base "api/"
          :add  {:add-start-statement "add/start_statement"
                 :add-start-premise   "add/start_premise"
                 :add-justify-premise "add/justify_premise"}
          :get  {:reference-usages "get/reference_information"
                 :statements       "get/statements"}})

Add new route to get statements from dbas


(ns ecregister.posts_ui
  (:gen-class)
  (:use [seesaw.core])
  (:use [seesaw.mig])
  (:use [seesaw.font])
  (:use [seesaw.border])
  )
(defn make-post-widget [{:keys [author title icon]}]
  (mig-panel
   :items [[(label :border (line-border :color "#ddd" :thickness 1) :size [50 :by 50]) "spany 2"]
           [(label :text author :font (font :name "Arial" :style :bold :size 17))
            "cell 1 0,pushy,bottom"]
           [(label :text title :font (font :name "Arial" :style :italic :size 15)) "cell 1 1,pushy,top"]]
   :constraints ["", "[][]", "[][]"]))

(defn build-posts-tab []
  (let [form
        (mig-panel
         :items [[(label "Последний опубликованный пост") "top,center,wrap"]
                 [(progress-bar :indeterminate? false :value 10) "center,wrap"]
                 [(make-post-widget {:author "Dima" :title "Как я что-то сделал"}) "center"]
                 ]
         :constraints ["fillx,gap 18px"]
         )]
    form))

(ns ecregister.posts_ui
  (:gen-class)
  (:use [seesaw.core])
  (:use [seesaw.mig])
  (:use [seesaw.font])
  (:use [seesaw.border])
  )
(defn make-post-widget [{:keys [author title icon]}]
  (mig-panel
   :items [[(label :border (line-border :color "#ddd" :thickness 1) :size [42 :by 42]) "spany 2"]
           [(label :text author :font (font :name "Arial" :style :bold :size 17))
            "cell 1 0,pushy,bottom"]
           [(label :text title :font (font :name "Arial" :style :italic :size 15)) "cell 1 1,pushy,top"]]
   :constraints ["", "[][]", "[][]"]
   :border (line-border :color "#ccc" :thickness 1)
   :minimum-size [400 :by 0]))

(defn build-posts-tab []
  (let [form
        (mig-panel
         :items [[(label "Последний опубликованный пост") "top,center,wrap"]
                 [(progress-bar :indeterminate? false :value 10) "center,wrap"]
                 [(make-post-widget {:author "Dima" :title "Как я что-то сделал"}) "center,wrap"]
                 [(make-post-widget {:author "Anton" :title "Как я что-то сделал"}) "center,wrap"]
                 ]
         :constraints ["fillx,gap 18px"]
         )]
    form))

Update look of post item label

Update look of post item label


(ns triangle.test (:require [clojure.test :refer :all]))
(load-file "triangle.clj")

(deftest equilateral-1
  (is (= :equilateral (triangle 2 2 2))))
(deftest equilateral-2
  (is (= :equilateral (triangle 10 10 10))))
(deftest isoceles-1
  (is (= :isosceles (triangle 3 4 4))))
(deftest isoceles-2
  (is (= :isosceles (triangle 4 3 4))))
(deftest scalene
  (is (= :scalene (triangle 3 4 5))))
(deftest invalid-1
  (is (= :illogical (triangle 1 1 50))))
(deftest invalid-2
  (is (= :illogical (triangle 1 2 1))))

(run-tests)

(ns triangle.test (:require [clojure.test :refer :all]))
(load-file "triangle.clj")

(deftest equilateral-1
  (is (= :equilateral (triangle/type 2 2 2))))
(deftest equilateral-2
  (is (= :equilateral (triangle/type 10 10 10))))
(deftest isoceles-1
  (is (= :isosceles (triangle/type 3 4 4))))
(deftest isoceles-2
  (is (= :isosceles (triangle/type 4 3 4))))
(deftest scalene
  (is (= :scalene (triangle/type 3 4 5))))
(deftest invalid-1
  (is (= :illogical (triangle/type 1 1 50))))
(deftest invalid-2
  (is (= :illogical (triangle/type 1 2 1))))

(run-tests)

Add namespace to triangle exercise.

Add namespace to triangle exercise.

... to be consistent with other examples. See PR #4 & PR #7.


(ns workflo.macros.entity.datascript
  (:require [datascript.core :as d]
            [workflo.macros.entity.schema :as es]))

(defn attr-schema
  [attr-opts]
  (reduce (fn [opts opt]
            (cond-> opts
              (= :ref opt)
              (assoc :db/valueType :db.type/ref)
              (= :many opt)
              (assoc :db/cardinality :db.cardinality/many)
              (= :unique-value opt)
              (assoc :db/unique :db.unique/value)
              (= :unique-identity opt)
              (assoc :db/unique :db.unique/identity)))
          {} attr-opts))

(defn entity-schema
  "Returns the DataScript schema for an entity."
  [entity]
  (reduce (fn [schema [attr-name attr-opts]]
            (let [aschema (attr-schema attr-opts)]
              (cond-> schema
                (not (empty? aschema))
                (assoc attr-name aschema))))
          {}
          (es/entity-schema entity)))

(defn merge-attr-schema
  "\"Merges\" two schemas for an attribute with the same name
   by throwing an exception if they are different and the
   first is not nil, and otherwise picking the second."
  [[attr-name prev-schema] [_ next-schema]]
  (if (nil? prev-schema)
    next-schema
    (if (= prev-schema next-schema)
      next-schema
      (let [err-msg (str "Conflicting schemas for attribute \""
                         attr-name "\": "
                         (pr-str prev-schema) " != "
                         (pr-str next-schema))]
        (throw #?(:cljs (js/Error. err-msg)
                  :clj  (Exception. err-msg)))))))

(defn merge-schemas
  "Merge multiple DataScript schemas so that there are no
   conflicting attributes. The default behavior is to throw
   an exception if two schemas for the same attribute are
   different."
  ([schemas]
   (merge-schemas schemas merge-attr-schema))
  ([schemas merge-fn]
   (reduce (fn [ret [attr-name attr-schema]]
             (update ret attr-name
                     (fn [existing-schema]
                       (merge-fn [attr-name existing-schema]
                                 [attr-name attr-schema]))))
           {} (apply concat schemas))))

Add a function to merge DataScript schemas and detect conflicts