{
 :name "tnseq-phase1",
 :path  "",

 :graph {:bt1 {:type "tool"
               :path "bowtie2"
               :args ["-p" "16" "--very-sensitive" "-x" "#1" "-U" "#2"]
               }
         :bt2 {:type "tool"
               :path "bowtie2"
               :args ["-f" "-N" "1" "--reorder"
                      "--no-unal" "--no-head"
                      "-p" "8"
                      "-x" "#1" "-U" "#3"]
               }
         :mmap {:type "func"
                :name "make-maps"
                :args ["#4"]}
         :st1 {:type :tool
               :path "samtools"
               :args ["view" "-b"]}
         :st2 {:type :tool
               :path "samtools"
               :args ["sort" "--threads" "8"]}
         :st3 {:type :tool
               :path "samtools"
               :args ["index" "-" "#6"]}
         :cl1 {:type "func"
               :name "write-bam"
               :args ["#5"]}
         :edges {:bt2 [:mmap]
                 :bt1 [:st1] :st1 [:st2] :st2 [:cl1 :st3]}}

 ;; instructional data used in /help
 :description "Process collapsed fastas from bowtie alignment, to bam conversion and map file making, to bam sort, to bam indexing, to bam write - all via streaming connections."
 }

Add support for Aerobio map file generation from streaming SAM


(ns circle.backend.aws-iam
  "fns for working with AWS Identity & Access Management"
  (:use [circle.aws-credentials :only (aws-credentials)])
  (:import com.amazonaws.services.identitymanagement.AmazonIdentityManagementClient
           com.amazonaws.services.identitymanagement.model.UploadServerCertificateRequest
           com.amazonaws.services.identitymanagement.model.GetServerCertificateRequest))

