(ns icecap.handlers.delay
  (:require [clojure.core.async :refer [timeout]]
            [icecap.handlers.core :refer [defstep]]
            [schema.core :as sc]))

(defstep :delay
  {:amount (sc/both sc/Int (sc/pred #(< 0 % 60)'(< 0 delay 60)))}
  [step]
  (timeout (:amount step)))

(ns icecap.handlers.delay
  (:require [clojure.core.async :refer [timeout]]
            [icecap.handlers.core :refer [defstep]]
            [schema.core :as sc]))

(defstep :delay
  {:amount (sc/conditional #(< 0 % 60) sc/Int)}
  [step]
  (timeout (:amount step)))

Use conditional instead of both

Use conditional instead of both


(ns mathom.toolbar)

(def tool (atom {}))

(defn clean
  []
  (let [prev (.getElementById js/document "mathom_toolbar")]
    (if (not (nil? prev))
      (.remove prev))))

(defn set-content
  [content]
  (set! (.-innerHTML (:bar @tool)) content))

(def content "

Mithril ClojureScript Toolbar

<button id=\"mathom_toolbar_prev\">Previous state</button>
<button id=\"mathom_toolbar_next\">Next state</button>

")

(defn setup
  []
  (let [body (aget (.getElementsByTagName js/document "body") 0)
        tb (.createElement js/document "div")]
    (clean)
    (.setAttribute tb "id" "mathom_toolbar")
    (.appendChild body tb)
    (set-content content)
    (swap! tool #(assoc @tool :bar tb)) ; To get access to generated node
    ))

(defn handle-event
  [eib])

(defn attach-listener
  []
  (.addEventListener (:bar @tool)
                     "click"
                     #(handle-event (aget (.-target %) "id"))))

(ns mathom.toolbar)

(def tool (atom {}))

(defn clean
  []
  (let [prev (.getElementById js/document "mathom_toolbar")]
    (if (not (nil? prev))
      (.remove prev))))

(defn set-content
  [content]
  (set! (.-innerHTML (:bar @tool)) content))

(def content "

Mithril ClojureScript Toolbar

<button id=\"mathom_toolbar_prev\">Previous state</button>
<button id=\"mathom_toolbar_next\">Next state</button>

")

(defn setup
  []
  (let [body (aget (.getElementsByTagName js/document "body") 0)
        tb (.createElement js/document "div")]
    (clean)
    (.setAttribute tb "id" "mathom_toolbar")
    (.appendChild body tb)
    (set-content content)
    (swap! tool #(assoc @tool :bar tb)))) ; To get access to generated node

(defn handle-event
  [eib])

(defn attach-listener
  []
  (.addEventListener (:bar @tool)
                     "click"
                     #(handle-event (aget (.-target %) "id"))))

(defn d-to-s
  "Returns stringified version
  of given map in HTML/XML
  attribute style"
  [d]
  (clojure.string/join " "
                       (for [[k v] d]
                         (str (name k) "=\"" v "\""))))

(defn h
  "Returns a string resembling
  HTML tag, attributes and children"
  [tag attrs children]
  (str "<" tag
       (if (not(empty? attrs)) (str " " (d-to-s attrs))) ">"
       (if (not(empty? children)) (clojure.string/join " " children))
       "</" tag ">"))

Add simple Cljs to HTML helpers

Add simple Cljs to HTML helpers


;; Copyright 2008-2014 Red Hat, Inc, and individual contributors.
;;
;; This is free software; you can redistribute it and/or modify it
;; under the terms of the GNU Lesser General Public License as
;; published by the Free Software Foundation; either version 2.1 of
;; the License, or (at your option) any later version.
;;
;; This software is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this software; if not, write to the Free
;; Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
;; 02110-1301 USA, or see the FSF site: http://www.fsf.org.

(ns no-clojure-jar.tests
  (:use clojure.test))

(deftest bundled-clojure-version
  (is (= "1.5.1" (clojure-version))))

;; Copyright 2008-2014 Red Hat, Inc, and individual contributors.
;;
;; This is free software; you can redistribute it and/or modify it
;; under the terms of the GNU Lesser General Public License as
;; published by the Free Software Foundation; either version 2.1 of
;; the License, or (at your option) any later version.
;;
;; This software is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this software; if not, write to the Free
;; Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
;; 02110-1301 USA, or see the FSF site: http://www.fsf.org.

(ns no-clojure-jar.tests
  (:use clojure.test))

(deftest bundled-clojure-version
  (is (= "1.6.0" (clojure-version))))

Test for the correct clojure version.

Test for the correct clojure version.


(ns webdev.core
  (:use [org.httpkit.server :only [run-server]])
  (:require [webdev.item.migration :as migration]
            [webdev.item.routes :refer [item-routes]]
            [webdev.common.routes :refer [common-routes]]
            [webdev.common.middleware :refer [wrap-db
                                              wrap-simulated-methods]])
  (:require [ring.middleware.reload :refer [wrap-reload]]
            [ring.middleware.params :refer [wrap-params]]
            [ring.middleware.resource :refer [wrap-resource]]
            [ring.middleware.file-info :refer [wrap-file-info]]
            [compojure.core :refer [routes]]
            [environ.core :refer [env]]))

(def db (env :database-url))

(def app
  (wrap-file-info
    (wrap-resource
      (wrap-db
        (wrap-params
          (wrap-simulated-methods (routes item-routes common-routes))))
      "static")))

(defn -main [port]
  (migration/create-table db)
  (run-server app {:port (Integer. port)}))

(defn -dev-main [port]
  (migration/create-table db)
  (run-server (wrap-reload #'app) {:port (Integer. port)}))

(ns webdev.core
  (:require [webdev.item.migration :as migration]
            [webdev.item.routes :refer [item-routes]]
            [webdev.common.routes :refer [common-routes]]
            [webdev.common.middleware :refer [wrap-db
                                              wrap-simulated-methods]])
  (:require [org.httpkit.server :refer [run-server]]
            [ring.middleware.reload :refer [wrap-reload]]
            [ring.middleware.params :refer [wrap-params]]
            [ring.middleware.resource :refer [wrap-resource]]
            [ring.middleware.file-info :refer [wrap-file-info]]
            [compojure.core :refer [routes]]
            [environ.core :refer [env]]))

(def db (env :database-url))

(def app-routes
  (routes
    item-routes
    common-routes))

(def app
  (-> app-routes
      (wrap-simulated-methods)
      (wrap-params)
      (wrap-db)
      (wrap-resource "static")
      (wrap-file-info)))

(defn -main [port]
  (migration/create-table db)
  (run-server app {:port (Integer. port)}))

(defn -dev-main [port]
  (migration/create-table db)
  (run-server (wrap-reload #'app) {:port (Integer. port)}))

Use threading macro for app setup.

Use threading macro for app setup.


(defproject {{ project_name }} "0.0.1-SNAPSHOT"
  :source-paths ["topologies"]
  :resource-paths ["_resources"]
  :aot :all
  :target-path "_build"
  :min-lein-version "2.0.0"
  :dependencies [[org.apache.storm/storm-core "0.9.1-incubating"]
                 [com.parsely/streamparse "0.0.1-SNAPSHOT"]
                 [org.clojure/clojure "1.5.1"]
                 [org.clojure/data.json "0.2.4"]
                 [org.clojure/tools.cli "0.3.1"]
                 ]
  )

(defproject {{ project_name }} "0.0.1-SNAPSHOT"
  :source-paths ["topologies"]
  :resource-paths ["_resources"]
  :aot :all
  :target-path "_build"
  :min-lein-version "2.0.0"
  :jvm-opts ["-client"]
  :dependencies [[org.apache.storm/storm-core "0.9.1-incubating"]
                 [com.parsely/streamparse "0.0.1-SNAPSHOT"]
                 [org.clojure/clojure "1.5.1"]
                 [org.clojure/data.json "0.2.4"]
                 [org.clojure/tools.cli "0.3.1"]]
  )

Add "-client" to JVM opts for quickstart projects.


(ns little-clojurer.chapter5
  (:require [little-clojurer.chapter4 :refer :all]))

(defn rember*
  [a l]
  nil)

(defn insertR*
  [new old l]
  nil)

(defn occur*
  [a l]
  nil)

(defn subst*
  [new old l]
  nil)

(defn insertL*
  [new old l]
  nil)

(defn member*
  [a l]
  nil)

(defn leftmost
  [l]
  nil)

(ns little-clojurer.chapter5
  (:require [little-clojurer.chapter4 :refer :all]))

(defn rember*
  "find all occurrances of a in l deeply recursively and remove them"
  [a l]
  nil)

(defn insertR*
  "find all occurrances of old in l deeply recursively and append new to the right of the occurrances"
  [new old l]
  nil)

(defn occur*
  "count the number of times a occurs in l deeply recursively"
  [a l]
  nil)

(defn subst*
  "find all occurrances of a in l deeply recursively and replace them with new"
  [new old l]
  nil)

(defn member*
  "check if a occurs in l deeply recursively"
  [a l]
  nil)

(defn leftmost
  "finds the leftmost atom in l deeply recursively. l cannot be empty and cannot contain empty lists."
  [l]
  nil)

Add docstrings to chapter 5 stubs.

Add docstrings to chapter 5 stubs.


(ns reabledit.components
  (:require [reabledit.util :as util]))

(defn data-table-cell-input
  [columns data nth-row nth-col state]
  (let [k (:key (nth columns nth-col))]
    [:input {:type "text"
             :auto-focus true
             :value (get (get-in @state [:edit :updated]) k)
             :on-change #(swap! state
                                assoc-in
                                [:edit :updated k]
                                (-> % .-target .-value))}]))

(defn data-table-cell
  [columns data v nth-row nth-col state]
  (let [selected? (= (:selected @state) [nth-row nth-col])
        edit? (:edit @state)]
    [:td {:class (if selected? "selected")
          :on-click #(util/set-selected! state nth-row nth-col)}
     (if (and selected? edit?)
       [data-table-cell-input columns data nth-row nth-col state]
       [:span v])]))

(defn data-table-row
  [columns data row-data nth-row state]
  [:tr
   ;; TODO: run map-indexed to columns only once
   (for [[nth-col {:keys [key value]}] (map-indexed vector columns)]
     ^{:key nth-col}
     [data-table-cell columns data (get row-data key) nth-row nth-col state])])

(defn data-table-headers
  [columns]
  [:thead
   [:tr
    (for [{:keys [key value]} columns]
      ^{:key key} [:th value])]])

(ns reabledit.components
  (:require [reabledit.util :as util]
            [reagent.core :as reagent]))

(defn data-table-cell-input
  [cursor]
  [:input {:type "text"
           :auto-focus true
           :value @cursor
           :on-change #(reset! cursor (-> % .-target .-value))}])

(defn data-table-cell
  [columns data v nth-row nth-col state]
  (let [selected? (= (:selected @state) [nth-row nth-col])
        edit? (:edit @state)
        key (:key (nth columns nth-col))
        cursor (reagent/cursor state [:edit :updated key])]
    [:td {:class (if selected? "selected")
          :on-click #(util/set-selected! state nth-row nth-col)}
     (if (and selected? edit?)
       [data-table-cell-input cursor]
       [:span v])]))

(defn data-table-row
  [columns data row-data nth-row state]
  [:tr
   ;; TODO: run map-indexed to columns only once
   (for [[nth-col {:keys [key value]}] (map-indexed vector columns)]
     ^{:key nth-col}
     [data-table-cell columns data (get row-data key) nth-row nth-col state])])

(defn data-table-headers
  [columns]
  [:thead
   [:tr
    (for [{:keys [key value]} columns]
      ^{:key key} [:th value])]])

Simplify arguments the editing component gets from the cell component


(ns interop.Sample
  (:gen-class))

(defn -main []
  (throw (UnsupportedOperationException. "Not yet implemented")))

(ns interop.Sample
  (:gen-class))

(defn -main [& _]
  (throw (UnsupportedOperationException. "Not yet implemented")))

Fix arity of interop call

Fix arity of interop call


(ns leiningen.pallet-release
  "Pallet release commands to support the PalletOps release workflow."
  (:require
   [leiningen.pallet-release.core :refer [fail]]
   [leiningen.pallet-release.release :as release]
   [leiningen.pallet-release.travis :as travis]))

(defn pallet-release
  "Pallet release commands to support the PalletOps release workflow."
  ^{:subtasks
    [#'release/init #'release/start #'release/finish
     #'travis/push #'release/publish]}
  [project & [cmd & args]]
  (case cmd
    "init" (release/init project args)
    "start" (release/start project args)
    "finish" (release/finish project args)
    "push" (travis/push project args)
    "publish" (release/publish project args)
    (fail "Known cmds are init, start, finish, and push")))

(ns leiningen.pallet-release
  "Pallet release commands to support the PalletOps release workflow."
  (:require
   [leiningen.pallet-release.core :refer [fail]]
   [leiningen.pallet-release.release :as release]
   [leiningen.pallet-release.travis :as travis]))

(defn pallet-release
  "Pallet release commands to support the PalletOps release workflow."
  ^{:subtasks
    [#'release/init #'release/start #'release/finish
     #'travis/push #'release/publish]}
  [project & [cmd & args]]
  (case cmd
    "init" (release/init project args)
    "start" (release/start project args)
    "finish" (release/finish project args)
    "push" (travis/push project args)
    "publish" (release/publish project args)
    (fail "Known cmds are init, start, finish, and publish.")))

Fix list of known commands in help message


(ns onyx.types)

<<<<<<< HEAD
(defrecord Message [id payload])

(defrecord Leaf [message id acker-id completion-id ack-val hash-group route])
=======
(defrecord Leaf [message id acker-id completion-id ack-val ack-vals route routes hash-group])

(defn leaf
  ([message]
     (->Leaf message nil nil nil nil nil nil nil nil)))
>>>>>>> ba78b0e... Read vpeer-id separately to rest of buffer so that

(defrecord Route [flow exclusions post-transformation action])

(defrecord Ack [id completion-id ack-val timestamp])

(defrecord Results [tree acks segments])

(defrecord Result [root leaves])

(defrecord Link [link timestamp])

(ns onyx.types)

(defrecord Leaf [message id acker-id completion-id ack-val hash-group route])

(defrecord Route [flow exclusions post-transformation action])

(defrecord Ack [id completion-id ack-val timestamp])

(defrecord Results [tree acks segments])

(defrecord Result [root leaves])

(defrecord Link [link timestamp])

Fix merge issue in last commit.

Fix merge issue in last commit.


(ns icecap.schema-test
  (:require [icecap.schema :refer :all]
            [clojure.test :refer :all]
            [schema.core :as s]))

(def simple-http-request {:target "http://example.test"})
(def simple-https-request {:target "https://example.test"})
(def simple-ftp-request {:target "ftp://example.test"})

(deftest RequestSpecTests
  (testing "Correct request specs validate"
    (are [example] (s/validate RequestSpec example)
         simple-http-request
         simple-https-request
         #{simple-http-request simple-https-request}))
  (testing "Request specs with unknown/unsupported schemes don't validate"
    (are [example] (thrown? Throwable (s/validate RequestSpec example))
         simple-ftp-request)))

(ns icecap.schema-test
  (:require [icecap.schema :refer :all]
            [clojure.test :refer :all]
            [schema.core :as s]))

(def simple-http-request {:target "http://example.test"})
(def simple-https-request {:target "https://example.test"})
(def simple-ftp-request {:target "ftp://example.test"})

(deftest RequestSpecTests
  (testing "Correct request specs validate"
    (are [example] (s/validate RequestSpec example)
         simple-http-request
         simple-https-request
         #{simple-http-request simple-https-request}))
  (testing "Request specs with unknown/unsupported schemes don't validate"
    (are [example reason] (= (s/check RequestSpec example) reason)
         simple-ftp-request {:target (not ("supported-scheme?" "ftp://example.test"))})))

Test allegedly better error reporting

Test allegedly better error reporting

Refs #1.


(ns lcmap.clownfish.system
  (:require [again.core :as again]
            [clojure.tools.logging :as log]
            ;; requiring this ensures the server component will start
            [lcmap.clownfish.server :as server]
            [lcmap.clownfish.setup.cassandra]
            [lcmap.clownfish.setup.rabbitmq]
            [mount.core :refer [defstate] :as mount]))

(defstate hook
  :start (do
           (log/debugf "registering shutdown handler")
           (.addShutdownHook (Runtime/getRuntime)
                             (Thread. #(mount/stop) "shutdown-handler"))))

(def default-retry-strategy
  (again/max-retries 10 (again/constant-strategy 5000)))

(defn start
  ([environment]
   (start default-retry-strategy))

  ([environment startup-retry-strategy]
   (again/with-retries startup-retry-strategy
     (do (log/info "Stopping mount components")
         (mount/stop)
         (log/info "Starting mount components...")
         ;; insulation to make sure these states do not get accidentally
         ;; started
         (mount/start-without #'lcmap.clownfish.setup.cassandra/setup
                              #'lcmap.clownfish.setup.cassandra/teardown
                              #'lcmap.clownfish.setup.rabbitmq/setup
                              (mount/with-args {:environment environment}))))))
(defn stop []
  (mount/stop))

(ns lcmap.clownfish.system
  (:require [again.core :as again]
            [clojure.tools.logging :as log]
            ;; requiring this ensures the server component will start
            [lcmap.clownfish.server :as server]
            [lcmap.clownfish.setup.cassandra]
            [lcmap.clownfish.setup.rabbitmq]
            [mount.core :refer [defstate] :as mount]))

(defstate hook
  :start (do
           (log/debugf "registering shutdown handler")
           (.addShutdownHook (Runtime/getRuntime)
                             (Thread. #(mount/stop) "shutdown-handler"))))

(def default-retry-strategy
  (again/max-retries 10 (again/constant-strategy 5000)))

(defn start
  ([environment]
   (start environment default-retry-strategy))

  ([environment startup-retry-strategy]
   (again/with-retries startup-retry-strategy
     (do (log/info "Stopping mount components")
         (mount/stop)
         (log/info "Starting mount components...")
         ;; insulation to make sure these states do not get accidentally
         ;; started
         (mount/start-without #'lcmap.clownfish.setup.cassandra/setup
                              #'lcmap.clownfish.setup.cassandra/teardown
                              #'lcmap.clownfish.setup.rabbitmq/setup
                              (mount/with-args {:environment environment}))))))
(defn stop []
  (mount/stop))

Fix stack overflow during startup

Fix stack overflow during startup


(ns de.otto.tesla.example.example-system
  (:require [de.otto.tesla.system :as system]
            [de.otto.tesla.example.calculating :as calculating]
            [de.otto.tesla.example.example-page :as example-page]
            [com.stuartsierra.component :as c])
  (:gen-class))

(defn example-calculation-function [input]
  (.toUpperCase input))

(defn example-system [runtime-config]
  (-> (system/empty-system runtime-config)
      (assoc :calculator
             (c/using (calculating/new-calculator example-calculation-function) [:metering :app-status]))
      (assoc :example-page
             (c/using (example-page/new-example-page) [:routes :calculator :app-status]))))

(defn -main
  "starts up the production system."
  [& args]
  (system/start-system (example-system{})))

(ns de.otto.tesla.example.example-system
  (:require [de.otto.tesla.system :as system]
            [de.otto.tesla.example.calculating :as calculating]
            [de.otto.tesla.example.example-page :as example-page]
            [com.stuartsierra.component :as c])
  (:gen-class))

(defn example-calculation-function [input]
  (.toUpperCase input))

(defn example-system [runtime-config]
  (-> (system/empty-system runtime-config)
      (assoc :calculator
             (c/using (calculating/new-calculator example-calculation-function) [:metering :app-status]))
      (assoc :example-page
             (c/using (example-page/new-example-page) [:routes :calculator :app-status]))
      (c/system-using {:server [:example-page]})))

(defn -main
  "starts up the production system."
  [& args]
  (system/start-system (example-system{})))

Example: Make sure page component is started before server

In the system definition from the example code, an explicit dependency
from the :server component to the :example-page component is introduced
to make sure the routes for example-page are registered before the
server is started.


(ns uxbox.locales
  "A i18n foundation."
  (:require [hodgepodge.core :refer [local-storage]]
            [cuerdas.core :as str]
            [uxbox.locales.en :as locales-en]))

(defonce +locales+
  {:en locales-en/+locales+})

(defonce +locale+
  (get local-storage ::locale :en))

(deftype C [val]
  IDeref
  (-deref [o] val))

(defn c
  [x]
  (C. x))

(defn ^boolean c?
  [r]
  (instance? C r))

(defn tr
  "Translate the string."
  ([t]
   (let [default (name t)
         value (get-in +locales+ [+locale+ t] default)]
     (if (vector? value)
       (or (second value) default)
       value)))
  ([t & args]
   (let [value (get-in +locales+ [+locale+ t] (name t))
         plural (first (filter c? args))
         args (mapv #(if (c? %) @% %) args)
         value (if vector?
                 (if (= @plural 1) (first value) (second value))
                 value)]
     (apply str/format value args))))

(ns uxbox.locales
  "A i18n foundation."
  (:require [hodgepodge.core :refer [local-storage]]
            [cuerdas.core :as str]
            [uxbox.locales.en :as locales-en]))

(defonce +locales+
  {:en locales-en/+locales+})

(defonce +locale+
  (get local-storage ::locale :en))

(deftype C [val]
  IDeref
  (-deref [o] val))

(defn c
  [x]
  (C. x))

(defn ^boolean c?
  [r]
  (instance? C r))

(defn tr
  "Translate the string."
  ([t]
   (let [default (name t)
         value (get-in +locales+ [+locale+ t] default)]
     (if (vector? value)
       (or (second value) default)
       value)))
  ([t & args]
   (let [value (get-in +locales+ [+locale+ t] (name t))
         plural (first (filter c? args))
         args (mapv #(if (c? %) @% %) args)
         value (cond
                 (and (vector? value)
                      (= 3 (count value)))
                 (nth value (min 2 @plural))

                 (vector? value)
                 (if (= @plural 1) (first value) (second value))

                 :else
                 value)]
     (apply str/format value args))))

Support 0, 1 or more in plural translations


(defproject shurly "1.0.0-SNAPSHOT"
  :description "FIXME: write description"
  :url "http://shurly.herokuapp.com"
  :license {:name "FIXME: choose"
            :url "http://example.com/FIXME"}
  :dependencies [[org.clojure/clojure "1.6.0"]
                 [compojure "1.1.8"]
                 [ring/ring-jetty-adapter "1.2.2"]
                 [ring/ring-devel "1.2.2"]
                 [ring-basic-authentication "1.0.5"]
                 [environ "0.5.0"]
                 [com.cemerick/drawbridge "0.0.6"]]
  :min-lein-version "2.0.0"
  :plugins [[environ/environ.lein "0.2.1"]]
  :hooks [environ.leiningen.hooks]
  :uberjar-name "shurly-standalone.jar"
  :profiles {:production {:env {:production true}}})

(defproject shurly "1.0.0-SNAPSHOT"
  :description "A URL shortener"
  :url "http://shurly.herokuapp.com"
  :dependencies [[org.clojure/clojure "1.6.0"]
                 [compojure "1.1.8"]
                 [ring/ring-jetty-adapter "1.2.2"]
                 [ring/ring-devel "1.2.2"]
                 [environ "0.5.0"]]
  :min-lein-version "2.0.0"
  :plugins [[environ/environ.lein "0.2.1"]]
  :hooks [environ.leiningen.hooks]
  :uberjar-name "shurly-standalone.jar"
  :ring {:handler shurly.web/app}
  :profiles {:production {:env {:production true}}})

Remove useless stuff and set ring handler


(defproject nasa-cmr/cmr-system-trace-lib "0.1.0-SNAPSHOT"
  :description "Provides library functions for tracing requests throughout the CMR system. Built on
               Twitter Zipkin and clj-zipkin."
  :url "***REMOVED***projects/CMR/repos/cmr-system-trace-lib/browse"
  :dependencies [[org.clojure/clojure "1.6.0"]
                 [nasa-cmr/cmr-common-lib "0.1.1-SNAPSHOT"]

                ;; clj-zipkin macros don't work very well. It's included mostly for some utility
                ;; functions, and the thrift handling.
                [clj-zipkin "0.1.3" :exclusions [ch.qos.logback/logback-classic
                                                 log4j
                                                 org.slf4j/slf4j-log4j12]]
                ;; Turn off the logging noise
                [com.dadrox/quiet-slf4j "0.1"]
                [clj-time "0.7.0"]]

  :plugins [[lein-test-out "0.3.1"]]

  :profiles
  {:dev {:dependencies [[org.clojure/tools.namespace "0.2.4"]
                        [org.clojars.gjahad/debug-repl "0.3.3"]]
         :source-paths ["src" "dev" "test"]}})

(defproject nasa-cmr/cmr-system-trace-lib "0.1.0-SNAPSHOT"
  :description "Provides library functions for tracing requests throughout the CMR system. Built on
               Twitter Zipkin and clj-zipkin."
  :url "***REMOVED***projects/CMR/repos/cmr-system-trace-lib/browse"
  :dependencies [[org.clojure/clojure "1.6.0"]
                 [nasa-cmr/cmr-common-lib "0.1.1-SNAPSHOT"]

                ;; clj-zipkin macros don't work very well. It's included mostly for some utility
                ;; functions, and the thrift handling.
                [clj-zipkin "0.1.3" :exclusions [ch.qos.logback/logback-classic
                                                 log4j
                                                 org.slf4j/slf4j-log4j12]]
                ;; Turn off the logging noise
                [com.dadrox/quiet-slf4j "0.1"]]

  :plugins [[lein-test-out "0.3.1"]]

  :profiles
  {:dev {:dependencies [[org.clojure/tools.namespace "0.2.4"]
                        [org.clojars.gjahad/debug-repl "0.3.3"]]
         :source-paths ["src" "dev" "test"]}})

Move clj-time dependency to cmr-common-lib


(defproject io.aviso/twixt "0.1.5"
  :description "An extensible asset pipeline for Clojure web applications"
  :url "https://github.com/AvisoNovate/twixt"
  :license {:name "Apache Sofware Licencse 2.0"
            :url  "http://www.apache.org/licenses/LICENSE-2.0.html"}
  :dependencies [[org.clojure/clojure "1.5.1"]
                 [org.clojure/tools.logging "0.2.6"]
                 [ring/ring-core "1.2.0"]
                 [org.mozilla/rhino "1.7R4"]
                 [com.github.sommeri/less4j "1.1.2"]
                 [de.neuland/jade4j "0.3.15"]
                 [io.aviso/pretty "0.1.5"]
                 [hiccup "1.0.4"]]
  :repositories [["jade4j" "https://raw.github.com/neuland/jade4j/master/releases"]]
  :codox {:src-dir-uri               "https://github.com/AvisoNovate/twixt/blob/master/"
          :src-linenum-anchor-prefix "L"}
  :profiles {:dev {:dependencies [[log4j "1.2.17"]
                                  [ring/ring-jetty-adapter "1.2.0"]]}})

(defproject io.aviso/twixt "0.1.5"
  :description "An extensible asset pipeline for Clojure web applications"
  :url "https://github.com/AvisoNovate/twixt"
  :license {:name "Apache Sofware Licencse 2.0"
            :url  "http://www.apache.org/licenses/LICENSE-2.0.html"}
  :dependencies [[org.clojure/clojure "1.5.1"]
                 [org.clojure/tools.logging "0.2.6"]
                 [ring/ring-core "1.2.0"]
                 [org.mozilla/rhino "1.7R4"]
                 [com.github.sommeri/less4j "1.1.2"]
                 [de.neuland/jade4j "0.3.15"]
                 [io.aviso/pretty "0.1.6"]
                 [hiccup "1.0.4"]]
  :repositories [["jade4j" "https://raw.github.com/neuland/jade4j/master/releases"]]
  :codox {:src-dir-uri               "https://github.com/AvisoNovate/twixt/blob/master/"
          :src-linenum-anchor-prefix "L"}
  :profiles {:dev {:dependencies [[log4j "1.2.17"]
                                  [ring/ring-jetty-adapter "1.2.0"]]}})

Update pretty dependency to 0.1.6

Update pretty dependency to 0.1.6


(ns leiningen.clean-tokyo
  (:use [clojure.java.shell :only [sh]]
        [clojure.java.io :only [file]]))

(defn clean [srcdir]
  (when (.exists (file srcdir "Makefile"))
    (println (:out (sh "make" "distclean" :dir (file srcdir))))))

(defn clean-tokyo []
  (clean (file "src/tokyocabinet"))
  (clean (file "src/tokyocabinet-java")))

(ns leiningen.clean-tokyo
  (:use [clojure.java.io :only [file]])
  (:require [conch.core :as sh]))

(defn clean [srcdir]
  (when (.exists (file srcdir "Makefile"))
    (sh/stream-to-out (sh/proc "make" "distclean" :dir (file srcdir)) :out)))

(defn clean-tokyo []
  (clean (file "src/tokyocabinet"))
  (clean (file "src/tokyocabinet-java")))

Make clean-tokyo task also use conch.

Make clean-tokyo task also use conch.


(ns jest.arithmetic-test
  (:require [clojure.test :refer :all]
            [jest.utils :refer :all]
            :verbose))

(deftest product-test-1
  (test-code
   "val x = 1 * 2;"
   ["(def x (* 1 2))"]))

(deftest product-test-2
  (test-code
   "val x = 1 * 2 * 3;"
   ["(def x (* (* 1 2) 3))"]))

(deftest quotent-test-1
  (test-code
   "val x = 1 / 2;"
   ["(def x (/ 1 2))"]))

(deftest quotent-test-2
  (test-code
   "val x = 1 / 2 / 3;"
   ["(def x (/ (/ 1 2) 3))"]))

(deftest multiply-divide-test
  (test-code
   "val x = 1 * 2 / 3;"
   ["(def x (/ (* 1 2) 3))"]))

(ns jest.arithmetic-test
  (:require [clojure.test :refer :all]
            [jest.utils :refer :all]
            :verbose))

(deftest sum-test-1
  (test-code
   "val x = 1 + 2;"
   ["(def x (+ 1 2))"]))

(deftest sum-test-2
  (test-code
   "val x = 1 + 2 + 3;"
   ["(def x (+ (+ 1 2) 3))"]))

(deftest product-test-1
  (test-code
   "val x = 1 * 2;"
   ["(def x (* 1 2))"]))

(deftest product-test-2
  (test-code
   "val x = 1 * 2 * 3;"
   ["(def x (* (* 1 2) 3))"]))

(deftest quotent-test-1
  (test-code
   "val x = 1 / 2;"
   ["(def x (/ 1 2))"]))

(deftest quotent-test-2
  (test-code
   "val x = 1 / 2 / 3;"
   ["(def x (/ (/ 1 2) 3))"]))

(deftest multiply-divide-test
  (test-code
   "val x = 1 * 2 / 3;"
   ["(def x (/ (* 1 2) 3))"]))

Add sum and diff tests

Add sum and diff tests


(ns buddy.crypto.keys
  (:import java.security.Key))

(defn make-secret-key
  "Generates a Key instance from given raw string key."
  [^String skey]
  (let [rawkey (.getBytes skey "UTF-8")]
    (proxy [Key] []
      (getFormat [] nil)
      (getEncoded [] rawkey)
      (toString [] skey))))

(ns buddy.crypto.keys
  (:require [buddy.crypto.core :refer [str->bytes]])
  (:import java.security.Key))

(defn make-secret-key
  "Generates a Key instance from given raw string key."
  [^String skey]
  (let [rawkey (str->bytes skey)]
    (proxy [Key] []
      (getFormat [] nil)
      (getEncoded [] rawkey)
      (toString [] skey))))

Use byddy.crypto utils function for get a byte array from string on make-secret-key function.


(ns reabledit.cells.read-only
  (:require [reabledit.util :as util]))

(defn read-only-cell
  [{:keys [row-data column-key]}]
  (let [v (get row-data column-key)]
    [:div.reabledit-read-only-cell
     {:title v}
     [:input.reabledit-read-only-cell__input.reabledit-focused
      {:type "text"
       :value ""
       :on-key-down #(if (= (.-keyCode %) 13) (.stopPropagation %))
       :on-copy #(util/set-clipboard-data % v)}]
     [:span.reabledit-read-only-cell__view v]]))

(ns reabledit.cells.read-only
  (:require [reabledit.util :as util]))

(defn read-only-cell
  [{:keys [row-data column-key]}]
  (let [v (get row-data column-key)]
    [:div.reabledit-read-only-cell
     {:title v}
     [:input.reabledit-read-only-cell__input.reabledit-focused
      {:type "text"
       :value ""
       :on-key-down #(if (= (.-keyCode %) 13) (.stopPropagation %))
       :on-copy #(util/set-clipboard-data % v)
       :on-cut #(util/set-clipboard-data % v)}]
     [:span.reabledit-read-only-cell__view v]]))

Add cut handler to read-only cell

Add cut handler to read-only cell


 (ns silly-image-store.handler
  (:require [silly-image-store.store :as store]
            [environ.core :refer [env]]
            [compojure.core :refer :all]
            [ring.middleware.json :refer :all]
            [compojure.handler :as handler]
            [compojure.route :as route]))

(def images-dir
  (env :base-store-dir))

(defn image-not-found [image]
  (route/not-found (str "No image '" image "' found")))

(defn serve-image [image]
  (let [image-file (store/load-image images-dir image)]
    (or image-file (image-not-found image))))

(defroutes app-routes
  (GET "/blah" [] {:status 200 :body {:def [123 456 789]}})
  (GET "/images/:image" [image] (serve-image image))
  (route/resources "/")
  (route/not-found "Not Found"))

(def app
  (-> (handler/site app-routes)
      (wrap-json-response)))

 (ns silly-image-store.handler
  (:require [silly-image-store.store :as store]
            [environ.core :refer [env]]
            [compojure.core :refer :all]
            [ring.middleware.json :refer :all]
            [compojure.handler :as handler]
            [compojure.route :as route]))

(def images-dir
  (env :base-store-dir))

(defn image-not-found [image]
  (route/not-found (str "No image '" image "' found")))

(defn serve-image [image]
  (let [image-file (store/load-image images-dir image)]
    (or image-file (image-not-found image))))

(defroutes app-routes
  (GET "/images" [] "nothing")
  (GET "/images/:image" [image] (serve-image image))
  (route/resources "/")
  (route/not-found "Not Found"))

(def app
  (-> (handler/site app-routes)
      (wrap-json-response)))

Replace fake json route by /images route


(ns desdemona.query
  (:require [clojure.core.logic :as l]))

(defn ^:private gen-query
  [n-answers query events]
  `(l/run ~n-answers [results#]
     (l/fresh [~'x]
       (l/membero ~'x results#)
       (l/everyg #(l/membero % results#) ~events)
       ~query)))

(defn run-query
  ([query events]
   (run-query 1 query events))
  ([n-answers query events]
   (eval (gen-query n-answers query events))))

(ns desdemona.query
  (:require [clojure.core.logic :as l]))

(defn ^:private gen-query
  [n-answers query events]
  `(l/run ~n-answers [results#]
     (l/fresh [~'x]
       (l/everyg #(l/membero % results#) ~events)
       (l/== [~'x] results#)
       ~query)))

(defn run-query
  ([query events]
   (run-query 1 query events))
  ([n-answers query events]
   (eval (gen-query n-answers query events))))

Use unification to constrain results

Use unification to constrain results


(ns clojuresque.tasks.repl
  (:require
    [clojuresque.cli :as cli]
    [clojuresque.util :as util]
    [clojure.tools.nrepl.server :as repl]))

(def barrier (promise))
(def server nil)

(cli/deftask start-repl
  "Start a nrepl server on the given port. An optional handler
  may be given as fully-qualified symbol. The repl server may
  be stopped via clojuresque.tasks.repl/stop-server."
  [[port     p "server port"]
   [handler  h "handler function" nil]]
  (let [p (Long/parseLong port)
        h (if handler
            (let [custom-handler (util/resolve-required handler)]
              (when-not custom-handler
                (throw (Exception. (str "Unknown handler Var: " handler))))
              (custom-handler))
            (repl/default-handler))
        s (repl/start-server :port p :handler h)]
    (println "Repl started on port" port)
    (alter-var-root #'server (constantly s)))
  @barrier)

(defn stop-repl
  []
  (when server
    (repl/stop-server server)
    (deliver barrier true)))

(ns clojuresque.tasks.repl
  (:require
    [clojuresque.cli :as cli]
    [clojuresque.util :as util]
    [clojure.tools.nrepl.server :as repl]))

(def barrier (promise))
(def server nil)

(cli/deftask start-repl
  "Start a nrepl server on the given port. An optional handler
  may be given as fully-qualified symbol. The repl server may
  be stopped via clojuresque.tasks.repl/stop-server."
  [[port     p "server port"]
   [handler  h "handler function" nil]]
  (let [p (Long/parseLong port)
        h (if handler
            (let [custom-handler (binding [*warn-on-reflection* *warn-on-reflection*]
                                   (util/resolve-required handler))]
              (when-not custom-handler
                (throw (Exception. (str "Unknown handler Var: " handler))))
              (custom-handler))
            (repl/default-handler))
        s (repl/start-server :port p :handler h)]
    (println "Repl started on port" port)
    (alter-var-root #'server (constantly s)))
  @barrier)

(defn stop-repl
  []
  (when server
    (repl/stop-server server)
    (deliver barrier true)))

Add workaround to fix ClojureScript

Add workaround to fix ClojureScript


(ns cglossa.core
  (:require [reagent.core :as reagent :refer [atom]]
            [plumbing.core :as plumbing :refer [map-vals]]
            [cglossa.centre :as centre]))

(def state {:showing-results false})
; avoid "not resolved" messages in Cursive
(declare getElementById)

(def data {:categories ["ku" "hest"]
           :users      ["per" "kari"]})

(defonce app-state (into {} (map-vals atom state)))
(defonce app-data (into {} (map-vals atom data)))

(defn header []
  [:div.navbar.navbar-fixed-top [:div.navbar-inner [:div.container [:span.brand "Glossa"]]]])

(defn app [s d]
  [:div
   [header]
   [:div.container-fluid
    [centre/top s d]
    [centre/bottom s d]]
   [:div.app-footer
    [:img.textlab-logo {:src "img/tekstlab.gif"}]]])

(defn ^:export main []
  (reagent/render-component
    (fn []
      [app app-state app-data])
    (. js/document (getElementById "app"))))

(ns cglossa.core
  (:require [reagent.core :as reagent :refer [atom]]
            [plumbing.core :as plumbing :refer [map-vals]]
            [cglossa.centre :as centre]))

; avoid "not resolved" messages in Cursive
(declare getElementById)

(def state {:showing-results? false
            :showing-sidebar? false})

(def data {:corpus {:name "LBK"
                    :search-engine :cwb-speech}})

(defonce app-state (into {} (map-vals atom state)))
(defonce app-data (into {} (map-vals atom data)))

(defn header []
  [:div.navbar.navbar-fixed-top [:div.navbar-inner [:div.container [:span.brand "Glossa"]]]])

(defn app [s d]
  [:div
   [header]
   [:div.container-fluid
    [centre/top s d]
    [centre/bottom s d]]
   [:div.app-footer
    [:img.textlab-logo {:src "img/tekstlab.gif"}]]])

(defn ^:export main []
  (reagent/render-component
    (fn []
      [app app-state app-data])
    (. js/document (getElementById "app"))))

Use some more authentic test data

Use some more authentic test data


(ns comic-reader.scrape
  (:require [clojure.string :as s]
            [net.cgrand.enlive-html :as html])
  (:import java.net.URL))

(defn fetch-feed [url]
  (html/xml-resource (java.net.URL. url)))

(defn fetch-url [url]
  (html/html-resource (java.net.URL. url)))

(defn fetch-list [{:keys [url selector normalize]}]
  (when (every? (complement nil?) [url selector normalize])
    (map normalize (html/select (fetch-url url) selector))))

(defn enlive->hiccup [{:keys [tag attrs content]}]
  (if (nil? content)
    [tag attrs]
    [tag attrs content]))

(defn fetch-image-tag [url]
  (-> (fetch-url url)
      (html/select [:div#imgholder :a :img#img])
      first
      enlive->hiccup))

Add function for getting a hiccup image tag


(ns my-money.routes.upload
  (:require [my-money.op-csv :refer :all]
            [compojure.core :refer [defroutes POST]]
            [ring.util.http-response :as response]))

(defroutes upload-routes
  (POST "/upload" [file]
    (let [data (read-csv (slurp (:tempfile file)))]
      (-> (response/ok (-> data
                           (remove-column-by-name "Arkistointitunnus")))))))

(ns my-money.routes.upload
  (:require [my-money.op-csv :refer :all]
            [compojure.core :refer [defroutes POST]]
            [ring.util.http-response :as response]))

(defroutes upload-routes
  (POST "/upload" [file]
    (let [data (read-csv (slurp (:tempfile file) :encoding "ISO-8859-1"))]
      (-> (response/ok (-> data
                           (remove-column-by-name "Arvopäivä")
                           (remove-column-by-name "Laji")
                           (remove-column-by-name "Arkistointitunnus")))))))

Fix character encodings for the data read from the csv. Remove columns from the response.


(ns theatralia.welcome-page
  (:require [net.cgrand.enlive-html :as html]
            [garden.core :refer [css]]
            [clojure.java.io :as io]))
;;; Credits:
;;;  - https://github.com/cgrand/enlive
;;;  - https://github.com/swannodette/enlive-tutorial/
;;;  - http://clojurewebdev.com/workshop/slides/

(def ^:private main-html (io/resource "templates/around.html"))
(def ^:private welcome-html (io/resource "templates/welcome.html"))

(html/defsnippet welcome-snippet
  welcome-html
  [:body :> html/any-node]
  [] identity)

(html/deftemplate index main-html
  []
  [:title] (html/content "Welcome to Theatralia!")
  [:#main-content] (html/content (welcome-snippet)))

(def css-data [[:html {:font-family "sans-serif"}]
               [:#theatralia {:font-family "fancy"}]
               [:#login {:float "right"}]])

(defn main-css []
  {:status 200
   :headers {"Content-Type" "text/css"}
   :body (css css-data)})

(ns theatralia.welcome-page
  (:require [net.cgrand.enlive-html :as html]
            [garden.core :refer [css]]
            [clojure.java.io :as io]))
;;; Credits:
;;;  - https://github.com/cgrand/enlive
;;;  - https://github.com/swannodette/enlive-tutorial/
;;;  - http://clojurewebdev.com/workshop/slides/

(def ^:private main-html (io/resource "templates/around.html"))
(def ^:private welcome-html (io/resource "templates/welcome.html"))

(html/defsnippet welcome-snippet
  welcome-html
  [:#main]
  [] identity)

(html/defsnippet login-snippet
  welcome-html
  [:#login]
  [] identity)

(html/deftemplate index main-html
  []
  [:title] (html/content "Welcome to Theatralia!")
  [:#main-content] (html/content (welcome-snippet))
  [:#global-tools] (html/content (login-snippet)))

(def css-data [[:html {:font-family "sans-serif"}]
               [:#theatralia {:font-family "fancy"}]
               [:#login {:float "right"}]])

(defn main-css []
  {:status 200
   :headers {"Content-Type" "text/css"}
   :body (css css-data)})

Adjust the deftemplates and defsnippets

Adjust the deftemplates and defsnippets

In bc87d96 I had made an adjustment to the HTML. Change the Enlive code
to take advantage of that. That means putting the login form into the
right column and the main text in the middle.


(ns oc.storage.lib.email
  (:require [amazonica.aws.sqs :as sqs]
            [taoensso.timbre :as timbre]
            [schema.core :as schema]
            [oc.storage.config :as config]
            [oc.storage.resources.common :as common-res]))

(def EmailTrigger
  {:to [schema/Str]
   :subject schema/Str
   :note schema/Str
   :reply-to (schema/maybe schema/Str)
   :org-slug schema/Str
   :origin-url schema/Str
   :entries [common-res/UpdateEntry]})

(defn ->trigger [org-slug update origin-url user]
  {:to (vec (:to update))
   :subject (:subject update)
   :note (:note update)
   :reply-to (:email user)
   :org-slug org-slug
   :origin-url origin-url
   :entries (:entries update)})

(defn send-trigger! [trigger]
  (timbre/info "Email request to:" config/aws-sqs-email-queue "\n" (dissoc trigger :entries))
  (schema/validate EmailTrigger trigger)
  (timbre/info "Sending request to:" config/aws-sqs-email-queue)
  (sqs/send-message
   {:access-key config/aws-access-key-id
    :secret-key config/aws-secret-access-key}
   config/aws-sqs-email-queue
   trigger)
  (timbre/info "Request sent to:" config/aws-sqs-email-queue))

(ns oc.storage.lib.email
  (:require [amazonica.aws.sqs :as sqs]
            [taoensso.timbre :as timbre]
            [schema.core :as schema]
            [oc.storage.config :as config]
            [oc.storage.resources.common :as common-res]))

(def EmailTrigger
  {:to [schema/Str]
   :subject schema/Str
   :note schema/Str
   :reply-to (schema/maybe schema/Str)
   :org-slug schema/Str
   :org-name schema/Str
   :logo-url (schema/maybe schema/Str)
   :origin-url schema/Str
   :currency schema/Str
   :entries [common-res/UpdateEntry]})

(defn ->trigger [org-slug update origin-url user]
  {:to (vec (:to update))
   :subject (:subject update)
   :note (:note update)
   :reply-to (:email user)
   :org-slug org-slug
   :origin-url origin-url
   :org-name (:org-name update)
   :logo-url (:logo-url update)
   :currency (:currency update)
   :entries (:entries update)})

(defn send-trigger! [trigger]
  (timbre/info "Email request to:" config/aws-sqs-email-queue "\n" (dissoc trigger :entries))
  (schema/validate EmailTrigger trigger)
  (timbre/info "Sending request to:" config/aws-sqs-email-queue)
  (sqs/send-message
   {:access-key config/aws-access-key-id
    :secret-key config/aws-secret-access-key}
   config/aws-sqs-email-queue
   trigger)
  (timbre/info "Request sent to:" config/aws-sqs-email-queue))

Add some missing update props to the update SQS trigger.


(ns fizzbuzz.core-test
  (:require [clojure.test :refer :all]
            [fizzbuzz.core :refer :all]))

(deftest a-test
  (testing "FIXME, I fail."
    (is (= 0 1))))

(ns fizzbuzz.core-test
  (:require [clojure.test :refer :all]
            [fizzbuzz.core :refer :all]))

(deftest fizzbuzz-val-test
  (testing "Returns fizz for multiple of 3"
    (is (= "fizz" (fizzbuzz-val 9))))
  (testing "Returns buzz for multiple of 5"
    (is (= "buzz" (fizzbuzz-val 10))))
  (testing "Returns fizzbuzz for multiple of 15"
    (is (= "fizzbuzz" (fizzbuzz-val 15))))
  (testing "Returns stringified number for other values")
    (is (= "13" (fizzbuzz-val 13))))

(deftest generic-fizzbuzz-test
  (testing "Returns vector of fizzbuzz results"
    (is (= ["1" "2" "fizz" "4" "buzz" "fizz" "7" "8" "fizz"]
           (generic-fizzbuzz 9)))))

(deftest fizzbuzz-test
  (testing "Returns vector of 100 fizzbuzz results"
    (is (= 100 (count (fizzbuzz))))))

Update the clojure fizzbuzz tests.

Update the clojure fizzbuzz tests.


(defproject io.aviso/tracker "0.1.0"
  :description "Track per-thread operations when exceptions occur"
  :url "https://github.com/AvisoNovate/tracker"
  :license {:name "Apache Sofware Licencse 2.0"
            :url  "http://www.apache.org/licenses/LICENSE-2.0.html"}
  :dependencies [[org.clojure/clojure "1.5.1"]
                 [org.clojure/tools.logging "0.2.6"]
                 [io.aviso/pretty "0.1.8"]]
  :codox {:src-dir-uri               "https://github.com/AvisoNovate/tracker/blob/master/"
          :src-linenum-anchor-prefix "L"}
  :profiles {:dev {:dependencies [[log4j "1.2.17"]]}})

(defproject io.aviso/tracker "0.1.1"
  :description "Track per-thread operations when exceptions occur"
  :url "https://github.com/AvisoNovate/tracker"
  :license {:name "Apache Sofware Licencse 2.0"
            :url  "http://www.apache.org/licenses/LICENSE-2.0.html"}
  :dependencies [[org.clojure/clojure "1.5.1"]
                 [org.clojure/tools.logging "0.2.6"]
                 [io.aviso/pretty "0.1.8"]]
  :codox {:src-dir-uri               "https://github.com/AvisoNovate/tracker/blob/master/"
          :src-linenum-anchor-prefix "L"}
  :profiles {:dev {:dependencies [[log4j "1.2.17"]]}})

Advance version number to 0.1.1

Advance version number to 0.1.1


(def project-version "0.1.0-SNAPSHOT")

(defproject whitman project-version
  :description "Samples web APIs for fun and profit"
  :url "https://github.com/mdippery/whitman"
  :license {:name "3-Clause BSD"
            :url "http://opensource.org/licenses/BSD-3-Clause"}
  :dependencies [[org.clojure/clojure "1.6.0"]
                 [org.clojure/data.json "0.2.6"]]
  :main ^:skip-aot whitman.core
  :target-path "target/%s"
  :jar-name "whitman.jar"
  :uberjar-name "whitman-standalone.jar"
  :manifest {"Implementation-Version" ~project-version}
  :profiles {:uberjar {:aot :all}})

(def project-version "0.1.0-SNAPSHOT")

(defproject whitman project-version
  :description "Samples web APIs for fun and profit"
  :url "https://github.com/mdippery/whitman"
  :license {:name "3-Clause BSD"
            :url "http://opensource.org/licenses/BSD-3-Clause"}
  :dependencies [[org.clojure/clojure "1.6.0"]
                 [org.clojure/data.json "0.2.6"]
                 [com.novemberain/monger "2.0.0"]]
  :main ^:skip-aot whitman.core
  :target-path "target/%s"
  :jar-name "whitman.jar"
  :uberjar-name "whitman-standalone.jar"
  :manifest {"Implementation-Version" ~project-version}
  :profiles {:uberjar {:aot :all}})

Include monger 2.0.0 as a dependency

Include monger 2.0.0 as a dependency


(ns emulator-4917.core)

(defn foo
  "I don't do a whole lot."
  [x]
  (println x "Hello, World!"))

(ns emulator-4917.core
  (:require #?(:cljs [cljs.nodejs :as nodejs])
            #?(:cljs [goog.crypt :as gcrypt])
            [clojure.string :as str]))

;; enable *print-fn* in clojurescript
#?(:cljs (enable-console-print!))

(defn to-4bit-array
  "Convert 0xf4 to [f 4]"
  [s]
  (let [h (bit-shift-right s 4) ;; 0xf4 >> 4   => f
        l (bit-and s 0x0f)]     ;; 0xf4 & 0x0f => 4
    [h l]))

(defn parse-rom
  "Parse binary file and convert contents to vector."
  [file]
  (flatten
   (map to-4bit-array
        #?(:clj
           (.getBytes (slurp file) "ascii")
           :cljs
           (->  (nodejs/require "fs")
                (.readFileSync file "ascii")
                .toString
                gcrypt/stringToUtf8ByteArray)
           ))))

(defn -main [& args]
  (let [arg1 (nth args 0)]
    (if arg1
      (println (parse-rom arg1))
      (println "Error: Please specify filename."))))

;; setup node.js starter point
#?(:cljs (set! *main-cli-fn* -main))

Implement binary reader for clj/cljs

Implement binary reader for clj/cljs

The funtion parse-rom will read from binary and convert it to 4-bit
array.

For example, the binary form is

	(79 FB 68 05 F2 00 00 05)

the parse-rom will convert it to

	(7 9 7 11 6 8 0 5 7 2 0 0 0 0 0 5)

Signed-off-by: Yen-Chin Lee <082d453d72dce940e12089a4ad48b97cfe1f3ec4@gmail.com>


(ns comic-reader.api
  (:require [ajax.core :refer [GET POST]]))

(defn error-handler [{:keys [status status-text]}]
  (.log js/console (str "something bad happened: " status " " status-text)))

(defn get-sites [callback]
  (GET "/api/v1/sites" {:handler callback
                        :error-handler error-handler
                        :response-format :edn}))

(ns comic-reader.api
  (:require [re-frame.core :refer [dispatch]]
            [ajax.core :refer [GET POST]]))

(defn error-handler [{:keys [status status-text]}]
  (.log js/console (str "something bad happened: " status " " status-text)))

(defn get-sites []
  (GET "/api/v1/sites" {:handler #(dispatch [:site-list %])
                        :error-handler error-handler
                        :response-format :edn}))

Rewrite API call to dispatch a re-frame event


{:user {
          :dependencies [[cider/cider-nrepl "0.12.0-SNAPSHOT"] ; Emnacs
                         [acyclic/squiggly-clojure "0.1.5"] ; Emacs
                         ^:replace [org.clojure/tools.nrepl "0.2.12"] ; Emacs
                         ]
        :singing {:gpg-key "matthew.russell@wormbase.org"}}
 ;; VisualVM profiling opts
 :jvm-opts ["-Dcom.sun.management.jmxremote"
            "-Dcom.sun.management.jmxremote.ssl=false"
            "-Dcom.sun.management.jmxremote.authenticate=false"
            "-Dcom.sun.management.jmxremote.port=43210"]}

{:user {:plugin-repositories [["private-plugins" {:url "private repo url"}]]
        :singing {:gpg-key "matthew.russell@wormbase.org"}
        :dependencies [[clojure-ini "0.0.2"]
                       [me.raynes/fs "1.4.6"]]
        :plugins [[cider/cider-nrepl "0.8.2"]
                  [refactor-nrepl "0.2.2"]
                  [jonase/eastwood "0.2.3"]
                  [lein-ancient "0.6.8"]
                  [lein-bikeshed "0.3.0"]
                  [lein-kibit "0.1.2"]
                  [lein-ns-dep-graph "0.1.0-SNAPSHOT"]]}
 :repl {:dependencies [[acyclic/squiggly-clojure "0.1.6"]
                       [datomic-schema-grapher "0.0.1"]
                       [org.clojure/tools.nrepl "0.2.12"]]}
 ;; VisualVM profiling opts
 :jvm-opts ["-Dcom.sun.management.jmxremote"
            "-Dcom.sun.management.jmxremote.ssl=false"
            "-Dcom.sun.management.jmxremote.authenticate=false"
            "-Dcom.sun.management.jmxremote.port=43210"]}

Fix up global deps and plugins.

Fix up global deps and plugins.


(ns obb-rules-api.deploy-test
  (:require [obb-rules-api.simulator-test :as sim])
  (:use clojure.test
        obb-rules-api.routes
        ring.mock.request))

(deftest test-deploy
  (let [[result response]
        (sim/turn-ok :p1
                     {:game {:state "deploy"
                             :stash {:p1 {:kamikaze 1}
                                     :p2 {:kamikaze 1}}
                             :width 8
                             :height 8
                             :elements {}}
                      :actions [[:deploy 1 :kamikaze [8 8]]]})]
    (is (= :deploy (get-in result [:board :state])))))

(deftest test-invalid-deploy
  (let [[result response]
        (sim/turn-fail :p2
                     {:game {:state "deploy"
                             :stash {:p1 {:kamikaze 1}
                                     :p2 {:kamikaze 1}}
                             :width 8
                             :height 8
                             :elements {}}
                      :actions [[:deploy 1 :kamikaze [8 8]]]})]
    (is (= "ActionFailed" (get-in result [:message])))
    (is (= :deploy (get-in result [:board :state])))))

(ns obb-rules-api.deploy-test
  (:require [obb-rules-api.simulator-test :as sim])
  (:use clojure.test
        obb-rules-api.routes
        ring.mock.request))

(deftest test-deploy
  (let [[result response]
        (sim/turn-ok :p1
                     {:game {:state "deploy"
                             :stash {:p1 {:kamikaze 1}
                                     :p2 {:kamikaze 1}}
                             :width 8
                             :height 8
                             :elements {}}
                      :actions [[:deploy 1 :kamikaze [8 8]]]})]
    (is (= :deploy (get-in result [:board :state])))))

(deftest test-finish-deploy
  (let [[result response]
        (sim/turn-ok :p1
                     {:game {:state "deploy"
                             :stash {:p1 {:kamikaze 1}
                                     :p2 {}}
                             :width 8
                             :height 8
                             :elements {}}
                      :actions [[:deploy 1 :kamikaze [8 8]]]})]
    (is (not= :deploy (get-in result [:board :state])))))

(deftest test-invalid-deploy
  (let [[result response]
        (sim/turn-fail :p2
                     {:game {:state "deploy"
                             :stash {:p1 {:kamikaze 1}
                                     :p2 {:kamikaze 1}}
                             :width 8
                             :height 8
                             :elements {}}
                      :actions [[:deploy 1 :kamikaze [8 8]]]})]
    (is (= "ActionFailed" (get-in result [:message])))
    (is (= :deploy (get-in result [:board :state])))))

Test auto start battle after deploy

Test auto start battle after deploy


(ns useful.datatypes-test
  (:use clojure.test useful.datatypes))

(defrecord Test [a b c])
(record-accessors Test)

(deftest test-record
  (let [init (Test. 1 2 3)
        second (Test. 1 5 4)]
    (is (= init (make-record Test :b 2 :a 1 :c 3)))
    (is (= second (assoc-record init :b 5 :c 4)))
    (is (= second (update-record init (+ b 3) (inc c))))
    (is (= (:a init) (a init)))
    (testing "Preserves metadata"
      (let [m {:test 1}
            r (Test. 1 2 3 m {})]
        (is (= m (meta (assoc-record r :b 10))))))
    (testing "Inline typehinting"
      (is (= second (assoc-record ^Test (assoc init :b 5) :c 4))))))

(ns useful.datatypes-test
  (:use clojure.test useful.datatypes))

(defrecord Test [a b c])
(record-accessors Test)

(deftest test-record
  (let [init (Test. 1 2 3)
        second (Test. 1 5 4)]
    (is (= init (make-record Test :b 2 :a 1 :c 3)))
    (is (= second (assoc-record init :b 5 :c 4)))
    (is (= second (update-record init (+ b 3) (inc c))))
    (is (= (:a init) (a init)))
    (testing "Preserves metadata"
      (let [m {:test 1}
            r (Test. 1 2 3 m {})]
        (is (= m (meta (assoc-record r :b 10))))))
    (testing "Inline typehinting"
      (is (= second (assoc-record ^Test (assoc init :b 5) :c 4))))

    (testing "Don't eval more than once"
      (let [times-evaled (atom 0)
            r (Test. 1 2 3)]
        (assoc-record ^Test (do (swap! times-evaled inc) r) :a :x :b :y :c :z)
        (is (= 1 @times-evaled))))))

Test that the record expr is only eval'd once


(ns clojournal.db
  (:require [monger.core :as mg]
            [monger.collection :as mc]
            [environ.core :as env]))

(defonce db
  (let [uri (:mongo-url env/env)
        {:keys [conn db]} (mg/connect-via-uri uri)]
    db))

(defn create-indexes []
  (mc/ensure-index db "articles" (array-map :title 1) {:name "by-title"})
  (mc/ensure-index db "articles" (array-map :content 1) {:name "by-content"})
  (mc/ensure-index db "articles" (array-map :author 1) {:name "by-author"})
  (mc/ensure-index db "articles" (array-map :tags 1) {:name "by-tags"}))

(ns clojournal.db
  (:require [monger.core :as mg]
            [monger.collection :as mc]
            [environ.core :as env]))

(defonce db
  (let [uri (:mongo-url env/env)
        {:keys [conn db]} (mg/connect-via-uri uri)]
    db))

(defn create-indexes []
  (mc/ensure-index db "articles" (array-map :title 1) {:name "by-title"})
  (mc/ensure-index db "articles" (array-map :author 1) {:name "by-author"})
  (mc/ensure-index db "articles" (array-map :tags 1) {:name "by-tags"}))

Remove index from article content, which caused some errors


(ns lt.objs.notifos
  (:require [lt.object :as object]
            [lt.objs.statusbar :as statusbar]
            [lt.objs.command :as cmd]
            [lt.util.js :refer [wait]]
            [crate.binding :refer [map-bound bound deref?]])
  (:require-macros [lt.macros :refer [defui]]))

(def standard-timeout 10000)

(defn working [msg]
  (when msg
    (set-msg! msg))
  (statusbar/loader-inc))

(defn done-working [msg]
  (when msg
    (set-msg! msg))
  (statusbar/loader-dec))

(defn msg* [m opts]
  (object/merge! statusbar/statusbar-loader (merge {:message m :class ""} opts)))

(defn set-msg! [msg opts]
  (msg* msg opts)
  (js/clearTimeout cur-timeout)
  (set! cur-timeout (wait standard-timeout #(msg* ""))))

(cmd/command {:command :reset-working
              :desc "Statusbar: Reset working indicator"
              :exec (fn []
                      (statusbar/loader-set 0)
                      )})

(ns lt.objs.notifos
  (:require [lt.object :as object]
            [lt.objs.statusbar :as statusbar]
            [lt.objs.command :as cmd]
            [lt.util.js :refer [wait]]
            [crate.binding :refer [map-bound bound deref?]])
  (:require-macros [lt.macros :refer [defui]]))

(def standard-timeout 10000)

(defn working [msg]
  (when msg
    (set-msg! msg))
  (statusbar/loader-inc))

(defn done-working
  ([]
   (statusbar/loader-dec))
  ([msg]
   (set-msg! msg)
   (statusbar/loader-dec)))

(defn msg* [m opts]
  (object/merge! statusbar/statusbar-loader (merge {:message m :class ""} opts)))

(defn set-msg! [msg opts]
  (msg* msg opts)
  (js/clearTimeout cur-timeout)
  (set! cur-timeout (wait standard-timeout #(msg* ""))))

(cmd/command {:command :reset-working
              :desc "Statusbar: Reset working indicator"
              :exec (fn []
                      (statusbar/loader-set 0)
                      )})

Add a zero-arg version of done-working

Add a zero-arg version of done-working


(ns pinpointer.trace-test
  (:require [clojure.test :refer [deftest are]]
            [clojure.spec.alpha :as s]
            [pinpointer.trace :as trace]))

(deftest trace-test
  (are [spec input expected]
      (= expected (trace/traces (s/explain-data spec input)))
    (s/map-of keyword? (s/coll-of (s/spec integer?)))
    {:a [1 2] :b ["3"]}
    [[[{:spec `(s/map-of keyword? (s/coll-of (s/spec integer?)))
        :val {:a [1 2] :b ["3"]}
        :steps [:b 1]}
       {:spec `(s/coll-of (s/spec integer?)) :val ["3"] :steps [0]}
       {:spec `(s/spec integer?) :val "3" :steps []}
       {:spec `integer? :val "3" :steps []}]]]))

(ns pinpointer.trace-test
  (:require [clojure.test :refer [deftest are]]
            [clojure.spec.alpha :as s]
            [pinpointer.trace :as trace]))

(deftest trace-test
  (are [spec input expected]
      (= expected (trace/traces (s/explain-data spec input)))
    (s/map-of keyword? (s/coll-of (s/spec integer?)))
    {:a [1 2] :b ["3"]}
    [[[{:spec `(s/map-of keyword? (s/coll-of (s/spec integer?)))
        :val {:a [1 2] :b ["3"]}
        :steps [:b 1]}
       {:spec `(s/coll-of (s/spec integer?)) :val ["3"] :steps [0]}
       {:spec `(s/spec integer?) :val "3" :steps []}
       {:spec `integer? :val "3" :steps []}]]]

    (s/cat :first integer? :second integer?)
    [1]
    [[[{:spec `(s/cat :first integer? :second integer?) :val [1] :steps []}
       {:spec `integer? :val [1] :steps [] :reason "Insufficient input"}]]]

    (s/cat :first integer? :second integer?)
    [1 2 3]
    [[[{:spec `(s/cat :first integer? :second integer?)
        :val [1 2 3]
        :steps [2]
        :reason "Extra input"}]]]))

Add more test cases for insufficient/extra input


(ns discuss.config)

(def project "discuss")

(def user "Q2hyaXN0aWFu")

(def api {:host "http://dbas/"
          :init "api/elektroautos"
          :base "api/"
          :add  {:add-start-statement "add/start_statement"
                 :add-start-premise   "add/start_premise"
                 :add-justify-premise "add/justify_premise"}
          :get  {:references       "get/references"
                 :reference-usages "get/reference/usages"
                 :statements       "get/statements"
                 :statement-url    "api/get/statement/url"}})

(ns discuss.config)

(def project "discuss")

(def user "Q2hyaXN0aWFu")

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

Use local address of dabas-

Use local address of dabas-


(ns rill.cli
  (:require [rill.event-store.atom-store :refer [atom-event-store]]
            [rill.event-channel :refer [event-channel]]
            [rill.event-stream :refer [all-events-stream-id]]
            [rill.event-store.atom-store.event :refer [unprocessable?]]
            [clojure.core.async :refer [<!!]])
  (:gen-class))

(defn -main [url user password]
  {:pre [url user password]}
  (let [ch (event-channel (atom-event-store url {:user user :password password})
                          all-events-stream-id -1 0)]
    (println "Printing all events...")
    (loop []
      (if-let [e (<!! ch)]
        (do (if (unprocessable? e)
              (println "Skipped message.")
              (prn e))
            (recur))))))

(ns rill.cli
  (:require [rill.event-store.psql :refer [psql-event-store]]
            [rill.event-channel :refer [event-channel]]
            [rill.event-stream :refer [all-events-stream-id]]
            [rill.event-store.atom-store.event :refer [unprocessable?]]
            [clojure.core.async :refer [<!!]])
  (:gen-class))

(defn -main [url]
  {:pre [url]}
  (let [ch (event-channel (psql-event-store url)
                          all-events-stream-id -1 0)]
    (println "Printing all events...")
    (loop []
      (if-let [e (<!! ch)]
        (do (if (unprocessable? e)
              (println "Skipped message.")
              (prn e))
            (recur))))))

Make it possible to use the psql event store


(ns yadnd5ecs.core
  (:require [om.core :as om :include-macros true]
            [om-tools.dom :as dom :include-macros true]
            [om-tools.core :refer-macros [defcomponent]]))

(enable-console-print!)

(def app-state (atom {:text "Hello Chestnut!"}))

(defn main []
  (om/root
    (fn [app owner]
      (reify
        om/IRender
        (render [_]
          (dom/h1 (:text app)))))
    app-state
    {:target (. js/document (getElementById "app"))}))

(ns yadnd5ecs.core
  (:require [om.core :as om :include-macros true]
            [om-tools.dom :as dom :include-macros true]
            [om-tools.core :refer-macros [defcomponent]]))

(enable-console-print!)

(def app-state (atom {:text "Hello Chestnut!"}))

(defcomponent app-view
  [app owner]
  (render [_]
          (dom/h1 (:text app))))

(defn main []
  (om/root
    app-view
    app-state
    {:target (. js/document (getElementById "app"))}))

Refactor initial view into defcomponent.


(ns
  ^{:doc

  "A patched JTextField implementation."

    :author "Frank Mosebach"}
  fm.simrunner.gui.text-field
  (:gen-class
    :name fm.simrunner.gui.TextField
    :extends javax.swing.JTextField
    :exposes-methods {setText superSetText}))

(defn -setText [this text]
  (when (not= (.getText this) text)
    (.superSetText this text)))

(ns
  ^{:doc

  "A patched JTextField implementation."

    :author "Frank Mosebach"}
  fm.simrunner.gui.text-field
  (:gen-class
    :name fm.simrunner.gui.TextField
    :extends javax.swing.JTextField
    :exposes-methods {setText superSetText}))

(defn -setText [this text]
  (when (not= (.getText this) text)
    (doto this
      (.superSetText text)
      (.setCaretPosition 0))))

Reset the caret to position 0 when setting the text.


(ns armstrong-numbers-test
  (:require [clojure.test :refer [deftest is testing]]
            [armstrong-numbers :refer [armstrong?]]))

(deftest armstrong-number-5
  (testing "Single digit numbers are Armstrong numbers"
    (is (armstrong? 5))))

(deftest not-armstrong-number-10
  (testing "There are no 2 digit Armstrong numbers"
    (is (not (armstrong? 10)))))

(deftest armstrong-number-153
  (testing "Three digit number that is an Armstrong number"
    (is (armstrong? 153))))

(deftest not-armstrong-number-100
  (testing "Three digit number that is an Armstrong number"
    (is (not (armstrong? 100)))))

(deftest armstrong-number-9474
  (testing "Four digit number that is an Armstrong number"
    (is (armstrong? 9474))))

(deftest not-armstrong-number-9475
  (testing "Four digit number that is not an Armstrong number"
    (is (not (armstrong? 9476)))))

(deftest armstrong-number-9926315
  (testing "Seven digit number that is an Armstrong number"
    (is (armstrong? 9926315))))

(deftest not-armstrong-number-9926314
  (testing "Seven digit number that is not an Armstrong number"
    (is (not (armstrong? 9926314)))))

(ns armstrong-numbers-test
  (:require [clojure.test :refer [deftest is testing]]
            [armstrong-numbers :refer [armstrong?]]))

(deftest armstrong-number-5
  (testing "Single digit numbers are Armstrong numbers"
    (is (armstrong? 5))))

(deftest not-armstrong-number-10
  (testing "There are no 2 digit Armstrong numbers"
    (is (not (armstrong? 10)))))

(deftest armstrong-number-153
  (testing "Three digit number that is an Armstrong number"
    (is (armstrong? 153))))

(deftest not-armstrong-number-100
  (testing "Three digit number that is not an Armstrong number"
    (is (not (armstrong? 100)))))

(deftest armstrong-number-9474
  (testing "Four digit number that is an Armstrong number"
    (is (armstrong? 9474))))

(deftest not-armstrong-number-9475
  (testing "Four digit number that is not an Armstrong number"
    (is (not (armstrong? 9476)))))

(deftest armstrong-number-9926315
  (testing "Seven digit number that is an Armstrong number"
    (is (armstrong? 9926315))))

(deftest not-armstrong-number-9926314
  (testing "Seven digit number that is not an Armstrong number"
    (is (not (armstrong? 9926314)))))

Fix 3-digit armstrong test description

Fix 3-digit armstrong test description

The description contradicts what is being tested and needs to be in
the negative.


(ns discuss.components.sidebar
  "Controlling the sidebar."
  (:require [om.core :as om]
            [om.dom :as dom]
            [discuss.utils.common :as lib]
            [discuss.utils.views :as vlib]))

(def id (lib/prefix-name "sidebar"))

(defn toggle
  "Toggle visibility of sidebar."
  ([]
   (let [sidebar-dom (.getElementById js/document id)
         main-wrapper (.getElementById js/document "main-wrapper")]
     (lib/toggle-class sidebar-dom "active")
     (lib/toggle-class main-wrapper "active")))
  ([bool]
   (let [sidebar-dom (.getElementById js/document id)
         main-wrapper (.getElementById js/document "main-wrapper")]
     (lib/toggle-class sidebar-dom "active" bool)
     (lib/toggle-class main-wrapper "active" bool))))

(defn show
  "Show sidebar."
  []
  (toggle true))

(defn hide
  "Hide sidebar."
  []
  (toggle false))

;;;; Sidebar
(defn view [data]
  (reify om/IRender
    (render [_]
      (dom/div nil
               (vlib/fa-icon "fa-bars" hide)
               (om/build discuss.views/main-view data)))))

(ns discuss.components.sidebar
  "Controlling the sidebar."
  (:require [om.core :as om]
            [om.dom :as dom]
            [goog.dom :as gdom]
            [discuss.utils.common :as lib]
            [discuss.utils.views :as vlib]))

(def id (lib/prefix-name "sidebar"))

(defn toggle
  "Toggle visibility of sidebar."
  ([]
   (let [sidebar-dom (gdom/getElement id)
         main-wrapper (gdom/getElement "main-wrapper")]
     (lib/toggle-class sidebar-dom "active")
     (lib/toggle-class main-wrapper "active")))
  ([bool]
   (let [sidebar-dom (gdom/getElement id)
         main-wrapper (gdom/getElement "main-wrapper")]
     (lib/toggle-class sidebar-dom "active" bool)
     (lib/toggle-class main-wrapper "active" bool))))

(defn show
  "Show sidebar."
  []
  (toggle true))

(defn hide
  "Hide sidebar."
  []
  (toggle false))

;;;; Sidebar
(defn view [data]
  (reify om/IRender
    (render [_]
      (dom/div nil
               (vlib/fa-icon "fa-bars" hide)
               (om/build discuss.views/main-view data)))))

Use Google Closure to find dom element

Use Google Closure to find dom element


;; All about higher order functions =)
(ns mlpractice.lesson1)

(defn generate-data-set
  "Generates a map of :x y values for linear regression"
  [constant slope num]
  (nth (iterate
        #(let [x (Math/random)]
           (assoc %1 x (+ constant (* slope x)))) {}) num))

(defn hypothesis-fn
  "Builds the hypothesis function h(x) using th0 and th1"
  [theta0 theta1]
  (fn h
    [x]
    (+ theta0 (* theta1 x))))

(defn cost-summation
  "The function that gets applied to every entry in every data set"
  [hypothesis agg data]
  (let [x (first data)
        y (second data)]
    (+ agg (- (hypothesis x) y))))

;;Difference between inside and outside let?
(defn cost-fn
  "Builds the cost function J(th0, th1) for some amount of data"
  [data]
  (let [coefficient (->> data (count) (* 2) (/ 1))]
    (fn cost
      [th0 th1]
      (let [hypothesis (hypothesis-fn th0 th1)]
        (* coefficient
           (reduce (partial cost-summation hypothesis) 0 data))))))

;; All about higher order functions =)
;; Linear Regression with multiple variables

(ns mlpractice.lesson1)

;innefficient because iterate holds onto old maps, should use a different function?
(defn generate-data-set
  "Generates a map of a vector x of feature values
   to its y value for linear regression"
  [data-point-num & coefficients]
  (nth (iterate
        #(let [n (count coefficients)
               x-vec (repeatedly n (fn [] (Math/random)))]
           (assoc %1 x-vec (apply + (map * x-vec coefficients))))
        {})
       data-point-num))

(defn hypothesis-fn
  "Builds the hypothesis function h(x) using a vector theta of coefficients"
  [param-vec]
  (fn h
    [feature-vec]
    (apply + (map * param-vec feature-vec))))

(defn cost-summation
  "The function that finds the error between our hypothesis function
   and our actual y value, and adds it to an aggregate"
  [hypothesis agg data]
  (let [x (first data)
        y (second data)]
    (+ agg (- (hypothesis x) y))))

;;Difference between inside and outside let?
(defn cost-fn
  "Builds the cost function J(th0, th1) for some amount of data"
  [data]
  (let [coefficient (->> data (count) (* 2) (/ 1))]
    (fn cost
      [param-vec]
      (let [hypothesis (hypothesis-fn param-vec)]
        (-> (partial cost-summation hypothesis)
            (reduce 0 data)
            (Math/pow 2)
            (* coefficient))))))

Update lesson 1 to work for linear regression with multiple variables


;; See: https://github.com/kumarshantanu/lein-localrepo
{:user {:plugins [;; Try new api quickly using the repl
                  [lein-try "0.4.3"]

                  ;;[lein-localrepo "0.5.4"]

                  ;; Convert pom.xml to project.clj
                  ;; Note: from https://github.com/thickey/lein-nevam
                  [lein-nevam "0.1.2"]

                  ;; A Leiningen plugin for a superior development environment
                  ;; See: [Introduction Blog Post](https://blog.venanti.us/ultra/)
                  ;; https://github.com/venantius/ultra
                  ;;[venantius/ultra "0.5.2"]

                  ;; Pretty-print a representation of the project map
                  [lein-pprint "1.2.0"]
                  ;; Keep adding more stuff here
                  ]
        ;; Experimental
        :dependencies [[pjstadig/humane-test-output "0.8.3"]]
        :injections [(require 'pjstadig.humane-test-output)
                     (pjstadig.humane-test-output/activate!)]}}

;; See: https://github.com/kumarshantanu/lein-localrepo
{:user {:plugins [;; Try new api quickly using the repl
                  [lein-try "0.4.3"]

                  ;;[lein-localrepo "0.5.4"]

                  ;; Convert pom.xml to project.clj
                  ;; Note: from https://github.com/thickey/lein-nevam
                  [lein-nevam "0.1.2"]

                  ;; A Leiningen plugin for a superior development environment
                  ;; See: [Introduction Blog Post](https://blog.venanti.us/ultra/)
                  ;; https://github.com/venantius/ultra
                  ;;[venantius/ultra "0.5.2"]

                  ;; Pretty-print a representation of the project map
                  [lein-pprint "1.2.0"]
                  ;; Keep adding more stuff here
                  ]
        ;; Experimental
        :dependencies [[pjstadig/humane-test-output "0.8.3"]
                       ;; See: https://github.com/pallet/alembic
                       [alembic "0.3.2"]]
        :injections [(require 'pjstadig.humane-test-output)
                     (pjstadig.humane-test-output/activate!)]}}

Add pallet/alembic to Clojure profile

Add pallet/alembic to Clojure profile


(ns avalon.rules.people
  (:require [bouncer.core :as b]
            [bouncer.validators :as v]
            [avalon.models.crud :as crud]
            [avalon.models.games :as games]))

(defn person-rules [method game]
  (let [taken? (fn [name]
                 (if (= method :post)
                   (= (count (games/people-named game name)) 0)
                   true))]
    {:name [v/required
            [taken? :message "There is already a player with that name"]]}))

(def add-person-rules
  {:status [[#{:waiting} :message "Game already started"]]})

(defn valid-person? [id kw key]
  (fn [ctx]
    (let [game (crud/get games/games id)
          rules (person-rules (get-in ctx [:request :request-method]) game)
          valid (and (b/valid? (kw ctx) rules)
                     (b/valid? game add-person-rules))
          errors (concat (first (b/validate (kw ctx) rules))
                         (first (b/validate game add-person-rules)))]
      [valid {key errors}])))

(def info-rules
  {:status [[#{:playing} :message "Game not started"]]})

(defn valid-info? [game]
  (let [valid (b/valid? game info-rules)
        errors (first (b/validate game info-rules))]
    [valid errors]))

(ns avalon.rules.people
  (:require [bouncer.core :as b]
            [bouncer.validators :as v]
            [avalon.models.crud :as crud]
            [avalon.models.games :as games]))

(defn person-rules [method game]
  (let [taken? (fn [name]
                 (if (= method :post)
                   (= (count (games/people-named game name)) 0)
                   true))]
    {:id [[(fn [_] (some? game)) :message "Game with that code does not exist"]]
     :name [v/required
            [taken? :message "There is already a player with that name"]]}))

(def add-person-rules
  {:status [[#{:waiting} :message "Game already started"]]})

(defn valid-person? [id kw key]
  (fn [ctx]
    (let [game (crud/get games/games id)
          rules (person-rules (get-in ctx [:request :request-method]) game)
          valid (and (b/valid? (kw ctx) rules)
                     (b/valid? game add-person-rules))
          errors (concat (first (b/validate (kw ctx) rules))
                         (first (b/validate game add-person-rules)))]
      [valid {key errors}])))

(def info-rules
  {:status [[#{:playing} :message "Game not started"]]})

(defn valid-info? [game]
  (let [valid (b/valid? game info-rules)
        errors (first (b/validate game info-rules))]
    [valid errors]))

Fix when code doesn't exist

Fix when code doesn't exist


(ns braid.core.client.pages
  (:require
    [spec-tools.data-spec :as ds]
    [braid.core.hooks :as hooks]))

(def page-dataspec
  {:key keyword?
   :on-load fn?
   :view fn?
   (ds/opt :styles) vector?})

(defonce pages
  (hooks/register! (atom {}) {keyword? page-dataspec}))

(defn on-load! [page-id page]
  (when-let [f (get-in @pages [page-id :on-load])]
    (f page)))

(defn get-view [page-id]
  (get-in @pages [page-id :view]))

(ns braid.core.client.pages
  (:require
    [spec-tools.data-spec :as ds]
    [braid.core.hooks :as hooks]))

(def page-dataspec
  {:key keyword?
   :view fn?
   (ds/opt :on-load) fn?
   (ds/opt :styles) vector?})

(defonce pages
  (hooks/register! (atom {}) {keyword? page-dataspec}))

(defn on-load! [page-id page]
  (when-let [f (get-in @pages [page-id :on-load])]
    (f page)))

(defn get-view [page-id]
  (get-in @pages [page-id :view]))

Make on-load key optional as per documentation


(defproject play-clj/lein-template "0.1.0-SNAPSHOT"
  :description "A template for making play-clj projects"
  :url "https://github.com/oakes/play-clj"
  :license {:name "Public Domain"
            :url "http://unlicense.org/UNLICENSE"}
  :dependencies [[lein-droid "0.2.0"]]
  :resource-paths ["resources"]
  :eval-in-leiningen true)

(defproject play-clj/lein-template "0.1.0"
  :description "A template for making play-clj projects"
  :url "https://github.com/oakes/play-clj"
  :license {:name "Public Domain"
            :url "http://unlicense.org/UNLICENSE"}
  :dependencies [[lein-droid "0.2.0"]]
  :resource-paths ["resources"]
  :eval-in-leiningen true)

Update template itself to stable release


(ns cadence.model
  (:refer-clojure :exclude [identity])
  (:require [monger.core :as mg]
            [monger.collection :as mc]
            [cadence.model.validators :as is-valid]
            [cemerick.friend :as friend])
  (:use clojure.walk
        [cemerick.friend.credentials :only [hash-bcrypt]]))

(defn- ensure-indexes []
  (mc/ensure-index "users" {:username 1}))

(defn connect [connection-info]
  (if (:uri connection-info)
    (mg/connect-via-uri! (:uri connection-info))
    (mg/connect!))
  (let [db-name (:db-name connection-info)]
    (mg/authenticate db-name
                     (:username connection-info)
                     (into-array Character/TYPE (:password connection-info)))
    (mg/set-db! (mg/get-db db-name))
    (ensure-indexes)))

(defn get-user [username]
  (mc/find-one-as-map "users" {:username username}))

(defn add-user [user]
  (if (is-valid/user? user)
    (mc/save "users" (assoc user :password (hash-bcrypt (:password user))))))

(def identity #(get friend/*identity* :current))

(defn get-phrase []
  "passwords are so completely last decade")

(ns cadence.model
  (:refer-clojure :exclude [identity])
  (:require [monger.core :as mg]
            [monger.collection :as mc]
            [cadence.model.validators :as is-valid]
            [cemerick.friend :as friend])
  (:use clojure.walk
        [cemerick.friend.credentials :only [hash-bcrypt]]))

(defn- ensure-indexes []
  (mc/ensure-index "users" {:username 1}))

(defn connect [connection-info]
  (if (:uri connection-info)
    (mg/connect-via-uri! (:uri connection-info))
    (mg/connect!))
  (let [db-name (:db-name connection-info)]
    (mg/authenticate db-name
                     (:username connection-info)
                     (into-array Character/TYPE (:password connection-info)))
    (mg/set-db! (mg/get-db db-name))
    (ensure-indexes)))

(defn get-user [username]
  (mc/find-one-as-map "users" {:username username}))

(defn add-user [user]
  (if (is-valid/user? user)
    (mc/save "users" (assoc user :password (hash-bcrypt (:password user))))))

(def identity #(get friend/*identity* :current))

(defn get-phrase []
  "completing this phrase is fun")

Change default phrase to a shorter one.

Change default phrase to a shorter one.


(ns bmihw.submit
  (:require [bmihw.common :refer [auth fb]]
            [reagent-forms.core :refer [bind-fields]]))

(defn update-state! [state key e]
  (let [new-state (swap! state assoc key (-> e .-target .-value))
        {:keys [username keyword content]} new-state
        submit (.querySelector js/document "#submit")]
    (set! (.-disabled submit) (not (and (or (seq username) (seq keyword))
                                        (seq content))))))

(defn submit-to-fb! [state]
  (.push fb
    (clj->js @state)
    (fn [error]
      (when error
        (js/alert (str "An error occurred: " error))))))

(defn submit-page []
  (let [state (atom {})]
    [:div [:h2 "Submit your insult."]
     [:div [:div
            [:input {:type :text :name :username :placeholder "Username"
                     :on-change #(update-state! state :username %)}]
            [:br]
            [:input {:type :text :name :keyword :placeholder "Keyword"
                     :on-change #(update-state! state :keyword %)}]
            [:br]
            [:input {:type :text :name :content :placeholder "Content"
                     :on-change #(update-state! state :content %)}]
            [:br]
            [:input {:type :submit :value "Submit" :id "submit" :disabled true
                     :on-click #(submit-to-fb! state)}]]]]))

(ns bmihw.submit
  (:require [bmihw.common :refer [auth fb]]
            [reagent-forms.core :refer [bind-fields]]))

(defn update-state! [state key e]
  (let [new-state (swap! state assoc key (-> e .-target .-value))
        {:keys [username keyword content]} new-state
        submit (.querySelector js/document "#submit")]
    (set! (.-disabled submit) (not (and (or (seq username) (seq keyword))
                                        (seq content))))))

(defn submit-to-fb! [state]
  (.push fb
    (clj->js (merge @state
                    (select-keys @auth ["uid" "provider"])
                    (select-keys (get @auth "twitter") ["accessToken" "accessTokenSecret" "username"])))
    (fn [error]
      (when error
        (js/alert (str "An error occurred: " error))))))

(defn submit-page []
  (let [state (atom {})]
    [:div [:h2 "Submit your insult."]
     [:div [:div
            [:input {:type :text :name :target-username :placeholder "Username"
                     :on-change #(update-state! state :target-username %)}]
            [:br]
            [:input {:type :text :name :keyword :placeholder "Keyword"
                     :on-change #(update-state! state :keyword %)}]
            [:br]
            [:input {:type :text :name :content :placeholder "Content"
                     :on-change #(update-state! state :content %)}]
            [:br]
            [:input {:type :submit :value "Submit" :id "submit" :disabled true
                     :on-click #(submit-to-fb! state)}]]]]))

SEND MORE STUFF TO FIREBASE

SEND MORE STUFF TO FIREBASE


(ns app.players
  (:require [app.representation :as reps]
            [app.player :as player]
            [app.multiplexer :as mux]
            [app.screen :as screen]))

(defonce index (atom 0))

(defn single [data layout]
  (reify
    player/Player
    (step-fwd [_]
      (reset! layout {:text ((:items (@data 0)) (mod @index (count @data)))
                      :opacity 1.0})
      (swap! index inc))
    (step-rnd [_]
      (reset! layout  {:text (mux/get-item data)
                       :opacity 1.0}))
    (animation [_])
    (render [_]
      [:div {:class "single"
             :key (rand-int 1000000)
             :style {:position "absolute"
                     :opacity 1.0
                     :left "40%"
                     :top "30%"}}
       (:text @layout)])))

(ns app.players
  (:require [app.representation :as reps]
            [app.player :as player]
            [app.multiplexer :as mux]
            [app.screen :as screen]))

(defonce index (atom 0))

(defn single [data layout]
  (reify
    player/Player
    (step-fwd [_]
      (reset! layout [{:text ((:items (@data 0)) (mod @index (count @data)))
                       :key (str (rand-int 100000000))
                       :opacity 1.0}])
      (swap! index inc))
    (step-rnd [_]
      (reset! layout [{:text (mux/get-item data)
                       :key (str (rand-int 100000000))
                       :opacity 1.0}]))
    (animation [_])
    (render [_]
      [:div {:class "single"
             :key (rand-int 1000000)
             :style {:position "absolute"
                     :opacity 1.0
                     :left "40%"
                     :top "30%"}}
       (:text (first @layout) )])))

Fix single mode and switching back to drizzle


(defproject com.howardlewisship.cascade/cascade-core "1.0.0-SNAPSHOT"
  :description "Simple, fast, easy web applications in idiomatic Clojure"
  :url "http://github.com/hlship/cascade/"
  :dependencies
    [[org.clojure/clojure "1.1.0"]
     [org.clojure/clojure-contrib "1.1.0"]
     [org.slf4j/slf4j-api "1.5.2"]

     [org.slf4j/slf4j-log4j12 "1.5.2"]
     [log4j/log4j "1.2.14"]]
  :dev-dependencies
    [[org.eclipse.jetty/jetty-server "7.0.0.RC4"]
     [org.eclipse.jetty/jetty-servlet "7.0.0.RC4"]
     [org.easymock/easymock "2.5.1"]
     [org.seleniumhq.selenium.client-drivers/selenium-java-client-driver "1.0.3"]
     ; oops, need the right classification of this, not yet supported
     [org.seleniumhq.selenium.server/selenium-server "1.0.3"]
     [org.seleniumhq.selenium.server/selenium-server-coreless "1.0.3"]]
  :aot :all
  :warn-on-reflection true
  :source-path "src/main/clojure"
  :test-path "src/test/clojure"
  :resources-path "src/main/resources"
  :jar-dir "target")

(defproject com.howardlewisship.cascade/cascade-core "1.0.0-SNAPSHOT"
  :description "Simple, fast, easy web applications in idiomatic Clojure"
  :url "http://github.com/hlship/cascade/"
  :dependencies
    [[org.clojure/clojure "1.1.0"]
     [org.clojure/clojure-contrib "1.1.0"]
     [org.slf4j/slf4j-api "1.5.2"]

     [org.slf4j/slf4j-log4j12 "1.5.2"]
     [log4j/log4j "1.2.14"]]
  :dev-dependencies
    [[org.eclipse.jetty/jetty-server "7.0.0.RC4"]
     [org.eclipse.jetty/jetty-servlet "7.0.0.RC4"]
     [org.easymock/easymock "2.5.1"]
     [org.seleniumhq.selenium.server/selenium-server "1.0.3" :classifier "standalone"]]
  :aot :all
  :warn-on-reflection true
  :source-path "src/main/clojure"
  :test-path "src/test/clojure"
  :resources-path "src/main/resources"
  :test-resources-path "src/test/resources"
  :jar-dir "target")

Update dependencies to pull Selenium with "standalone" classifier, identify test resources path


(defproject onyx-app/lein-template "0.9.0.8"
  :description "Onyx Leiningen application template"
  :url "https://github.com/onyx-platform/onyx-template"
  :license {:name "Eclipse Public License"
            :url "http://www.eclipse.org/legal/epl-v10.html"}
  :repositories {"snapshots" {:url "https://clojars.org/repo"
                              :username :env
                              :password :env
                              :sign-releases false}
                 "releases" {:url "https://clojars.org/repo"
                             :username :env
                             :password :env
                             :sign-releases false}}
  :plugins [[lein-set-version "0.4.1"]]
  :profiles {:dev {:plugins [[lein-set-version "0.4.1"]
                             [lein-update-dependency "0.1.2"]
                             [lein-pprint "1.1.1"]]}}
  :eval-in-leiningen true)

(defproject onyx-app/lein-template "0.9.0.9-SNAPSHOT"
  :description "Onyx Leiningen application template"
  :url "https://github.com/onyx-platform/onyx-template"
  :license {:name "Eclipse Public License"
            :url "http://www.eclipse.org/legal/epl-v10.html"}
  :repositories {"snapshots" {:url "https://clojars.org/repo"
                              :username :env
                              :password :env
                              :sign-releases false}
                 "releases" {:url "https://clojars.org/repo"
                             :username :env
                             :password :env
                             :sign-releases false}}
  :plugins [[lein-set-version "0.4.1"]]
  :profiles {:dev {:plugins [[lein-set-version "0.4.1"]
                             [lein-update-dependency "0.1.2"]
                             [lein-pprint "1.1.1"]]}}
  :eval-in-leiningen true)

Prepare for next release cycle.

Prepare for next release cycle.


(defproject org.onyxplatform/onyx-sql "0.7.3-SNAPSHOT"
  :description "Onyx plugin for JDBC-backed SQL databases"
  :url "https://github.com/MichaelDrogalis/onyx-sql"
  :license {:name "Eclipse Public License"
            :url "http://www.eclipse.org/legal/epl-v10.html"}
  :dependencies [[org.clojure/clojure "1.7.0"]
                 [org.clojure/java.jdbc "0.3.3"]
                 ^{:voom {:repo "git@github.com:onyx-platform/onyx.git" :branch "master"}}
                 [org.onyxplatform/onyx "0.7.3-20150827_160450-g706d154"]
                 [java-jdbc/dsl "0.1.3"]
                 [com.mchange/c3p0 "0.9.2.1"]
                 [honeysql "0.5.1"]]
  :profiles {:dev {:dependencies [[midje "1.7.0"]
                                  [environ "1.0.0"]
                                  [mysql/mysql-connector-java "5.1.25"]]
                   :plugins [[lein-midje "3.1.3"]]}
             :circle-ci {:jvm-opts ["-Xmx4g"]}})

(defproject org.onyxplatform/onyx-sql "0.7.3-SNAPSHOT"
  :description "Onyx plugin for JDBC-backed SQL databases"
  :url "https://github.com/MichaelDrogalis/onyx-sql"
  :license {:name "Eclipse Public License"
            :url "http://www.eclipse.org/legal/epl-v10.html"}
  :dependencies [[org.clojure/clojure "1.7.0"]
                 [org.clojure/java.jdbc "0.3.3"]
                 ^{:voom {:repo "git@github.com:onyx-platform/onyx.git" :branch "master"}}
                 [org.onyxplatform/onyx "0.7.3-20150827_202930-g49ef67c"]
                 [java-jdbc/dsl "0.1.3"]
                 [com.mchange/c3p0 "0.9.2.1"]
                 [honeysql "0.5.1"]]
  :profiles {:dev {:dependencies [[midje "1.7.0"]
                                  [environ "1.0.0"]
                                  [mysql/mysql-connector-java "5.1.25"]]
                   :plugins [[lein-midje "3.1.3"]]}
             :circle-ci {:jvm-opts ["-Xmx4g"]}})

Update dependency org.onyxplatform/onyx to version 0.7.3-20150827_202930-g49ef67c.

Automatic commit by lein-traffic-control.


(defproject onyx-app/lein-template "0.9.7.0-alpha17"
  :description "Onyx Leiningen application template"
  :url "https://github.com/onyx-platform/onyx-template"
  :license {:name "MIT License"
            :url "http://choosealicense.com/licenses/mit/#"}
  :repositories {"snapshots" {:url "https://clojars.org/repo"
                              :username :env
                              :password :env
                              :sign-releases false}
                 "releases" {:url "https://clojars.org/repo"
                             :username :env
                             :password :env
                             :sign-releases false}}
  :plugins [[lein-set-version "0.4.1"]]
  :profiles {:dev {:plugins [[lein-set-version "0.4.1"]
                             [lein-update-dependency "0.1.2"]
                             [lein-pprint "1.1.1"]]}}
  :eval-in-leiningen true)

(defproject onyx-app/lein-template "0.9.7.0-SNAPSHOT"
  :description "Onyx Leiningen application template"
  :url "https://github.com/onyx-platform/onyx-template"
  :license {:name "MIT License"
            :url "http://choosealicense.com/licenses/mit/#"}
  :repositories {"snapshots" {:url "https://clojars.org/repo"
                              :username :env
                              :password :env
                              :sign-releases false}
                 "releases" {:url "https://clojars.org/repo"
                             :username :env
                             :password :env
                             :sign-releases false}}
  :plugins [[lein-set-version "0.4.1"]]
  :profiles {:dev {:plugins [[lein-set-version "0.4.1"]
                             [lein-update-dependency "0.1.2"]
                             [lein-pprint "1.1.1"]]}}
  :eval-in-leiningen true)

Prepare for next release cycle.

Prepare for next release cycle.


(defproject me.arrdem/oxcart "0.1.0-SNAPSHOT"
  :description "An experimental optimizing compiler for Clojure code"
  :url "http://github.com/arrdem/oxcart"
  :license {:name "Eclipse Public License"
            :url "http://www.eclipse.org/legal/epl-v10.html"}
  :dependencies [
                 [org.clojure/clojure            "1.5.1"]
                 [org.clojure/tools.analyzer.jvm "0.1.0"]
                 [org.clojure/tools.emitter.jvm  "0.1.0"]
                 ])

(defproject me.arrdem/oxcart "0.1.0-SNAPSHOT"
  :description "An experimental optimizing compiler for Clojure code"
  :url "http://github.com/arrdem/oxcart"
  :license {:name "Eclipse Public License"
            :url "http://www.eclipse.org/legal/epl-v10.html"}
  :dependencies [
                 [org.clojure/clojure            "1.5.1"]
                 [org.clojure/tools.analyzer.jvm "0.1.0"]
                 [org.clojure/tools.emitter.jvm  "0.1.0"]
                 [org.clojure/tools.reader       "0.8.4"]
                 ])

Add tools.reader as a dep

Add tools.reader as a dep


(ns desdemona.query-test
  (:require
   [desdemona.query :as q]
   [clojure.test :refer [deftest is]]))

(def dsl->logic
  @#'desdemona.query/dsl->logic)

(deftest dsl->logic-tests
  (is (= '(clojure.core.logic/featurec x {:ip "10.0.0.1"})
         (dsl->logic '(= (:ip x) "10.0.0.1")))))

(deftest dsl-query-tests
  (is (= [[{:ip "10.0.0.1"}]]
         (q/run-dsl-query '(= (:ip x) "10.0.0.1")
                          [{:ip "10.0.0.1"}]))))

(deftest logic-query-tests
  (is (= []
         (q/run-logic-query 'l/fail
                            [{:ip "10.0.0.1"}])))
  (is (= [[{:ip "10.0.0.1"}]]
         (q/run-logic-query '(l/featurec x {:ip "10.0.0.1"})
                            [{:ip "10.0.0.1"}]))))

(ns desdemona.query-test
  (:require
   [desdemona.query :as q]
   [clojure.test :refer [deftest is are]]))

(def dsl->logic
  @#'desdemona.query/dsl->logic)

(deftest dsl->logic-tests
  (is (= '(clojure.core.logic/featurec x {:ip "10.0.0.1"})
         (dsl->logic '(= (:ip x) "10.0.0.1")))))

(deftest dsl-query-tests
  (is (= [[{:ip "10.0.0.1"}]]
         (q/run-dsl-query '(= (:ip x) "10.0.0.1")
                          [{:ip "10.0.0.1"}]))))

(deftest logic-query-tests
  (are [events query results] (= results (q/run-logic-query query events))
    [{:ip "10.0.0.1"}]
    'l/fail
    []

    [{:ip "10.0.0.1"}]
    '(l/featurec x {:ip "10.0.0.1"})
    [[{:ip "10.0.0.1"}]]))

Refactor logic-query-tests to use `are`

Refactor logic-query-tests to use `are`