(defmacro with-iam-client
  [client & body]
  `(let [~client (AmazonIdentityManagementClient. aws-credentials)]
     ~@body))

(defn upload-certificate
  "Uploads an SSL certificate. cert is the certificate public key, it
  begins with ---BEGIN CERTIFICATE---. priv key begins with --BEGIN
  RSA PRIVATE KEY--- "
  [{:keys [name certificate private-key]}]
  (with-iam-client client
    (let [result (.uploadServerCertificate client (UploadServerCertificateRequest. name certificate private-key))]
      (.getServerCertificateMetadata result))))

(defn get-certificate [name]
  (with-iam-client client
    (-> client (.getServerCertificate (GetServerCertificateRequest. name)) (.getServerCertificate) (bean) (update-in [:serverCertificateMetadata] bean))))

Add missing file that should have been committed months ago. Adds fns for uploading SSL certificates to AWS, useful for creating SSL load balancers at the repl


(ns org.spootnik.cyanite.path
  "Implements a path store which tracks metric names. The
   default implementation provides lucene based implementations"
  (:require [clucy.core                  :as search]
            [clojure.tools.logging       :refer [error info debug]]))

(defprotocol Pathstore
  "The pathstore provides a way to insert paths and later look them up"
  (register [this tenant path])
  (search [this tenant path]))

(defn lucene-pathstore
  [index]
  (reify Pathstore
    (register [this tenant path]
      (search/add index {:tenant tenant :path path}))
    (search [this tenant path]
      (let [query (format "tenant:'%s' path:'%s'" tenant path)]
        (->> (loop [init []
                    page 0]
               (let [paths (map :path (search/search index query 1000000
                                                     :page page
                                                     :results-per-page 100))]

                 (if (< (count paths) 100)
                   (concat init paths)
                   (recur (concat init paths) (inc page))))))))))

(defn lucene-memory-pathstore
  [_]
  (lucene-pathstore (search/memory-index)))

(defn lucene-file-pathstore
  [{:keys [path]}]
  (lucene-pathstore (search/disk-index path)))

Add a metric name index protocol and implementation

This is based on lucene and provides both an in-memory
and on-disk implementation


(ns vip.data-processor.validation.v5-test
  (:require  [clojure.test :refer :all]
             [vip.data-processor.pipeline :as pipeline]
             [vip.data-processor.db.postgres :as psql]
             [vip.data-processor.validation.xml :as xml]
             [vip.data-processor.test-helpers :refer :all]
             [vip.data-processor.validation.v5 :as v5]))

(use-fixtures :once setup-postgres)
(use-fixtures :each with-clean-postgres)

(deftest ^:postgres full-good-v5-test
  (let [ctx {:input (xml-input "v5_sample_feed.xml")
             :pipeline (concat [psql/start-run
                                xml/load-xml-ltree]
                               v5/validations)}
        out-ctx (pipeline/run-pipeline ctx)]
    (assert-no-problems out-ctx [])))

Test the v5 sample feed against all validaitons


(ns app-macros.view-test
  (:require [cljs.test :refer-macros [deftest is]]
            [om.next :as om]
            [app-macros.view :refer-macros [defview]]))

(defview MinimalView)

(deftest minimal-view-works
  (and (is (not (nil? MinimalView)))
       (is (not (nil? minimal-view)))))

(defview MinimalViewWithKeyfn
  (keyfn [{:keys [foo]}] (str foo "-baz")))

(deftest minimal-view-with-key-fn-works
  (and (is (not (nil? MinimalViewWithKeyfn)))
       (is (not (nil? minimal-view-with-keyfn)))
       (is (not (nil? minimal-view-with-keyfn-keyfn)))
       (is (= "bar-baz" (minimal-view-with-keyfn-keyfn {:foo "bar"})))))

(defview ViewWithQuery
  (query [this]
    [:foo :bar]))

(deftest view-with-query-works
  (is (= [:foo :bar] (om/get-query ViewWithQuery))))

(defview ViewWithProps
  [user [name email]]
  (ident [this props] [:user/by-name name])
  (get-name [this] name)
  (get-email [this] email))

(comment
  (deftest view-with-props-works
    (let [view (view-with-props {:user/name "Jeff"
                                 :user/email "jeff@jeff.org"})]
      (println (.-prototype (type view)))
      (println (.-om$isComponent view))
      (and (is (= "Jeff" (.get-name view)))
           (is (= "jeff@jeff.org" (.get-email view))))))

  (cljs.pprint/pprint
   (macroexpand-1
    '(defview ViewWithProps
       [user [name email]]
       (ident [this props] [:user/by-name name])
       (get-name [this] name)
       (get-email [this] email)))))

Add a few basic tests for the defview macro


(ns snippets.color.setting
  (:require [quil.snippet :refer [defsnippet]]
            [quil.core :refer :all]))

(defsnippet background-s {}
  (background 255 0 0)
  (let [gr (create-graphics 100 100)]
    (with-graphics gr
      (background 120))
    (image gr 0 0)

    (with-graphics gr
      (background 70 120))
    (image gr 70 70)

    (with-graphics gr
      (background 0 255 255))
    (image gr 140 140)

    (with-graphics gr
      (background 0 0 255 120))
    (image gr 210 210)))

(defsnippet background-image-s {}
  (let [gr (create-graphics (width) (height))]
    (with-graphics gr
      (background 0 120 120)
      (ellipse 250 250 300 300))

    (background-image gr)))

(defsnippet fill-s {}
  (background 0 0 255)

  (fill 120)
  (rect 0 0 100 100)

  (fill 80 120)
  (rect 70 70 100 100)

  (fill 0 255 0)
  (rect 140 140 100 100)

  (fill 255 0 0 120)
  (rect 210 210 100 100))

(defsnippet no-fill-s {}
  (background 255)

  (stroke 0)
  (fill 120)
  (rect 0 0 100 100)

  (no-fill)
  (rect 70 70 100 100))

(defsnippet no-stroke-s {}
  (background 255)

  (fill 120)
  (stroke 0)
  (rect 0 0 100 100)

  (no-stroke)
  (rect 70 70 100 100))

(defsnippet stroke-s {}
  (background 255)
  (stroke-weight 10)

  (stroke 120)
  (rect 0 0 100 100)

  (stroke 80 120)
  (rect 70 70 100 100)

  (stroke 0 255 0)
  (rect 140 140 100 100)

  (stroke 255 0 0 120)
  (rect 210 210 100 100))

Add Color - Setting snippets.

Add Color - Setting snippets.


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

(defn main []
  (loop [line (read-line)]
    (when line
      (let [[a b c] (str/split line #" ")
            a' (Integer/parseInt a)
            b' (Integer/parseInt b)
            c' (Integer/parseInt c)
            result (/ (+ (+ (Math/abs (- a' b')) b') a') 2)
            result (/ (+ (+ (Math/abs (- c' result)) result) c') 2)]
        (printf "%d eh o maior%n" result))
      (recur (read-line)))))

(main)

Solve The Greatest in clojure

Solve The Greatest in clojure


(ns onyx.static.pretty-print
  #?(:clj (:require [io.aviso.ansi :as a])))

(def bold
  #?(:clj a/bold
     :cljs identity))

(def magenta
  #?(:clj a/magenta
     :cljs identity))

(def blue
  #?(:clj a/blue
     :cljs identity))

(def bold-red
  #?(:clj a/bold-red
     :cljs identity))

(def bold-green
  #?(:clj a/bold-green
     :cljs identity))

Add missing pretty print file.

Add missing pretty print file.


{:nodes
 {:ph2
  {:name "tnseq-phase2",
   :type "tool",
   :args []}
  :prn1 {:type "func",
         :name "prn"}},
 :edges
 {:ph2 [:prn1]}}

Add job flow for phase 2 tnseq

Add job flow for phase 2 tnseq


(ns onyx.state-extensions)

(defmulti initialise-log
  (fn [log-type event]
    log-type))

(defmulti close-log
  (fn [log]
    (type log)))

;; For onyx to implement
;; We can implement log storage for Kafka and maybe ZK (if small data is used and we gc)
(defmulti store-log-entries
  "Store state update [op k v] entries in a log"
  (fn [log event entries]
    (type log)))

(defmulti playback-log-entries
  "Read state update [op k v] entries from log"
  (fn [log event state apply-fn]
    (type log)))

(defmulti store-seen-ids
  "Store seen ids in a log. Ideally these will be timestamped for auto expiry"
  (fn [log event seen-ids]
    (type log)))

(defmulti playback-seen-ids
  "Read seen ids from a log"
  (fn [log event bucket-state apply-fn]
    (type log)))

Add state extensions State extensions are for a log type to implement for storage and playback of state commands


(ns cmr.common.background-jobs
  "Namespace for creating simple background jobs that run at a specified interval in a thread.
  For more complex requirements see the cmr.common.jobs namespace which use Quartz."
  (:require [cmr.common.lifecycle :as lifecycle]))

(defrecord BackgroundJob
  [
   ;; The job-function to run
   job-fn

   ;; The interval (in seconds) to run the job
   job-interval-secs

   ;; A reference to the thread to run the background job
   thread-ref]

  lifecycle/Lifecycle

  (start
    [this system]
    (when thread-ref (.interrupt thread-ref))
    (let [thread (Thread.
                   (fn []
                     (try
                      (while (not (.isInterrupted (Thread/currentThread)))
                        (job-fn)
                        (Thread/sleep (* 1000 job-interval-secs)))
                      (catch InterruptedException _))))
          ;; Have to set the thread reference before starting the thread otherwise interrupt fails
          updated-this (assoc this :thread-ref thread)]
      (.start (:thread-ref updated-this))
      updated-this))

  (stop
    [this system]
    (when thread-ref (.interrupt thread-ref))
    (assoc this :thread-ref nil)))

(defn create-background-job
  "Creates a background job using the provided job-fn and how often to run the job in seconds."
  [job-fn job-interval-secs]
  (->BackgroundJob job-fn job-interval-secs nil))

(comment
  (def counter (atom 1))
  (def job (create-background-job #(swap! counter inc) 0.1))
  (def job (lifecycle/start job nil))
  (def job (lifecycle/stop job nil))
  @counter)

CMR-3525: Add new simple background jobs namespace for running jobs


(ns newsfeed.integration.api
  (:require [midje.sweet :refer :all]
            [peridot.core :as p]
            [clojure.data.json :as json]
            [newsfeed.core :as nf]
            [newsfeed.api :as api]))

(facts "about 'api'"
       (let [app (p/session nf/app)]
         (fact "returns 200 on /ping"
               (get-in (p/request app "/ping") [:response :status]) => 200)
         (fact "returns 403 when no token given"
               (get-in (p/request app "/api") [:response :status]) => 403)
         (fact "returns 403 when invalid token given"
               (get-in (p/request app "/api" :headers {"X-Auth-Token" "invalid"}) [:response :status]) => 403)
         (fact "returns 404 when valid token given but invalid route"
               (get-in (p/request app "/api/404" :headers {"X-Auth-Token" "valid"}) [:response :status]) => 404
               (provided (contains? nf/tokens "valid") => true))
         (fact "returns 200 on /api/feeds when valid token given"
               (get-in (p/request app "/api/feeds" :headers {"X-Auth-Token" "valid"}) [:response :status]) => 200
               (provided (contains? nf/tokens "valid") => true
                         (api/get-feeds anything) => '()))))

Add integration tests for newsfeed service


; Eli Bendersky [http://eli.thegreenplace.net]
; This code is in the public domain.
(ns expression.protocols)

(defrecord Constant [value])
(defrecord BinaryPlus [lhs rhs])

(defprotocol Evaluatable
  (evaluate [this]))

(defprotocol Stringable
  (stringify [this]))

(extend-type Constant
  Evaluatable
    (evaluate [this] (:value this))
  Stringable
    (stringify [this] (str (:value this))))

(extend-type BinaryPlus
  Evaluatable
    (evaluate [this] (+ (evaluate (:lhs this)) (evaluate (:rhs this))))
  Stringable
    (stringify [this]
      (clojure.string/join " + " [(stringify (:lhs this))
                                  (stringify (:rhs this))])))

; Also have an alternative to use extend-protocol here...
; the core is 'extend' - a true matrix of type/op

(def c1 (Constant. 1.1))
(def c2 (Constant. 2.2))
(def p1 (BinaryPlus. c1 c2))
(def p2 (BinaryPlus. p1 c2))

(evaluate p2)
(stringify p2)

; "Adding" a new data type - the built-in double type and showing how to extend
; all protocols for it.
(extend-type java.lang.Double
  Evaluatable
    (evaluate [this] this)
  Stringable
    (stringify [this] (str this)))

(def f1 11.5)
(def p3 (BinaryPlus. c1 f1))

(evaluate p3)
(stringify p3)

Add a basic working example in Clojure

Add a basic working example in Clojure


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

(ns bytebuf.core-tests
  (:require [clojure.test :refer :all]
            [bytebuf.core :as buf]))

(deftest allocate
  (testing "Allocate heap buffer."
    (let [buffer (buf/allocate 16)]
      (is (not (.isDirect buffer)))))

  (testing "Allocate direct buffer"
    (let [buffer (buf/allocate 16 {:type :direct})]
      (is (.isDirect buffer))))
)

Add test directory with initial tests.

Add test directory with initial tests.


(ns radicalzephyr.boot-junit
  {:boot/export-tasks true}
  (:require [boot.core :as core])
  (:import org.junit.runner.JUnitCore))

(deftask junit
  "Run the jUnit test runner."
  []
  (with-pre-wrap fileset
    (let [result (JUnitCore/runClasses
                  (into-array [#_ (magic goes here to find all test classes)]))]
      (when (> (.getFailureCount result) 0)
        (throw (ex-info "There were some test failures." {:result result}))))
    fileset))

Add the stub of the junit task

Add the stub of the junit task


(ns discuss.find
  (:require [clojure.walk :refer [keywordize-keys]]
            [om.core :as om :include-macros true]
            [om.dom :as dom :include-macros true]
            [discuss.communication :as com]
            [discuss.lib :as lib]))

(def data (atom {}))

(defn statement-handler
  "Called when received a response in the search."
  [response]
  (let [res (lib/json->clj response)
        values (:values res)
        error (:error res)]
    (if (pos? (count error))
      (lib/error-msg! error)
      (do
        (lib/no-error!)
        (swap! data assoc :foo (keywordize-keys res))
        (println res)
        (println values)
        (println (get "values" res))
        ))))

(defn statement
  "Find related statements to given keywords."
  [keywords]
  (com/ajax-get "api/get/statements/1/3/a" {} statement-handler))

(defn item-view []
  (reify om/IRender
    (render [_]
      (dom/div nil "One element"))))

(defn view []
  (reify om/IRender
    (render [_]
      (dom/h4 nil "Hello World!"))))

Prepare statement query to dbas

Prepare statement query to dbas


{:nodes
 {:ph2
  {:name "tnseq-final-aggregate",
   :type "tool",
   :args []}
  :prn1 {:type "func",
         :name "prn"}},
 :edges
 {:ph2 [:prn1]}}

Add super(aka global or final) aggregation job flow


;;   Copyright (c) Reid McKenzie, Rich Hickey & contributors. The use
;;   and distribution terms for this software are covered by the
;;   Eclipse Public License 1.0
;;   (http://opensource.org/licenses/eclipse-1.0.php) which can be
;;   found in the file epl-v10.html at the root of this distribution.
;;   By using this software in any fashion, you are agreeing to be
;;   bound by the terms of this license.  You must not remove this
;;   notice, or any other, from this software.

(ns oxcart.passes.emit-clj
  {:doc "Implements an ast to source return emitter designed to be run
         after other transformations for verification of output."
   :added "0.0.4"
   :author "Reid McKenzie"}
  (:require [clojure.tools.analyzer.passes.jvm.emit-form :as emit]
            [oxcart.passes.util :as util]))

(defn emit-clojure
  "λ Whole-AST → options → (Seq Form)

  Uses tools.analyzer.jvm to emit Clojure code from a whole program
  AST. Inteded for use in debugging and verifying output, as well as
  for rebuilding and re-analyzing programs in between syntax level
  passes.

  options:
    At present there are no options accepted by this pass."
  [{:keys [modules] :as whole-ast} options]
  (->> whole-ast
       util/whole-ast->forms
       (map emit/emit-form)))

Add AST to form emission pass

Add AST to form emission pass


(ns vip.data-processor.db.sqlite-test
  (:require [vip.data-processor.db.sqlite :as sqlite]
            [clojure.test :refer :all]
            [vip.data-processor.validation.data-spec.v3-0 :as v3-0]))

(deftest column-names-test
  (let [db (sqlite/temp-db "column-names-test" "3.0")]
    (is (= ["state_id" "early_vote_site_id"]
           (sqlite/column-names (-> db :tables :state-early-vote-sites))))))

Add a test for sqlite/column-names

Add a test for sqlite/column-names

The upcoming korma update broke the original version of this fn, so I added a test first.


(ns main
  (:require [clojure.string :as string]))

(def notas [10000.0 5000.0 2000.0 1000.0 500.0 200.0])
(def coins [100.0 50.0 25.0 10.0 5.0 1.0])

(defn print-result [value currencies currency-type]
  (println (str (string/upper-case currency-type) "S:"))
  (loop [value value
         [currency & remaining-currencies] currencies]
    (let [quantity (quot value currency)]
      (printf
       "%.0f %s(s) de R$ %.2f%n"
       quantity
       currency-type
       (with-precision 2 (/ currency 100.0))))
    (if (seq remaining-currencies)
      (recur (mod value currency) remaining-currencies)
      (mod value currency))))

(defn main []
  (loop [line (read-line)]
    (when line
      (let [value (-> line
                      (Double/parseDouble))]
            (-> (* value 100)
                (print-result notas "nota")
                (print-result coins "moeda"))
        (recur (read-line))))))

(main)

Solve Banknotes and Coins in clojure

Solve Banknotes and Coins in clojure


(ns desdemona.cli-test
  (:require
   [desdemona.launcher.aeron-media-driver :as aeron]
   [clojure.test :refer [deftest testing is]])
  (:import
   [java.io StringWriter]))

(def fake-block-forever!
  (constantly ::blocked-forever))

(defn fake-exit
  [status]
  [::exited status])

(defmacro with-fake-launcher-side-effects
  "Runs body with a fake exit, block-forever! and stdout.

  This assumes you're using com.gfredericks.system-slash-exit, because
  it's _way_ easier to mock out than the alternative.

  Returns [body-value stdout]. If it would have blocked forever, body-value
  will be ::blocked-forever. If it would have exited, body-value will
  be [::exited status]."
  [& body]
  `(with-redefs [com.gfredericks.system-slash-exit/exit fake-exit
                 desdemona.launcher.utils/block-forever! fake-block-forever!]
     (let [stdout# (StringWriter.)]
       (binding [*out* stdout#]
         (let [result# ~@body]
           [result# (str stdout#)])))))

(deftest aeron-main-tests
  "Tests for the aeron-media-driver main."
  (testing "usage"
    (let [[result stdout] (with-fake-launcher-side-effects
                            (aeron/-main "--help"))]
      (is (= result 0))
      (is (= stdout nil)))))

Add basic test structure + failing test

Add basic test structure + failing test


(ns konserve.konserve-test
  (:require [cljs.test :refer [run-tests]]
            [konserve.filestore-test]
            [konserve.serializers-test]))

(run-tests 'konserve.filestore-test
           'konserve.serializers-test)

Add cljs konserve main test.

Add cljs konserve main test.


(ns doctopus.files.predicates
  "We've got a loooot of filtering to do.

  Like, a lot.")

(defmulti is-type?
  "Returns true if the type of the file matches the type given."
  (fn [fobj regex] (class fobj)))

(defmethod is-type? java.lang.String
  [file-string type-regex]
  (if (re-find type-regex file-string)
    true
    false))

(defmethod is-type? java.io.File
  [file-handle type-regex]
  (is-type? (.getPath file-handle) type-regex))

(defn markdown?
  "returns true only for type files."
  [file-handle]
  (is-type? file-handle #"(?i)md|markdown|mdown$"
            ))

(defn restructured-text?
  "returns true only for type files."
  [file-handle]
  (is-type? #"(?i)rst|rest$" (.getPath file-handle)
            ))

Move the predicate functions in to their own ns -- it seems likely that we'll wind up with a bunch of these. Also, remove the note about expecting a java.io.File from the docstrings -- our schmancy multimethod `is-type` obviates that.


{:user {:plugins [[lein-try "0.4.1"]
                  [lein-pprint "1.1.1"]
                  [cider/cider-nrepl "0.7.0"]]}}

Add leiningen `:user` profile file

Add leiningen `:user` profile file


(ns main)

(defn main []
  (let [h (-> (read-line) (Double/parseDouble))
        s (-> (read-line) (Double/parseDouble))]
    (printf "%.3f%n" (/ (* h s) 12))))

(main)

Solve Fuel Spent in clojure

Solve Fuel Spent in clojure


;; This Source Code Form is subject to the terms of the Mozilla Public
;; License, v. 2.0. If a copy of the MPL was not distributed with this
;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
;;
;; Copyright (c) 2016 Andrey Antukh <niwi@niwi.nz>

(ns uxbox.util.dom.files
  "A interop helpers for work with files."
  (:require [beicon.core :as rx]
            [cuerdas.core :as str]))

(defn- read-as-dataurl
  [file]
  (rx/create
   (fn [sick]
     (let [fr (js/FileReader.)]
       (aset fr "onload" #(sick (rx/end (.-result fr))))
       (.readAsDataURL fr file))
     (constantly nil))))

(defn- retrieve-image-size
  [data]
  (println "data:" data)
  (rx/create
   (fn [sick]
     (let [img (js/Image.)]
       (aset img "onload" #(sick (rx/end [(.-width img) (.-height img)])))
       (set! (.-src img) data))
     (constantly nil))))

(defn get-image-size
  "Get the real image size."
  [file]
  (->> (read-as-dataurl file)
       (rx/flat-map retrieve-image-size)))

Add utils for work with dom file like objects.


(ns subman.t-routes
  (:require [midje.sweet :refer [fact => truthy]]
            [subman.routes :as routes]))

(fact "routes should be ok"
      routes/main-routes => truthy)

Add simple test for routes

Add simple test for routes


;; This Source Code Form is subject to the terms of the Mozilla Public
;; License, v. 2.0. If a copy of the MPL was not distributed with this
;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
;;
;; Copyright (c) 2016 Andrey Antukh <niwi@niwi.nz>

(ns uxbox.images
  "Image postprocessing."
  (:require [storages.core :as st]
            [uxbox.media :as media]
            [uxbox.util.paths :as paths]
            [uxbox.util.images :as images]
            [uxbox.util.data :refer (dissoc-in)]))

(defn make-thumbnail
  [path {:keys [size format quality] :as cfg}]
  (let [parent (paths/parent path)
        [filename ext] (paths/split-ext path)

        suffix-parts [(nth size 0) (nth size 1) quality format]
        final-name (apply str filename "-" (interpose "." suffix-parts))
        final-path (paths/path parent final-name)

        images-storage media/images-storage
        thumbs-storage media/thumbnails-storage]
    (if @(st/exists? thumbs-storage final-path)
      (str (st/public-url thumbs-storage final-path))
      (let [datapath @(st/lookup images-storage path)
            content (images/thumbnail datapath cfg)
            path @(st/save thumbs-storage final-path content)]
        (str (st/public-url thumbs-storage path))))))

(defn populate-thumbnail
  [entry {:keys [src dst] :as cfg}]
  (let [src (if (vector? src) src [src])
        dst (if (vector? dst) dst [dst])]
    (assoc-in entry dst
              (make-thumbnail (get-in entry src) cfg))))

(defn populate-thumbnails
  [entry & settings]
  (reduce populate-thumbnail entry settings))

(defn populate-urls
  [entry storage src dst]
  (let [src (if (vector? src) src [src])
        dst (if (vector? dst) dst [dst])
        value (get-in entry src)
        url (str (st/public-url storage value))]
    (-> entry
        (dissoc-in src)
        (assoc-in dst url))))

Add the ability to populate objects with thumbnails and url resolved paths.


;; This Source Code Form is subject to the terms of the Mozilla Public
;; License, v. 2.0. If a copy of the MPL was not distributed with this
;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
;;
;; Copyright (c) 2016 Andrey Antukh <niwi@niwi.nz>

(ns uxbox.util.mixins
  (:require [rum.core :as rum]
            [sablono.compiler :as s]))

(defn- parse-defc
  [args]
  (loop [r {}
         s 0
         v (first args)
         n (rest args)]
    (case s
      0 (if (symbol? v)
          (recur (assoc r :name v) (inc s) (first n) (rest n))
          (throw (ex-info "Invalid" {})))
      1 (if (string? v)
          (recur (assoc r :doc v) (inc s) (first n) (rest n))
          (recur r (inc s) v n))
      2 (if (map? v)
          (if-let [mixins (:mixins v)]
            (let [spec (dissoc v :mixins)
                  mixins (if (empty? spec)
                           mixins
                           (conj mixins spec))]
              (recur (assoc r :mixins mixins) (inc s) (first n) (rest n)))
            (recur (assoc r :mixins [v]) (inc s) (first n) (rest n)))
          (recur r (inc s) v n))
      3 (let [sym (:name r)
              func `(fn ~sym ~v ~(s/compile-html `(do ~@n)))]
          [func (:doc r) (:mixins r) sym]))))

(defmacro defc
  [& args]
  (let [[render doc mixins cname] (parse-defc args)]
    `(def ~cname ~doc (rum/build-defc ~render ~mixins ~(str cname)))))

Add own defc macro for more easy define components with less boilerplate.


(ns clj-gatling.core-test
  (:require [clojure.test :refer :all]
            [clj-gatling.test-helpers :refer :all]
            [clj-containment-matchers.clojure-test :refer :all]
            [clj-gatling.core :refer [run run-simulation]]
            [clj-async-test.core :refer :all]
            [clojure.core.async :refer [go <! <!! timeout]]
            [clj-time.core :as time]))

(use-fixtures :once setup-error-file-path)

(def legacy-scenario
  {:name "Test scenario"
   :context {}
   :requests [{:name "Request1" :fn successful-request}
              {:name "Request2" :fn failing-request}]})

(def simulation
  {:name "Test simulation"
   :scenarios [{:name "Test scenario"
                :steps [(step "Step1" true)
                        (step "Step2" false)]}]})

(deftest legacy-simulation-returns-summary
  (let [summary (run-simulation [legacy-scenario] 1 {})]
    (is (= {:ok 1 :ko 1} summary))))

(deftest simulation-returns-summary
  (let [summary (run simulation {:concurrency 1})]
    (is (= {:ok 1 :ko 1} summary))))

Add smoke tests for core entrypoint functionss


;; See: https://clojuredocs.org/clojure.test/deftest
(ns cjapplied.ch08)
(use 'clojure.test)

(deftest addition
  (is (= 4 (+ 2 2)))
  (is (= 7 (+ 3 4))))

(deftest subtraction
  (is (= 1 (- 4 3)))
  (is (= 3 (- 7 4))))

;; composing tests
(deftest arithmetic
  (addition)
  (subtraction))

(deftest test-range
  (is (= '(0 1 2 3 4) (range 5))))

(run-tests 'cjapplied.ch08)
;; {:test 6, :pass 9, :fail 0, :error 0, :type :summary}

(run-all-tests) ;;
{:test 9, :pass 10, :fail 1, :error 1, :type :summary}

Add sample from Clojure Applied

Add sample from Clojure Applied


(ns parse-names.core
  (:require [parse-names.vendor :as v]))

(defn parse-name [name]
  (let [name-obj (v/parse name)]
    (->> {:first-name (.-firstName name-obj)
          :last-name (.-lastName name-obj)
          :leading-initial (.-salutation name-obj)
          :suffix (.-suffix name-obj)
          :middle-name (.-initials name-obj)}
         (filter (fn [[k v]] (not (empty? v))))
         (into {}))))

Add cljs wrapper on vendor

Add cljs wrapper on vendor


(ns doctopus.web-test
  (:require [clojure.edn :as edn]
            [clojure.java.io :as io]
            [clojure.test :refer :all]
            [compojure.core :refer [context]]
            [doctopus.configuration :refer [docs-uri-prefix]]
            [doctopus.db :as db]
            [doctopus.doctopus.head :as h]
            [doctopus.doctopus :refer [->Doctopus load-routes bootstrap-heads]]
            [doctopus.doctopus.tentacle :as t]
            [doctopus.test-database :refer [schema-only-fixture]]
            [doctopus.test-utilities :as utils]
            [doctopus.web :as web]))

(use-fixtures :once schema-only-fixture)

(def test-map-props
  (h/parse-tentacle-config-map
   (edn/read-string (slurp (io/resource "test/heads/test/doctopus-test.edn")))))

(def one-head (h/map->Head {:name "test"}))
(def one-tentacle (t/map->Tentacle test-map-props))
(def stunt-doctopus (->Doctopus {} {}))

(deftest document-routes-test
  (db/save-head! one-head)
  (db/save-tentacle! one-tentacle)
  (db/create-mapping! one-head one-tentacle)
  (bootstrap-heads stunt-doctopus)
  (testing "Doctopus document routes"
    (let [ctx-str (str "/" docs-uri-prefix)
          routes (context ctx-str [] (load-routes stunt-doctopus))
          response (utils/fake-request routes :get "/docs/doctopus-test/index.html")]
      (is (utils/truthy? (:body response)))
      (is (= "text/html" ((:headers response) "Content-Type")))
      (is (= 200 (:status response))))))

(deftest routes-test
  (testing "Tests against base, unwrapped doctopus-routes"
    (let [routes (web/create-application web/doctopus-routes)
          requester (partial utils/fake-request routes)]
      (is (= 200 (:status (requester :get "/"))))
      (is (= 200 (:status (requester :get "/index.html"))))
      (is (= 200 (:status (requester :get "/heads"))))
      (is (= 200 (:status (requester :get "/heads/doctopus-test"))))
      (is (= 200 (:status (requester :get "/add-head"))))
      (is (= 200 (:status (requester :get "/add-tentacle"))))
      ;; These two 403. Huh. Not... perfectly sure what to do.
      ;; (is (= 200 (:status (requester :post "/add-tentacle"))))
      ;; (is (= 200 (:status (requester :post "/add-head"))))
      )))

Add web NS tests, mostly for routes

Add web NS tests, mostly for routes


(ns user
  (:require [clojars
             [config :as config]
             [errors :as errors]
             [system :as system]]
            [clojars.db.migrate :as migrate]
            [clojure.java.io :as io]
            [clojure.tools.namespace.repl :refer [refresh]]
            [eftest.runner :as eftest]
            [meta-merge.core :refer [meta-merge]]
            [reloaded.repl :refer [system init stop go clear]]))

(def dev-env
  {:app {:middleware []}})

(defn new-system []
  (refresh)
  (config/configure [])
  (assoc (system/new-system (meta-merge config/config dev-env))
         :error-reporter (errors/->StdOutReporter)))

(ns-unmap *ns* 'test)

(defn reset []
  (if system
    (do (clear)
        (go))
    (refresh)))

(defn test [& tests]
  (let [tests (if (empty? tests)
                  (eftest/find-tests "test")
                  tests)]
        (eftest/run-tests tests {:report eftest.report.pretty/report
                                 :multithread? false})))

(when (io/resource "local.clj")
  (load "local"))

(defn migrate []
  (migrate/migrate (:db config/config)))

;; TODO: function to setup fake data (from clojars.dev.setup?)

(reloaded.repl/set-init! new-system)

(ns user
  (:require [clojars
             [cloudfiles :as cf]
             [config :as config]
             [errors :as errors]
             [system :as system]]
            [clojars.db.migrate :as migrate]
            [clojure.java.io :as io]
            [clojure.tools.namespace.repl :refer [refresh]]
            [eftest.runner :as eftest]
            [meta-merge.core :refer [meta-merge]]
            [reloaded.repl :refer [system init stop go clear]]))

(def dev-env
  {:app {:middleware []}})

(defn new-system []
  (refresh)
  (config/configure [])
  (assoc (system/new-system (meta-merge config/config dev-env))
    :error-reporter (errors/->StdOutReporter)
    :cloudfiles (cf/connect "" "" "dev" "transient")))

(ns-unmap *ns* 'test)

(defn reset []
  (if system
    (do (clear)
        (go))
    (refresh)))

(defn test [& tests]
  (let [tests (if (empty? tests)
                  (eftest/find-tests "test")
                  tests)]
        (eftest/run-tests tests {:report eftest.report.pretty/report
                                 :multithread? false})))

(when (io/resource "local.clj")
  (load "local"))

(defn migrate []
  (migrate/migrate (:db config/config)))

;; TODO: function to setup fake data (from clojars.dev.setup?)

(reloaded.repl/set-init! new-system)

Add in-memory cloudfiles connection to the dev system


(ns subman.t-search
  (:require-macros [purnam.test.sweet :refer [facts fact]])
  (:require [reagent.core :refer [atom]]
            [subman.helpers :refer [truthy]]
            [subman.search :as search]))

(facts "should create search request"
       (fact "with query"
             (search/create-search-request "test") => "/api/search/?query=test")
       (fact "with query and lang"
             (search/create-search-request
              "test :lang ru") => "/api/search/?query=test&lang=ru"))

(fact "watch to query should be ok"
      (search/watch-to-query (atom "")
                             (atom [])
                             (atom 0)) => truthy)

Add simple tests for search

Add simple tests for search


; Use refs to create a vector of accounts in memory. Create debit and credit functions to change the balance of an account.
(def accounts (ref [0 0 0]))

(defn balance
  [accounts index]
  (nth @accounts index))

(defn debit
  [accounts index amount]
  (dosync (alter accounts assoc index (- (balance accounts index) amount))))

(defn credit
  [accounts index amount]
  (dosync (alter accounts assoc index (+ (balance accounts index) amount))))

Add clojure day 3 basic

Add clojure day 3 basic


(ns decktouch.mtg-card-master
  (:require [clojure.data.json :as json]))

(def mtg-cards (json/read-str (slurp "resources/AllCards.json")))

(def card-names (keys mtg-cards))

(defn match
  "Returns true if query is a substring in string"
  [query string]
  (some? (re-matches (re-pattern (str "(?i)" query ".*"))
                    string)))

(defn get-cards-matching-query
  "Return a list of maps of strings of card names that match the query for the card input autocomplete"
  [query]
  (let [match-query (partial match query)]
      (map (fn [thing] {:cardName thing})
        (filter match-query card-names))))

Add mtg card master namespace

Add mtg card master namespace


(ns cljam.io.vcf.reader-test
  (:require [clojure.test :refer [deftest is]]
            [cljam.io.vcf.reader :as vcf-reader]))

(deftest parse-structured-line-test
  (is (= {:id "ID", :description "\"This\" is a description",
          :note "You can use \" in string fields by escaping it with \\"}
       (#'vcf-reader/parse-structured-line "ID=ID,Description=\"\\\"This\\\" is a description\",Note=\"You can use \\\" in string fields by escaping it with \\\\\"")))
  (is (thrown-with-msg? RuntimeException
                        #"Unexpected end of string field"
                        (#'vcf-reader/parse-structured-line "x=\"unbalanced double quote")))
  (is (thrown-with-msg? RuntimeException
                        #"Either '\\' or '\"' was expected immediately after '\\', but got 'x'"
                        (#'vcf-reader/parse-structured-line "x=\"unknown \\x escape sequence\""))))

Add tests for character escaping for VCF string fields


Add test case for cljam.cigar

Add test case for cljam.cigar


(defproject cryogen "0.1.0"
            :description "Simple static site generator"
            :url "https://github.com/lacarmen/cryogen"
            :license {:name "Eclipse Public License"
                      :url "http://www.eclipse.org/legal/epl-v10.html"}
            :dependencies [[org.clojure/clojure "1.6.0"]
                           [ring/ring-devel "1.3.2"]
                           [compojure "1.3.1"]
                           [ring-server "0.3.1"]
                           [cryogen-core "0.1.8"]]
            :plugins [[lein-ring "0.8.13"]]
            :main cryogen.core
            :ring {:init cryogen.server/init
                   :handler cryogen.server/handler})

(defproject cryogen "0.1.0"
            :description "Simple static site generator"
            :url "https://github.com/lacarmen/cryogen"
            :license {:name "Eclipse Public License"
                      :url "http://www.eclipse.org/legal/epl-v10.html"}
            :dependencies [[org.clojure/clojure "1.6.0"]
                           [ring/ring-devel "1.3.2"]
                           [compojure "1.3.1"]
                           [ring-server "0.3.1"]
                           [cryogen-core "0.1.9"]]
            :plugins [[lein-ring "0.8.13"]]
            :main cryogen.core
            :ring {:init cryogen.server/init
                   :handler cryogen.server/handler})

Update cryogen-core dependency to 0.1.9.


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

(def url "https://docs.google.com/spreadsheets/d/1XMCStIcX-UkJF2YYmco7mnoSec8I8Vg_1wSSAVR7L00/export?format=csv")

(def input (slurp url))
(def entries (str/split input #"\n"))
(def an-entry (-> (str/split input #"\n")
                  (get 2)))

;; Helpers
;; =======
(defn- unicode-bool
  "Returns true if val is a unicode checkmark"
  [val]
  (= "✔" val))

(defn- update-fields
  "Applies f to each value of fields"
  [coll f fields]
  (reduce #(update %1 %2 f) coll fields))

;; Entry parsing
;; ===========
(defn split-entry
  "Splits the entry in an array of values"
  [csv-line]
  (drop 1 (str/split csv-line #",")))

(defn pedal
  "Builds a pedal hash-map from the values array"
  [values]
  (zipmap [:brand :model :distributor :isolator :adapter :comment] values))

(defn parse-boolean-fields
  "Updates :distributor, :isolator and :adapter to be proper booleans"
  [entry]
  (update-fields entry unicode-bool [:distributor :isolator :adapter]))

;; Parsing all the data
(defn parse-entries
  "Transforms all entries into pedals"
  [entries]
  (map #(-> (str/trim %)
            split-entry
            pedal
            parse-boolean-fields)
       entries))

(defn write-to-file
  "Writes the output to the data.cljs file"
  [entries]
  (spit
   "./gigrig/src/gigrig/data.cljs"
   (with-out-str
     (println "(ns gigrig.data)")
     (println "(defonce data")
     (pr entries)
     (println ")"))))

(defn -main []
  (-> (slurp url)
      (str/split #"\n")
      (#(drop 2 %))
      parse-entries
      write-to-file))

Write scraper for pedals db

Write scraper for pedals db


(ns doctopus.files-test
  (:require [doctopus.files :refer :all]
            [clojure.test :refer :all]))

(deftest test-truncate-str
  (testing "Can we truncate one path by removing another path from the front?"
    (let [fq "/foo/bar/baz/bing/bang/document.markdown"
          remove-str "/foo/bar/baz/bing/"
          result (truncate-str fq remove-str)]
      (is (= result "bang/document.markdown")))))

Add our first test oh boy!

Add our first test oh boy!


(ns grafter.rdf.ontologies.ons-geography
  (:require [grafter.rdf.ontologies.util :refer :all]))

(def statistical-entity (prefixer "http://statistics.data.gov.uk/def/statistical-entity#"))
(def statistical-entity:name                 (statistical-entity "name"))
(def statistical-entity:abbreviation         (statistical-entity "abbreviation"))
(def statistical-entity:owner                (statistical-entity "owner"))
(def statistical-entity:coverage             (statistical-entity "coverage"))
(def statistical-entity:relatedentity        (statistical-entity "relatedentity"))
(def statistical-entity:status               (statistical-entity "status"))
(def statistical-entity:liveinstances        (statistical-entity "liveinstances"))
(def statistical-entity:archivedinstances    (statistical-entity "archivedinstances"))
(def statistical-entity:coverage             (statistical-entity "coverage"))
(def statistical-entity:firstcode            (statistical-entity "firstcode"))
(def statistical-entity:lastcode             (statistical-entity "lastcode"))
(def statistical-entity:reservedcode         (statistical-entity "reservedcode"))
(def statistical-entity:introduced           (statistical-entity "introduced"))
(def statistical-entity:lastinstancechange   (statistical-entity "lastinstancechange"))
(def statistical-entity:code                 (statistical-entity "code"))
(def statistical-entity:crossborderinstances (statistical-entity "crossborderinstances"))

(def statistical-geography (prefixer "http://statistics.data.gov.uk/def/statistical-geography#"))
(def statistical-geography:officialname      (statistical-entity "officialname"))
(def statistical-geography:status            (statistical-entity "status"))

(def boundary-change (prefixer "http://statistics.data.gov.uk/def/boundary-change/"))
(def boundary-change:operativedate           (boundary-change "operativedate"))
(def boundary-change:originatingChangeOrder  (boundary-change "originatingChangeOrder"))
(def boundary-change:terminateddate          (boundary-change "terminateddate"))
(def boundary-change:changeOrderTitle        (boundary-change "changeOrderTitle"))

Add Vocabulary (prefixers) for ONS/ Statistical Geography


(ns caesium.randombytes-test
  (:require [caesium.randombytes :as r]
            [clojure.test :refer [deftest is]]))

(deftest randombytes-tests
  (let [some-bytes (r/randombytes 10)]
    (is (= 10 (alength some-bytes)))))

Add a simple test for randombytes

Add a simple test for randombytes


(ns ^:figwheel-load word-finder.actions.call-server
  (:require [ajax.core :refer [GET]]))

(def server "http://localhost:8080/api/words/")

;;FIXME: the string interpolation can be easily broken.
(defn find-words [input-string callback]
  (GET (str server "find" "?find=" input-string)
      {:handler       callback
       :error-handler #(println "ERROR" %)}))

(defn find-anagrams [input-string callback]
  (GET (str server "anagrams" "?find=" input-string)
      {:handler       callback
       :error-handler #(println "ERROR!" %)}))

(defn find-sub-anagrams [input-string callback]
  (GET (str server "sub-anagrams" "?find=" input-string)
      {:handler callback}))

(ns ^:figwheel-load word-finder.actions.call-server
  (:require [ajax.core :refer [GET]]))

(def server "http://localhost:8080/api/words/")

(defn find-words
  "Call the server-side find-words, returning JSON"
  [input-string callback]
  (GET (str server "find")
      {:params        {:find input-string}
       :format        :json
       :handler       callback
       :error-handler #(println "ERROR" %)}))

(defn find-anagrams
  "Call the server-side find-anangrams, returning JSON"
  [input-string callback]
  (GET (str server "anagrams")
      {:params        {:find input-string}
       :format        :json
       :handler       callback
       :error-handler #(println "ERROR!" %)}))

(defn find-sub-anagrams
  "Call the server-side find-sub-anagrams, returning JSON"
  [input-string callback]
  (GET (str server "sub-anagrams")
      {:params        {:find input-string}
       :format        :json
       :handler       callback
       :error-handler #(println "ERROR!" %)}))

Fix the cljs server calls to use ajax.core :params

Instead of doing poor string interpolation, just use the library.


(ns hydrofoil.expectations.model
  (:require [expectations :refer :all]
            [hydrofoil.model :refer :all]
            [hydrofoil.core :refer :all]
            [hydrofoil.evolution :refer :all]))

;;; --------- Utils Tests ------------

Add Utils test file, don't have anything to put in it yet.


(ns clj-diff.test.performance
  (:use [clj-diff.core])
  (:use [clj-diff.performance] :reload)
  (:use [clojure.test]))

(deftest mutate-test
  (let [a "abcdefghijklmnopqrstuvwxyz"
        changes #(count (flatten (map rest (:+ %))))
        largest-group #(apply max (map count (map rest (:+ %))))]
    (is (<= (changes (diff a (mutate a 1 1)))
           1))
    (is (<= (changes (diff a (mutate a 2 1)))
            2))
    (is (<= (changes (diff a (mutate a 5 1)))
            5))
    (is (<= (changes (diff a (mutate a 5 5)))
            5))
    (is (<= (largest-group (diff a (mutate a 5 5)))
            5))
    (is (<= (changes (diff a (mutate a 10 5)))
            10))
    (is (<= (largest-group (diff a (mutate a 10 5)))
            5))))

Add unit test for mutate and update the charts.


(ns circle.admin.ebs
  (:require [org.jclouds.ec2.ebs2 :as ebs])
  (:require [circle.backend.ec2 :as ec2])
  (:use [circle.utils.except :only (throw-if-not)])
  (:use [circle.aws-credentials :only (jclouds-compute)]))

(defn default-volume [instance-id]
  (let [inst (ec2/instance instance-id)
        devices (map bean (-> inst :blockDeviceMappings))
        root-dev (-> inst :rootDeviceName)
        dev (first (filter #(not= root-dev (:deviceName %)) devices))]
    (-> dev :ebs (bean) :volumeId)))

(defn volume-from-id
  "returns a Volume from the id"
  [vol-id]
  (->>
   jclouds-compute
   (ebs/volumes)
   (filter #(= vol-id (.getId %)))
   (first)))

(defn take-snapshot
  "Create a snapshot of an EBS volume.
  ec2-id - and AWS instance id
  description -

  Options:
  vol-id - the vol-id. If not specified, uses the first non-root device.
   "
  [ec2-id description & {:keys [vol-id]}]
  (ebs/create-snapshot jclouds-compute (volume-from-id (or vol-id (default-volume ec2-id))) description))

(defn latest-snapshot
  "Returns the snapshot-id with matching description"
  [description]
  (->>
   (ebs/snapshots jclouds-compute :owner "self")
   (map bean)
   (filter #(= description (:description %)))
   (sort-by :startTime)
   (last)
   :id))

Add functions for interacting with EBS snapshots


(ns clojure-walkthrough.cjia.ch07-xx)
; 7.1: Macro basic

; 7.1.1: Textual substitution

(def a-ref (ref 0))

(dosync
 (ref-set a-ref 1)) ; 1

;; You could implement this using the macros like
; (syn-set a-ref 1)

(defmacro sync-set [r v]
  (list 'dosync
        (list 'ref-set r v)))

(sync-set a-ref 1) ;; 1

Add macro example from section 7.1

Add macro example from section 7.1


(ns cljs-nlp.stats.levenshtein
  (:use [clojure.string :only [blanks?]]))

(defn create-element
  [char1 char2 previous-row current-row idx]
  (if (= char1 char2)
    (previous-row (- idx 1))
    (+ 1 (min
      (previous-row (- idx 1))
      (previous-row idx)
      (last current-row)))))

(defn create-row
  [char1 str2 previous-row current-row]
  (let [char2 (first str2)
        idx (count current-row)]
    (if (= (count current-row) (count previous-row))
      current-row
      (recur
        char1
        (rest str2)
        previous-row
        (conj current-row (create-element char1 char2 previous-row current-row idx))))))

(defn levenshtein
  "Calculate the edit distance between two strings."
  ([str1 str2]
    (let [initial-row (vec (range (inc (count str2))))]
      (levenshtein 1 initial-row str1 str2)))
  ([row-no previous-row str1 str2]
    (let [next-row (create-row (first str1) str2 previous-row [row-no])
          rest-str1 (subs str1 1)]
      (if (blank? rest-str1)
        (last next-row)
        (recur (inc row-no) next-row rest-str1 str2)))))

Add ability to calculate edit distance.

Add ability to calculate edit distance.


(defproject onyx-app/lein-template "0.10.0.0-beta10"
  :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.10.0.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.


(ns grimoire.api.web-test
  (:require [grimoire.api :as api]
            [grimoire.things :as t]
            [grimoire.util :refer [succeed? result]]
            [grimoire.api.web.read]
            [clojure.test :refer :all]))

(def test-config
  {:datastore
   {:mode :web
    :host "http://127.0.0.1:3000"}}) ;; test against local Grimoire instance

;; Listing tests
;;------------------------------------------------------------------------------

(deftest list-groups-test
  (let [?res (-> test-config
                api/list-groups)]
    (is (succeed? ?res))
    (doseq [?g (result ?res)]
      (is (t/isa? :group ?g)))))

(deftest list-artifacts-test
  (let [g    (t/->Group "org.clojure")
        ?res (-> test-config
                (api/list-artifacts g))]
    (is (succeed? ?res))
    (doseq [?a (result ?res)]
      (is (t/isa? :artifact ?a)))))

(deftest list-versions-test
  (let [g    (t/->Group "org.clojure")
        a    (t/->Artifact g "clojure")
        ?res (-> test-config
                (api/list-versions a))]
    (is (succeed? ?res))
    (doseq [?v (result ?res)]
      (is (t/isa? :version ?v)))))

(deftest list-ns-test
  (let [v    (t/->Version "org.clojure" "clojure" "1.6.0")
        ?res (-> test-config
                (api/list-namespaces v))]
    (is (succeed? ?res))
    (doseq [?ns (result ?res)]
      (is (t/isa? :namespace ?ns)))))

(deftest list-prior-versions-test
  (let [ns   (t/->Ns "org.clojure" "clojure" "1.6.0" "clojure.core")
        ?res (-> test-config
                (api/thing->prior-versions ns))]
    (is (succeed? ?res))
    (is (= #{"1.6.0" "1.5.0" "1.4.0"}
           (->> ?res result (map (comp :name :parent)) set)))))

(deftest list-def-test
  (let [ns   (t/->Ns "org.clojure" "clojure" "1.6.0" "clojure.core")
        ?res (-> test-config
                (api/list-defs ns))]
    (is (succeed? ?res))
    (let [defs (->> ?res result (map :name) set)]
      (doseq [d ["for" "def" "let" "catch"]]
        (is (defs d))))))

Add tests of the Grimoire web API

Add tests of the Grimoire web API


(ns pathfinder.analyze.clojure-test
  (:use midje.sweet
        pathfinder.analyze.analyzer
        pathfinder.analyze.clojure))

(facts "about heuristic analysis"
       (fact "should keep the source"
             (analyze (->CljHeuristicAnalyzer) "foo" {}) => (contains {:source "foo"}))
       (fact "should keep the metadata"
             (analyze (->CljHeuristicAnalyzer) "foo" {:a :b}) => (contains {:meta {:a :b}}))
       (fact "should extract definitions"
             (:definitions (analyze (->CljHeuristicAnalyzer) "(defn foo [] 3)" {}))
             => (contains (contains {:name "foo"})))
       (fact "should extract definitions, namespaced"
             (:definitions (analyze (->CljHeuristicAnalyzer) "(ns test) (defn foo [] 3)" {}))
             => (contains (contains {:name "test/foo"}))))

Add tests for current clj heuristic analyzer


(ns com.nomistech.clojure-the-language.protocols-and-records-test
  (:require [midje.sweet :refer :all]))

;;;; ___________________________________________________________________________
;;;; ---- `defrecord` and what it gives you ----

(defrecord MyRecord [x y])

(fact "Simple constructor"
  (MyRecord. 1 2)
  => {:x 1 :y 2})

(fact "Constructor using metadata"
  (-> (MyRecord. 1 2 {:m-1 1 :m-2 2} nil)
      meta)
  => {:m-1 1 :m-2 2})

(fact "Constructor using extension data"
  (-> (MyRecord. 1 2 nil {:e-1 1 :e-2 2})
      :e-1)
  => 1)

(fact "->xxx factory function"
  (->MyRecord 1 2)
  => (MyRecord. 1 2))

(fact "map->xxx factory function"
  (map->MyRecord {:x 1 :y 2})
  => (MyRecord. 1 2))

;;;; ___________________________________________________________________________

Add protocols and records stuff.

Add protocols and records stuff.


(ns lazytest.reified-tests
  (:use (lazytest expect testable runnable-test)))

(def t1 (reify Testable
	       (get-tests [this]
			  (list
			   (reify RunnableTest
				  (run-tests [this]
					     (list
					      (try-expectations this
								(expect= 1 2)))))))))

(def t2 (reify Testable
	       (get-tests [this]
			  (list
			   (reify RunnableTest
				  (run-tests [this]
					     (list
					      (try-expectations this
								(expect= 1 1)))))))))

(def t3 (reify Testable
	       (get-tests [this]
			  (list
			   (reify RunnableTest
				  (run-tests [this]
					     (list
					      (try-expectations this
								(expect-instance java.lang.String :a)))))))))

(def t4 (reify Testable
	       (get-tests [this]
			  (list
			   (reify RunnableTest
				  (run-tests [this]
					     (list
					      (try-expectations this
								(expect-not= 1 1)))))))))

(def t5 (reify Testable
	       (get-tests [this]
			  (list
			   (reify RunnableTest
				  (run-tests [this]
					     (list
					      (try-expectations this
								(expect= (/ 1 0) 0)))))))))

(def t6 (reify Testable
	       (get-tests [this]
			  (list
			   (reify RunnableTest
				  (run-tests [this]
					     (list
					      (try-expectations this
								(expect (< 1 0))))))))))

Add reified-tests example source for testing at the REPL


(ns clojure-walkthrough.cjia.ch10-xx
  (:require [clojure.test :refer :all]
            [clojure-walkthrough.cjia.ch10-date-operations :refer :all]))

(deftest test-simple-data-parsing
  (let [d (date "2009-01-22")]
    (is (= (day-from d) 22))))

Add place holder for cjia

Add place holder for cjia


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

(defn main []
  (let [[x1 y1] (-> (read-line) (str/split #" "))
        [x2 y2] (-> (read-line) (str/split #" "))
        [x1' y1' x2' y2'] (map #(Double/parseDouble %) [x1 y1 x2 y2])]
    (printf "%.4f%n" (Math/sqrt (+ (Math/pow (- x2' x1') 2) (Math/pow (- y2' y1') 2))))))

(main)

Solve Distance Between Two Points in clojure


(ns main)

(defn main []
  (let [a (Double/parseDouble (read-line))
        b (Double/parseDouble (read-line))]
    (format "%.5f" (/ (+ (* a 3.5) (* b 7.5)) 11.0))))

(println "MEDIA =" (main))

Solve Average 1 in clojure

Solve Average 1 in clojure


(ns workflo.macros.entity-test
  (:require [clojure.spec :as s]
            [clojure.test :refer [deftest is]]
            [workflo.macros.entity :as e :refer [defentity]]))

(deftest minimal-defentity
  (is (= '(do
            (def macros-user-schema map?)
            (def macros-user-definition
              {:schema pod/macros-user-schema}))
         (macroexpand-1 `(defentity macros/user
                           (~'schema ~'map?))))))

(deftest defentity-with-validation
  (is (= '(do
            (def macros-user-validation
              (s/keys :req [:foo/bar]
                      :opt [:bar/baz]))
            (def macros-user-schema map?)
            (def macros-user-definition
              {:schema pod/macros-user-schema
               :validation pod/macros-user-validation}))
         (macroexpand-1 `(defentity macros/user
                           (~'validation
                             (~'s/keys :req [:foo/bar]
                                       :opt [:bar/baz]))
                           (~'schema ~'map?))))))

(deftest defentity-with-auth
  (is (= '(do
            (defn macros-user-auth
              [{:keys [foo bar]}]
              (println foo bar))
            (def macros-user-auth-query
              '[{:name foo :type :property}
                {:name bar :type :property}])
            (def macros-user-schema map?)
            (def macros-user-definition
              {:auth pod/macros-user-auth
               :auth-query pod/macros-user-auth-query
               :schema pod/macros-user-schema}))
         (macroexpand-1 `(defentity macros/user
                           ~'(auth [foo bar]
                             (println foo bar))
                           ~'(schema map?))))))

(deftest defentity-with-auth-and-validation
  (is (= '(do
            (defn macros-user-auth
              [{:keys [foo bar]}]
              (println foo bar))
            (def macros-user-auth-query
              '[{:name foo :type :property}
                {:name bar :type :property}])
            (def macros-user-validation
              (s/keys :req-un [::foo ::bar]))
            (def macros-user-schema map?)
            (def macros-user-definition
              {:auth pod/macros-user-auth
               :auth-query pod/macros-user-auth-query
               :validation pod/macros-user-validation
               :schema pod/macros-user-schema}))
         (macroexpand-1 `(defentity macros/user
                           ~'(auth [foo bar]
                                   (println foo bar))
                           ~'(validation
                               (s/keys :req-un [::foo ::bar]))
                           ~'(schema map?))))))

Add code generation tests for the defentity macro


(ns server.name-bazaar.utils
  (:require
    [cljs.core.async :refer [<! go]]
    [cljs.test :refer-macros [async]]
    [cljs-time.coerce :refer [from-long]]
    [cljs-web3-next.eth :as web3-eth]
    [cljs-web3-next.evm :as web3-evm]
    [cljs-web3-next.helpers :as web3-helpers]
    [district.server.web3 :refer [web3]]
    [district.shared.async-helpers :refer [promise->]]
    [mount.core :as mount]
    [taoensso.timbre :as log]))

(def snapshot-id (atom ""))

(def namehash (aget (js/require "eth-ens-namehash") "hash"))
(def sha3 (comp (partial str "0x") (aget (js/require "js-sha3") "keccak_256")))

(defn now []
  (promise-> (web3-eth/get-block-number @web3)
             #(web3-eth/get-block @web3 % false)
             (fn [block]
               (let [block (web3-helpers/js->cljkk block)]
                 (from-long (* (:timestamp block) 1000))))))

(defn before-test []
  (async done
    (go
      (-> (mount/with-args
            {:web3            {:url        "ws://127.0.0.1:8549"
                               :on-online  #(log/warn "Ethereum node went online")
                               :on-offline #(log/warn "Ethereum node went offline")}
             :smart-contracts {:contracts-build-path "./resources/public/contracts-build/"
                               :contracts-var        #'name-bazaar.shared.smart-contracts/smart-contracts
                               :auto-mining?         true}})
          (mount/only [#'district.server.web3
                       #'district.server.smart-contracts/smart-contracts])
          (mount/start))
      (let [id (<! (web3-evm/snapshot @web3))]
        (swap! snapshot-id (fn [_] id)))
      (done))))

(defn after-test []
  (async done
    (go
      ;; we'd like to use cljs-web3-next.evm/revert here, but it's broken now as:
      ;; 1. evm_revert doesn't accept 0 arguments even if it should:
      ;;    https://github.com/trufflesuite/ganache-cli/issues/672
      ;; 2. evm_revert is a non-standard method not explicitly supported in web3js
      ;; 3. there's a validator expecting by default any non-standard method to have 0 args
      ;; so we need to go more low level
      (js-invoke (aget @web3 "currentProvider")
                 "send"
                 (clj->js {:jsonrpc "2.0",
                           :method "evm_revert",
                           :params [@snapshot-id],
                           :id 1})
                 (fn [err _]
                   (if err (throw (js/Error. "Error evm_revert-ing to snapshot" err)))
                   (mount/stop)
                   (js/setTimeout #(done) 500))))))

Use snapshots to clear chain before test

Before, deployer was used to clear test blockchain state
before each test. Deployer is now gone, replaced with
truffle. I found it much faster to use ganache snapshotting
before / after each test, than to call truffle migrate.