Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Update nippy dependency to 2.9.0 | (defproject buddy/buddy-sign "0.6.0"
:description "High level message signing for Clojure"
:url "https://github.com/funcool/buddy-sign"
:license {:name "Apache 2.0"
:url "http://www.apache.org/licenses/LICENSE-2.0"}
:dependencies [[org.clojure/clojure "1.7.0" :scope "provided"]
[com.taoensso/nippy "2.8.0"]
[buddy/buddy-core "0.6.0"]
[cats "0.4.0"]
[clj-time "0.9.0"]
[cheshire "5.5.0"]]
:source-paths ["src"]
:javac-options ["-target" "1.7" "-source" "1.7" "-Xlint:-options"]
:test-paths ["test"])
| (defproject buddy/buddy-sign "0.6.0"
:description "High level message signing for Clojure"
:url "https://github.com/funcool/buddy-sign"
:license {:name "Apache 2.0"
:url "http://www.apache.org/licenses/LICENSE-2.0"}
:dependencies [[org.clojure/clojure "1.7.0" :scope "provided"]
[com.taoensso/nippy "2.9.0"]
[buddy/buddy-core "0.6.0"]
[cats "0.4.0"]
[clj-time "0.9.0"]
[cheshire "5.5.0"]]
:source-paths ["src"]
:javac-options ["-target" "1.7" "-source" "1.7" "-Xlint:-options"]
:test-paths ["test"])
|
Update dependencies and version info. | ;(defproject cli4clj "1.4.0"
(defproject cli4clj "1.4.1-SNAPSHOT"
:description "Create simple interactive CLIs for Clojure applications."
:url "https://github.com/ruedigergad/cli4clj"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:dependencies [[org.clojure/clojure "1.9.0"]
[clj-assorted-utils "1.18.2"]
[org.clojure/core.async "0.3.465"]
[jline/jline "2.14.5"]]
:global-vars {*warn-on-reflection* true}
:html5-docs-docs-dir "ghpages/doc"
:html5-docs-ns-includes #"^cli4clj.*"
:html5-docs-repository-url "https://github.com/ruedigergad/cli4clj/blob/master"
:test2junit-output-dir "ghpages/test-results"
:test2junit-run-ant true
:main cli4clj.example
:plugins [[lein-cloverage "1.0.2"] [test2junit "1.3.3"] [lein-html5-docs "3.0.3"]]
:profiles {:repl {:dependencies [[jonase/eastwood "0.2.5" :exclusions [org.clojure/clojure]]]}}
)
| (defproject cli4clj "1.5.0"
;(defproject cli4clj "1.5.1-SNAPSHOT"
:description "Create simple interactive CLIs for Clojure applications."
:url "https://github.com/ruedigergad/cli4clj"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:dependencies [[org.clojure/clojure "1.9.0"]
[clj-assorted-utils "1.18.2"]
[org.clojure/core.async "0.4.474"]
[jline/jline "2.14.6"]]
:global-vars {*warn-on-reflection* true}
:html5-docs-docs-dir "ghpages/doc"
:html5-docs-ns-includes #"^cli4clj.*"
:html5-docs-repository-url "https://github.com/ruedigergad/cli4clj/blob/master"
:test2junit-output-dir "ghpages/test-results"
:test2junit-run-ant true
:main cli4clj.example
:plugins [[lein-cloverage "1.0.2"] [test2junit "1.3.3"] [lein-html5-docs "3.0.3"]]
:profiles {:repl {:dependencies [[jonase/eastwood "0.2.6" :exclusions [org.clojure/clojure]]]}}
)
|
Move logging dependencies to :dev profile | (defproject com.farmlogs.conduit "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url "http://example.com/FIXME"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:dependencies [[org.clojure/clojure "1.7.0"]
[com.novemberain/langohr "3.4.1"]
[com.stuartsierra/component "0.3.0"]
[org.clojure/core.async "0.2.374"]
[org.clojure/tools.logging "0.3.1"]
[ch.qos.logback/logback-classic "1.1.2" :exclusions [org.slf4j/slf4j-api]]
[org.slf4j/jul-to-slf4j "1.7.7"]
[org.slf4j/jcl-over-slf4j "1.7.7"]
[org.slf4j/log4j-over-slf4j "1.7.7"]]
:profiles {:dev {:dependencies [[org.clojure/test.check "0.9.0"]]}})
| (defproject com.farmlogs.conduit "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url "http://example.com/FIXME"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:dependencies [[org.clojure/clojure "1.7.0"]
[com.novemberain/langohr "3.4.1"]
[com.stuartsierra/component "0.3.0"]
[org.clojure/core.async "0.2.374"]
[org.clojure/tools.logging "0.3.1"]]
:profiles {:dev {:dependencies
[[org.clojure/test.check "0.9.0"]
[ch.qos.logback/logback-classic "1.1.2" :exclusions [org.slf4j/slf4j-api]]
[org.slf4j/jul-to-slf4j "1.7.7"]
[org.slf4j/jcl-over-slf4j "1.7.7"]
[org.slf4j/log4j-over-slf4j "1.7.7"]]}})
|
Update to most recent version of Clojure. | (defproject inet.data "0.5.2-SNAPSHOT"
:description "Represent and manipulate various Internet entities as data."
:url "http://github.com/llasram/inet.data"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:dependencies [[org.clojure/clojure "1.4.0"]
[hier-set "1.1.2"]]
:plugins [[lein-ragel "0.1.0"]
[codox "0.6.1"]]
:source-paths ["src/clojure"]
:java-source-paths ["src/java" "target/ragel"]
:ragel-source-paths ["src/ragel"]
:javac-options ["-g"]
:prep-tasks ["ragel" "javac"]
:warn-on-reflection true
:codox {:exclude [inet.data.util]}
:aliases {"doc!" ["with-profile" "doc,dev" "doc"]}
:profiles {:dev {:dependencies [[byteable "0.2.0"]
[criterium "0.2.1"]]}
:doc {:dependencies [[org.clojure/clojure "1.3.0"]]}})
| (defproject inet.data "0.5.2-SNAPSHOT"
:description "Represent and manipulate various Internet entities as data."
:url "http://github.com/llasram/inet.data"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:dependencies [[org.clojure/clojure "1.5.1"]
[hier-set "1.1.2"]]
:plugins [[lein-ragel "0.1.0"]
[codox "0.6.1"]]
:source-paths ["src/clojure"]
:java-source-paths ["src/java" "target/ragel"]
:ragel-source-paths ["src/ragel"]
:javac-options ["-g"]
:prep-tasks ["ragel" "javac"]
:warn-on-reflection true
:codox {:exclude [inet.data.util]}
:aliases {"doc!" ["with-profile" "doc,dev" "doc"]}
:profiles {:dev {:dependencies [[byteable "0.2.0"]
[criterium "0.2.1"]]}
:doc {:dependencies [[org.clojure/clojure "1.3.0"]]}})
|
Test stuff in REPL they said. | (ns lambda-blog.templates.tags
(:require [lambda-blog.templates.bits :refer [panel text-centered]]
[lambda-blog.templates.page :refer [page]]
[lambda-blog.utils :refer [pathcat]]
[s-html.tags :refer [a div h1 span]]))
(defn tag-cloud [min max {:keys [entries path-to-root tags]}]
(let [counts (->> tags
;; FIXME O(N_tags * N_entries) but could be O(N_entries)
(map #(->> entries
(filter (fn [{:keys [tags]}]
(contains? (into #{} (map :id tags))
(:id %))))
count
(vector %))))
total (count entries)]
(div (text-centered
(map (fn [[t c]]
(a {:class :tag
:href (pathcat path-to-root (:path t))}
(span {:class [:label :label-info]
:style (format "font-size: %s%%;"
(+ min-size
(* (- max-size min-size)
(/ c total))))}
(:id t))
" "))
(sort-by (comp :id first)
counts))))))
(defn tags-index [ent]
(page (fn [ent]
[(-> "Tag cloud" h1 text-centered panel)
(tag-cloud 100 300 ent)])
ent))
| (ns lambda-blog.templates.tags
(:require [lambda-blog.templates.bits :refer [panel text-centered]]
[lambda-blog.templates.page :refer [page]]
[lambda-blog.utils :refer [pathcat]]
[s-html.tags :refer [a div h1 span]]))
(defn tag-cloud [min max {:keys [entries path-to-root tags]}]
(let [counts (->> tags
;; FIXME O(N_tags * N_entries) but could be O(N_entries)
(map #(->> entries
(filter (fn [{:keys [tags]}]
(contains? (into #{} (map :id tags))
(:id %))))
count
(vector %))))
total (count entries)]
(div (text-centered
(map (fn [[t c]]
(a {:class :tag
:href (pathcat path-to-root (:path t))}
(span {:class [:label :label-info]
:style (format "font-size: %s%%;"
(+ min
(* (- max min)
(/ c total))))}
(:id t))
" "))
(sort-by (comp :id first)
counts))))))
(defn tags-index [ent]
(page (fn [ent]
[(-> "Tag cloud" h1 text-centered panel)
(tag-cloud 100 300 ent)])
ent))
|
Add optional reference attributes for SAM. | (ns cljam.io.sam.util.refs
"Utility functions for SAM references.")
(defn make-refs
"Return a reference sequence from the sam header."
[hdr]
(for [sq (:SQ hdr)]
{:name (:SN sq), :len (:LN sq)}))
(defn- ref-id*
[refs name]
(some #(when (= name (:name (second %))) (first %))
(map-indexed vector refs)))
(def ref-id
"Returns reference ID from the reference sequence and the specified reference
name. If not found, returns nil."
(memoize ref-id*))
(defn ref-name
"Returns a reference name from the reference ID. Returns nil if id is not
mapped."
[refs ^long id]
(when (<= 0 id (dec (count refs)))
(:name (nth refs id))))
(defn ref-by-name
"Returns the first reference which has the specified name."
[refs name]
(some #(if (= (:name %) name) %) refs))
| (ns cljam.io.sam.util.refs
"Utility functions for SAM references."
(:require [clojure.set :as cset]))
(defn make-refs
"Return a reference sequence from the sam header."
[hdr]
(map
#(cset/rename-keys
%
{:SN :name, :LN :len, :AH :alt, :AS :assembly,
:M5 :md5, :SP :species, :UR :uri})
(:SQ hdr)))
(defn- ref-id*
[refs name]
(some #(when (= name (:name (second %))) (first %))
(map-indexed vector refs)))
(def ref-id
"Returns reference ID from the reference sequence and the specified reference
name. If not found, returns nil."
(memoize ref-id*))
(defn ref-name
"Returns a reference name from the reference ID. Returns nil if id is not
mapped."
[refs ^long id]
(when (<= 0 id (dec (count refs)))
(:name (nth refs id))))
(defn ref-by-name
"Returns the first reference which has the specified name."
[refs name]
(some #(if (= (:name %) name) %) refs))
|
Exclude `contains?` to avoid warnings | (ns extracter.files
(:require [clojure.java.io :as io]))
(defn contains?
[^java.util.regex.Pattern re ^String s]
(boolean (re-find re s)))
(defn fact?
"Returns true if the given file appears to contain at least one fact docstring."
[^java.io.File f]
(with-open [fin (io/reader f)]
(->> fin
line-seq
(some (partial contains? #"# Fact: ")))))
(defn file?
[^java.io.File f]
(.isFile f))
(defn facts-in-dir
"Returns a lazy sequence of java.io.File instances for every fact source file in a directory path.
Scans recursively."
[^String path]
(->> path
io/file
file-seq
(filter file?)
(filter fact?)))
| (ns extracter.files
(:refer-clojure :exclude [contains?])
(:require [clojure.java.io :as io]))
(defn contains?
[^java.util.regex.Pattern re ^String s]
(boolean (re-find re s)))
(defn fact?
"Returns true if the given file appears to contain at least one fact docstring."
[^java.io.File f]
(with-open [fin (io/reader f)]
(->> fin
line-seq
(some (partial contains? #"# Fact: ")))))
(defn file?
[^java.io.File f]
(.isFile f))
(defn facts-in-dir
"Returns a lazy sequence of java.io.File instances for every fact source file in a directory path.
Scans recursively."
[^String path]
(->> path
io/file
file-seq
(filter file?)
(filter fact?)))
|
Fix make-site-entry test for changed name of test site | (ns comic-reader.site-scraper-test
(:require [clojure.java.io :as io]
[clojure.test :as t]
[comic-reader.site-scraper :as sut])
(:import comic_reader.sites.MangaSite))
(t/deftest make-site-entry-test
(t/is (= (sut/make-site-entry "non-existent")
["non-existent" nil]))
(let [test-file (io/as-file "resources/sites/test-site.clj")]
(spit test-file "{}")
(let [[label opts] (sut/make-site-entry "test-site")]
(t/is (= label
"test-site"))
(t/is (= (class opts)
MangaSite)))
(io/delete-file test-file)))
| (ns comic-reader.site-scraper-test
(:require [clojure.java.io :as io]
[clojure.test :as t]
[comic-reader.site-scraper :as sut])
(:import comic_reader.sites.MangaSite))
(t/deftest make-site-entry-test
(t/is (= (sut/make-site-entry "non-existent")
["non-existent" nil]))
(let [test-file (io/as-file "resources/sites/test.site.edn")]
(spit test-file "{}")
(let [[label opts] (sut/make-site-entry "test")]
(t/is (= label
"test"))
(t/is (= (class opts)
MangaSite)))
(io/delete-file test-file)))
|
Fix documentation typo in content-type middleware | (ns ring.middleware.content-type
"Middleware for automatically adding a content type to response maps."
(:require [ring.util.mime-type :refer [ext-mime-type]]
[ring.util.response :refer [content-type get-header]]))
(defn content-type-response
"Adds a content-type header to response. See: wrap-content-type."
{:added "1.2"}
([response request]
(content-type-response response request {}))
([response request options]
(if response
(if (get-header response "Content-Type")
response
(let [mime-type (ext-mime-type (:uri request) (:mime-types options))]
(content-type response (or mime-type "application/octet-stream")))))))
(defn wrap-content-type
"Middleware that adds a content-type header to the response if one is not
set by the handler. Uses the ring.util.mime-type/ext-mime-type function to
guess the content-type from the file extension in the URI. If no
content-type can be found, it defaults to 'application/octet-stream'.
Accepts the following options:
:mime-types - a map of filename extensions to mime-types that will be
used in addition to the ones defined in
ring.util.mime-types/default-mime-types"
([handler]
(wrap-content-type handler {}))
([handler options]
(fn
([request]
(-> (handler request) (content-type-response request options)))
([request respond raise]
(handler request
(fn [response] (respond (content-type-response response request options)))
raise)))))
| (ns ring.middleware.content-type
"Middleware for automatically adding a content type to response maps."
(:require [ring.util.mime-type :refer [ext-mime-type]]
[ring.util.response :refer [content-type get-header]]))
(defn content-type-response
"Adds a content-type header to response. See: wrap-content-type."
{:added "1.2"}
([response request]
(content-type-response response request {}))
([response request options]
(if response
(if (get-header response "Content-Type")
response
(let [mime-type (ext-mime-type (:uri request) (:mime-types options))]
(content-type response (or mime-type "application/octet-stream")))))))
(defn wrap-content-type
"Middleware that adds a content-type header to the response if one is not
set by the handler. Uses the ring.util.mime-type/ext-mime-type function to
guess the content-type from the file extension in the URI. If no
content-type can be found, it defaults to 'application/octet-stream'.
Accepts the following options:
:mime-types - a map of filename extensions to mime-types that will be
used in addition to the ones defined in
ring.util.mime-type/default-mime-types"
([handler]
(wrap-content-type handler {}))
([handler options]
(fn
([request]
(-> (handler request) (content-type-response request options)))
([request respond raise]
(handler request
(fn [response] (respond (content-type-response response request options)))
raise)))))
|
Return time elapsed as a float. | (ns cmr.opendap.util)
(defn bool
[arg]
(if (contains? #{true :true "true" "TRUE" "t" "T" 1} arg)
true
false))
(defn remove-empty
[coll]
(remove #(or (nil? %) (empty? %)) coll))
(defn deep-merge
"Merge maps recursively."
[& maps]
(if (every? #(or (map? %) (nil? %)) maps)
(apply merge-with deep-merge maps)
(last maps)))
(defn now
[]
(/ (System/currentTimeMillis) 1000))
(defn timed
[start]
(- (now) start))
(defn most-frequent
"This identifies the most frequently occuring data in a collection
and returns it."
[data]
(->> data
frequencies
;; the 'frequencies' function puts data first; let's swap the order
(map (fn [[k v]] [v k]))
;; sort in reverse order to get the highest counts first
(sort (comp - compare))
;; just get the highest
first
;; the first element is the count, the second is the bounding data
second))
| (ns cmr.opendap.util)
(defn bool
[arg]
(if (contains? #{true :true "true" "TRUE" "t" "T" 1} arg)
true
false))
(defn remove-empty
[coll]
(remove #(or (nil? %) (empty? %)) coll))
(defn deep-merge
"Merge maps recursively."
[& maps]
(if (every? #(or (map? %) (nil? %)) maps)
(apply merge-with deep-merge maps)
(last maps)))
(defn now
[]
(/ (System/currentTimeMillis) 1000))
(defn timed
[start]
(float (- (now) start)))
(defn most-frequent
"This identifies the most frequently occuring data in a collection
and returns it."
[data]
(->> data
frequencies
;; the 'frequencies' function puts data first; let's swap the order
(map (fn [[k v]] [v k]))
;; sort in reverse order to get the highest counts first
(sort (comp - compare))
;; just get the highest
first
;; the first element is the count, the second is the bounding data
second))
|
Set the default print function for tests in V8. | (ns test-runner
(:require [cljs.core-test :as core-test]
[cljs.reader-test :as reader-test]
[clojure.string-test :as string-test]))
(core-test/test-stuff)
(reader-test/test-reader)
(string-test/test-string)
(println "Tests completed without exception")
| (ns test-runner
(:require [cljs.core-test :as core-test]
[cljs.reader-test :as reader-test]
[clojure.string-test :as string-test]))
(set! *print-fn* js/print)
(core-test/test-stuff)
(reader-test/test-reader)
(string-test/test-string)
(println "Tests completed without exception")
|
Add `subscribe-all' to receive *all* messages | (ns pepa.bus
(:require [com.stuartsierra.component :as component]
[clojure.core.async :as async :refer [>!!]]))
;;; pepa.bus is a simple application-wide notification bus. Clients
;;; can subscribe for any topic they want and will receive a value for
;;; any call of `notify!' for that topic.
(defn subscribe
"Returns a channel with that will receive a value when `notify!' is
called for that topic."
([bus topic buf]
(let [chan (async/chan buf)]
(async/sub (:output bus) topic chan)
chan))
([bus topic]
(subscribe bus topic nil)))
(defn notify!
([bus topic data]
(>!! (:input bus) (assoc data ::topic topic)))
([bus topic]
(notify! bus topic {})))
(defrecord Bus [input output]
component/Lifecycle
(start [component]
(println ";; Starting bus")
(let [input (async/chan)
output (async/pub input ::topic)]
(assoc component
:input input
:output output)))
(stop [component]
(println ";; Stopping bus")
(assoc component
:input nil
:output nil)))
(defn make-component []
(map->Bus {}))
| (ns pepa.bus
(:require [com.stuartsierra.component :as component]
[clojure.core.async :as async :refer [>!!]]))
;;; pepa.bus is a simple application-wide notification bus. Clients
;;; can subscribe for any topic they want and will receive a value for
;;; any call of `notify!' for that topic.
(defn subscribe
"Returns a channel with that will receive a value when `notify!' is
called for that topic."
([bus topic buf]
(let [chan (async/chan buf)]
(async/sub (:output bus) topic chan)
chan))
([bus topic]
(subscribe bus topic nil)))
(defn notify!
([bus topic data]
(>!! (:input bus) (assoc data ::topic topic)))
([bus topic]
(notify! bus topic {})))
(defn subscribe-all
"Returns a channel receiving all messages sent over the bus."
[bus & [buf]]
(let [ch (async/chan buf)]
(async/tap (:mult bus) ch)))
(defrecord Bus [input mult output]
component/Lifecycle
(start [component]
(println ";; Starting bus")
(let [input (async/chan)
mult (async/mult input)
output-tap (async/chan)
output (async/pub output-tap ::topic)]
(async/tap mult output-tap)
(assoc component
:input input
:mult mult
:output output)))
(stop [component]
(println ";; Stopping bus")
(async/close! (:input component))
(assoc component
:input nil
:mult nil
:output nil)))
(defn make-component []
(map->Bus {}))
|
Extend protocols to google maps classes | (ns gtfve.utils.google-maps
(:require-macros [cljs.core.async.macros :refer [go go-loop]])
(:require [cljs.core.async :as async :refer [put! chan <! close!]]))
(defonce Maps google.maps)
(defonce Data Maps.Data)
(defonce map-types (js->clj Maps.MapTypeId :keywordize-keys true))
(defonce default-map-opts {:center {:lat 14.653386
:lng 121.032520}
:mapTypeId (:ROADMAP map-types)
:zoom 15})
(defn data-listen
([data type]
(data-listen data type (chan)))
([data type c]
(.. data (addListener type (fn [e] (put! c (if e e (js/Date.))))))
c))
(defn listen
([gmap type]
(listen gmap type (chan)))
([gmap type c]
(.. Maps -event (addListener gmap type (fn [e] (put! c (if e e (js/Date.))))))
c))
| (ns gtfve.utils.google-maps
(:require-macros [cljs.core.async.macros :refer [go go-loop]])
(:require [cljs.core.async :as async :refer [put! chan <! close!]]))
(defonce Maps google.maps)
(defonce Data Maps.Data)
(defonce map-types (js->clj Maps.MapTypeId :keywordize-keys true))
(defonce default-map-opts {:center {:lat 14.653386
:lng 121.032520}
:mapTypeId (:ROADMAP map-types)
:zoom 15})
(extend-type Maps.LatLng
ILookup
(-lookup [this key] (get (js->clj this) key))
(-lookup [this key not-found] (or (get (js->clj this) key) not-found))
ISeqable
(-seq [this] (list (.lat this) (.lng this)))
IEncodeClojure
(-js->clj [this options] {:lat (.lat this) :lng (.lng this)}))
(extend-type Data.Point
ILookup
(-lookup [this key] (get (js->clj this) key))
(-lookup [this key not-found] (or (get (js->clj this) key) not-found))
ISeqable
(-seq [this] (seq (.get this)))
IEncodeClojure
(-js->clj [this options] (apply js->clj (.get this) options)))
(defn data-listen
([data type]
(data-listen data type (chan)))
([data type c]
(.. data (addListener type (fn [e] (put! c (if e e (js/Date.))))))
c))
(defn listen
([gmap type]
(listen gmap type (chan)))
([gmap type c]
(.. Maps -event (addListener gmap type (fn [e] (put! c (if e e (js/Date.))))))
c))
|
Change ceiling test to be deterministic | (ns backtype.storm.util-test
(:import [backtype.storm Config])
(:import [backtype.storm.utils Utils])
(:import [com.netflix.curator.retry ExponentialBackoffRetry])
(:use [backtype.storm util])
(:use [clojure test])
)
(deftest test-new-curator-uses-exponential-backoff
(let [expected_interval 2400
expected_retries 10
expected_ceiling 5000
conf (merge (clojurify-structure (Utils/readDefaultConfig))
{Config/STORM_ZOOKEEPER_RETRY_INTERVAL expected_interval
Config/STORM_ZOOKEEPER_RETRY_TIMES expected_retries
Config/STORM_ZOOKEEPER_RETRY_INTERVAL_CEILING expected_ceiling})
servers ["bogus_server"]
arbitrary_port 42
curator (Utils/newCurator conf servers arbitrary_port)
retry (-> curator .getZookeeperClient .getRetryPolicy)
]
(is (.isAssignableFrom ExponentialBackoffRetry (.getClass retry)))
(is (= (.getBaseSleepTimeMs retry) expected_interval))
(is (= (.getN retry) expected_retries))
(is (= (.getMaxRetryInterval retry) expected_ceiling))
; It would be very unlikely for this to fail three times.
(is (or
(= (.getSleepTimeMs retry 10 0) expected_ceiling)
(= (.getSleepTimeMs retry 10 0) expected_ceiling)
(= (.getSleepTimeMs retry 10 0) expected_ceiling)
))
)
)
| (ns backtype.storm.util-test
(:import [backtype.storm Config])
(:import [backtype.storm.utils Utils])
(:import [com.netflix.curator.retry ExponentialBackoffRetry])
(:use [backtype.storm util])
(:use [clojure test])
)
(deftest test-new-curator-uses-exponential-backoff
(let [expected_interval 2400
expected_retries 10
expected_ceiling (/ expected_interval 2)
conf (merge (clojurify-structure (Utils/readDefaultConfig))
{Config/STORM_ZOOKEEPER_RETRY_INTERVAL expected_interval
Config/STORM_ZOOKEEPER_RETRY_TIMES expected_retries
Config/STORM_ZOOKEEPER_RETRY_INTERVAL_CEILING expected_ceiling})
servers ["bogus_server"]
arbitrary_port 42
curator (Utils/newCurator conf servers arbitrary_port)
retry (-> curator .getZookeeperClient .getRetryPolicy)
]
(is (.isAssignableFrom ExponentialBackoffRetry (.getClass retry)))
(is (= (.getBaseSleepTimeMs retry) expected_interval))
(is (= (.getN retry) expected_retries))
(is (= (.getMaxRetryInterval retry) expected_ceiling))
(is (= (.getSleepTimeMs retry 10 0) expected_ceiling))
)
)
|
Remove clojure 1.5 and 1.6 proofiles from tests. | {:dev
{:aliases {"test-all" ["with-profile" "dev,1.7:dev,1.6:dev,1.5:dev" "test"]}
:dependencies [[com.nimbusds/nimbus-jose-jwt "4.13.1"]]
:codeina {:sources ["src"]
:reader :clojure
:target "doc/dist/latest/api"
:src-uri "http://github.com/funcool/buddy-core/blob/master/"
:src-uri-prefix "#L"}
:plugins [[funcool/codeina "0.3.0"]
[lein-ancient "0.6.10"]]}
:1.6 {:dependencies [[org.clojure/clojure "1.6.0"]]}
:1.5 {:dependencies [[org.clojure/clojure "1.5.1"]]}
:1.7 {:dependencies [[org.clojure/clojure "1.7.0"]]}}
| {:dev
{:aliases {"test-all" ["with-profile" "dev,1.7:dev" "test"]}
:dependencies [[com.nimbusds/nimbus-jose-jwt "4.13.1"]]
:codeina {:sources ["src"]
:reader :clojure
:target "doc/dist/latest/api"
:src-uri "http://github.com/funcool/buddy-core/blob/master/"
:src-uri-prefix "#L"}
:plugins [[funcool/codeina "0.4.0"]
[lein-ancient "0.6.10"]]}
:1.7 {:dependencies [[org.clojure/clojure "1.7.0"]]}}
|
Add test under clojure 1.8 | {:dev
{:dependencies [[org.clojure/tools.namespace "0.2.11"]
[criterium "0.4.3"]]
:source-paths ["dev"]
:codeina {:sources ["src"]
:reader :clojure
:target "doc/dist/latest/api"
:src-uri "http://github.com/funcool/cats/blob/master/"
:src-uri-prefix "#L"}
:plugins [[funcool/codeina "0.3.0"]
[lein-ancient "0.6.7" :exclusions [org.clojure/tools.reader]]]}
:bench
[:dev
{:main ^:skip-aot benchmarks
:jvm-opts ^:replace []}]}
| {:dev
{:aliases {"test-all" ["with-profile" "dev,1.8:dev" "test"]}
:dependencies [[org.clojure/tools.namespace "0.2.11"]
[criterium "0.4.3"]]
:source-paths ["dev"]
:codeina {:sources ["src"]
:reader :clojure
:target "doc/dist/latest/api"
:src-uri "http://github.com/funcool/cats/blob/master/"
:src-uri-prefix "#L"}
:plugins [[funcool/codeina "0.3.0"]
[lein-ancient "0.6.7" :exclusions [org.clojure/tools.reader]]]}
:1.8 {:dependencies [[org.clojure/clojure "1.8.0-RC4"]]}
:bench
[:dev
{:main ^:skip-aot benchmarks
:jvm-opts ^:replace []}]}
|
Make sure test fails if 1.x not available | (ns xa.init
(:require [immutant.xa :as xa]
[immutant.web :as web]
[clojure.java.jdbc :as sql]))
(defonce ds (xa/datasource "foo" {:adapter "h2" :database "mem:foo"}))
(def spec {:datasource ds})
(sql/with-connection spec
(sql/create-table :things
[:name :varchar]))
(xa/transaction
(sql/with-connection spec
(sql/insert-records :things {:name "success"})))
(defn read []
(sql/with-connection spec
(sql/with-query-results rows ["select name from things"]
(:name (first rows)))))
;;; A web interface
(defn handler [req]
{:status 200
:headers {"Content-Type" "text/plain"}
:body (read)})
(web/start "/thing" handler) | (ns xa.init
(:require [immutant.xa :as xa]
[immutant.web :as web]
[clojure.java.jdbc :as sql]
clojure.java.jdbc.internal)) ; ensure project dep wins
(defonce ds (xa/datasource "foo" {:adapter "h2" :database "mem:foo"}))
(def spec {:datasource ds})
(sql/with-connection spec
(sql/create-table :things
[:name :varchar]))
(xa/transaction
(sql/with-connection spec
(sql/insert-records :things {:name "success"})))
(defn read []
(sql/with-connection spec
(sql/with-query-results rows ["select name from things"]
(:name (first rows)))))
;;; A web interface
(defn handler [req]
{:status 200
:headers {"Content-Type" "text/plain"}
:body (read)})
(web/start "/thing" handler) |
Fix movement of test entity | (ns chocolatier.engine.entities
;; NOTE to use protocols from another ns, import them explicitely by
;; name and not their methods
;; Use them in this ns by refering to the name
(:require [chocolatier.engine.components :refer [Entity Renderable
Attackable TestComp]]))
(defrecord Bunny [id sprite x y]
Entity
(tick [this]
(let [sprite (:sprite this)])
(aset sprite "rotation" (+ 0.01 (aget sprite "rotation"))))
Renderable
(render [this stage]
(.addChild stage (:sprite this)))
Attackable
(attack [this] (println "owww"))
TestComp
(test-it [this] (println "testing")))
| (ns chocolatier.engine.entities
;; NOTE to use protocols from another ns, import them explicitely by
;; name and not their methods
;; Use them in this ns by refering to the name
(:require [chocolatier.engine.components :refer [Entity Renderable
Attackable TestComp]]))
(defrecord Bunny [id sprite x y]
Entity
(tick [this]
(let [sprite (:sprite this)
old-rotation (aget sprite "rotation")]
(aset sprite "rotation" (+ 0.01 old-rotation))))
Renderable
(render [this stage]
(.addChild stage (:sprite this)))
Attackable
(attack [this] (println "owww"))
TestComp
(test-it [this] (println "testing")))
|
Add some ajax functions that need to be tested. | (ns pp-client.util)
;;------------------------------------------------------------------------------
;; Util Functions
;;------------------------------------------------------------------------------
(defn log
"Log a Clojure thing."
[thing]
(js/console.log (pr-str thing)))
(defn js-log
"Log a JavaScript thing."
[thing]
(js/console.log thing))
(defn uuid []
"Create a UUID."
[]
(apply
str
(map
(fn [x]
(if (= x \0)
(.toString (bit-or (* 16 (.random js/Math)) 0) 16)
x))
"00000000-0000-4000-0000-000000000000")))
| (ns pp-client.util)
(def $ js/jQuery)
;;------------------------------------------------------------------------------
;; Util Functions
;;------------------------------------------------------------------------------
(defn log
"Log a Clojure thing."
[thing]
(js/console.log (pr-str thing)))
(defn js-log
"Log a JavaScript thing."
[thing]
(js/console.log thing))
(defn uuid []
"Create a UUID."
[]
(apply
str
(map
(fn [x]
(if (= x \0)
(.toString (bit-or (* 16 (.random js/Math)) 0) 16)
x))
"00000000-0000-4000-0000-000000000000")))
;;------------------------------------------------------------------------------
;; AJAX
;;------------------------------------------------------------------------------
(def default-ajax-options {
:contentType "application/json; charset=UTF-8"
:cache false
:dataType "json"
:error #(log "TODO: ajax error handling")})
;; TODO: use `:pre` to asset that opts has at a minimum a URL and success function
(defn doajax [opts]
(let [opts2 (clj->js (merge default-ajax-options opts))]
(.ajax $ opts2))) |
Remove session counter example for now. | (ns demo.web
(:require [clojure.pprint :refer [pprint]]
[immutant.web :as web]
[immutant.web.javax :as javax]
[ring.middleware.resource :as ring-resource]
[ring.util.response :as ring-util]))
(defn echo-request
"Echoes the request back as a string."
[request]
(ring-util/response (with-out-str (pprint request))))
(def assets
"Serve static assets from resources/public/"
(ring-resource/wrap-resource #'echo-request "public"))
;;; The Ring Session example: https://github.com/ring-clojure/ring/wiki/Sessions
(defn counter [{session :session}]
(let [count (:count session 0)
session (assoc session :count (inc count))]
(-> (ring-util/response (str "You accessed this page " count " times\n"))
(assoc :session session))))
(defn -main
[& {:as args}]
;; this uses an Undertow handler by default, which is faster than a servlet
(web/run echo-request args)
;; using a servlet allows the session to be shared in a WildFly
;; cluster and allow access to the session from websockets
(web/run
(javax/create-servlet #'counter)
:path "/counter"))
| (ns demo.web
(:require [clojure.pprint :refer [pprint]]
[immutant.web :as web]
[ring.util.response :as ring-util]))
(defn echo-request
"Echoes the request back as a string."
[request]
(ring-util/response (with-out-str (pprint request))))
(defn -main
[& {:as args}]
(web/run echo-request args))
|
Update getting started example to use map resolvers | (ns com.wsscode.pathom.book.connect.getting-started
(:require [com.wsscode.pathom.core :as p]
[com.wsscode.pathom.connect :as pc]
[com.wsscode.pathom.profile :as pp]))
; initialize a dispatch function
(defmulti resolver-fn pc/resolver-dispatch)
; initialize indexes
(def indexes (atom {}))
; this creates a factory that will add a new method on the resolver-fn and add it to the indexes
(def defresolver (pc/resolver-factory resolver-fn indexes))
; creating our first resolver
(defresolver `latest-product
{::pc/output [{::latest-product [:product/id :product/title :product/price]}]}
(fn [_ _]
{::latest-product {:product/id 1
:product/title "Acoustic Guitar"
:product/price 199.99M}}))
(def parser
(p/parser {::p/plugins
[(p/env-plugin
{::p/reader [p/map-reader
pc/all-readers]
::pc/resolver-dispatch resolver-fn
::pc/indexes @indexes})
pp/profile-plugin]}))
(comment
(parser {} [::latest-product]))
| (ns com.wsscode.pathom.book.connect.getting-started
(:require [com.wsscode.pathom.core :as p]
[com.wsscode.pathom.connect :as pc]
[com.wsscode.pathom.profile :as pp]))
; creating our first resolver
(pc/defresolver latest-product [_ _]
{::pc/output [{::latest-product [:product/id :product/title :product/price]}]}
{::latest-product {:product/id 1
:product/title "Acoustic Guitar"
:product/price 199.99M}})
(def parser
(p/parallel-parser
{::p/env {::p/reader [p/map-reader
pc/parallel-reader
pc/open-ident-reader
p/env-placeholder-reader]
::p/placeholder-prefixes #{">"}}
::p/mutate pc/mutate-async
::p/plugins [(pc/connect-plugin {::pc/register latest-product})
p/error-handler-plugin
p/request-cache-plugin
p/trace-plugin]}))
(comment
(parser {} [::latest-product]))
|
Improve the state chooser item code ever so slightly | (ns web.components.state-chooser
(:require [clojure.string :as str]
[om.next :as om :refer-macros [defui]]
[om.dom :as dom]))
(defui StateChooserItem
static om/Ident
(ident [this props]
[:state (:id props)])
static om/IQuery
(query [this]
[:id :name :type])
Object
(render [this]
(let [{:keys [id name type]} (om/props this)]
(dom/option #js {:value id}
(condp = type
:branch "b "
:tag "t "
" ")
(str/replace name
#"refs/heads/|refs/remotes/|refs/tags/"
"")))))
(def state-chooser-item (om/factory StateChooserItem {:keyfn :id}))
(defui StateChooser
Object
(state-selected [this e]
(let [id (.. e -target -value)
{:keys [select-fn]} (om/props this)]
(when select-fn
(select-fn [:state id])))
(.preventDefault e))
(render [this]
(let [{:keys [state states]} (om/props this)]
(dom/div #js {:className "state-chooser"}
(dom/select #js {:onChange #(.state-selected this %)}
(for [state states]
(state-chooser-item state)))))))
(def state-chooser (om/factory StateChooser))
| (ns web.components.state-chooser
(:require [clojure.string :as str]
[om.next :as om :refer-macros [defui]]
[om.dom :as dom]))
(defui StateChooserItem
static om/Ident
(ident [this props]
[:state (:id props)])
static om/IQuery
(query [this]
[:id :name :type])
Object
(render [this]
(let [{:keys [id name type]} (om/props this)
prefixes #"refs/heads/|refs/remotes/|refs/tags/"]
(dom/option #js {:value id}
(condp = type :branch "b " :tag "t " " ")
(str/replace name prefixes "")))))
(def state-chooser-item (om/factory StateChooserItem {:keyfn :id}))
(defui StateChooser
Object
(state-selected [this e]
(let [id (.. e -target -value)
{:keys [select-fn]} (om/props this)]
(when select-fn
(select-fn [:state id])))
(.preventDefault e))
(render [this]
(let [{:keys [state states]} (om/props this)]
(dom/div #js {:className "state-chooser"}
(dom/select #js {:onChange #(.state-selected this %)}
(for [state states]
(state-chooser-item state)))))))
(def state-chooser (om/factory StateChooser))
|
Add a domain extractor utility | (ns hacker-agent.utils)
(defn dissoc-in [data path]
(let [prefix (butlast path)
key (last path)]
(if prefix
(update-in data prefix dissoc key)
(dissoc data key))))
(defn log-clj [o]
(.log js/console (clj->js o)))
| (ns hacker-agent.utils)
(defn dissoc-in [data path]
(let [prefix (butlast path)
key (last path)]
(if prefix
(update-in data prefix dissoc key)
(dissoc data key))))
(defn log-clj [o]
(.log js/console (clj->js o)))
(defn domain [url]
(let [re (new js/RegExp "^https?\\:\\/\\/(www\\.)?([^\\/:?#]+)(?:[\\/:?#]|$)")
matches (.exec re url)]
(and matches (get matches 2))))
|
Add another test for `possible-moves' | (ns tttclj.t-core
(:use midje.sweet)
(:use [tttclj.core]))
(facts "about `create-game'"
(fact "x always starts"
(->> (repeat 100 (create-game))
(map :player)
(frequencies)) => { :x 100 })
(fact "no tiles are set to start with"
(frequencies (:tiles (create-game))) => { :- 9 }))
(facts "about `opponent'"
(opponent :x) => :o
(opponent :o) => :x)
(def game1 (make-move 3 (create-game)))
(facts "about `make-move'"
(fact "the player should swap to :o"
(:player game1) => :o)
(fact "one tile is taken now"
(frequencies (:tiles game1)) => { :- 8 :x 1})
(fact "cannot make same move again"
(make-move 3 (make-move 3 (create-game))) => nil))
(facts "about `possible-moves'"
(fact "there should be 9 to start"
(count (possible-moves (create-game))) => 9))
| (ns tttclj.t-core
(:use midje.sweet)
(:use [tttclj.core]))
(facts "about `create-game'"
(fact "x always starts"
(->> (repeat 100 (create-game))
(map :player)
(frequencies)) => { :x 100 })
(fact "no tiles are set to start with"
(frequencies (:tiles (create-game))) => { :- 9 }))
(facts "about `opponent'"
(opponent :x) => :o
(opponent :o) => :x)
(def game1 (make-move 3 (create-game)))
(facts "about `make-move'"
(fact "the player should swap to :o"
(:player game1) => :o)
(fact "one tile is taken now"
(frequencies (:tiles game1)) => { :- 8 :x 1})
(fact "cannot make same move again"
(make-move 3 (make-move 3 (create-game))) => nil))
(facts "about `possible-moves'"
(fact "there should be 9 to start"
(count (possible-moves (create-game))) => 9)
(fact "there should be 8 after the first move"
(count (possible-moves game1)) => 8))
|
Use update to make the impl more legible | (ns desdemona.lifecycles.logging
(:require [taoensso.timbre :refer [info]]))
(defn log-batch
[event lifecycle]
(let [task-name (-> event
:onyx.core/task-map
:onyx/name)]
(doseq [m (->> event
:onyx.core/results
:tree
(mapcat :leaves)
(map :message))]
(info task-name "logging segment:" m)))
{})
(def log-calls
{:lifecycle/after-batch log-batch})
(defn add-logging
"Adds logging output to a task's output-batch."
[job task]
(if-let [entry (first (filter #(= (:onyx/name %) task) (:catalog job)))]
(update-in
job
[:lifecycles]
conj
{:lifecycle/task task
:lifecycle/calls ::log-calls})))
| (ns desdemona.lifecycles.logging
(:require [taoensso.timbre :refer [info]]))
(defn log-batch
[event lifecycle]
(let [task-name (-> event
:onyx.core/task-map
:onyx/name)]
(doseq [m (->> event
:onyx.core/results
:tree
(mapcat :leaves)
(map :message))]
(info task-name "logging segment:" m)))
{})
(def log-calls
{:lifecycle/after-batch log-batch})
(defn add-logging
"Adds logging output to a task's output-batch."
[job task]
(if-let [entry (first (filter #(= (:onyx/name %) task) (:catalog job)))]
(update job :lifecycles conj {:lifecycle/task task
:lifecycle/calls ::log-calls})))
|
Add more details to list-route | (in-ns 'instaskip.actions)
(defn list-routes [filters innkeeper-config]
(let [routes (m/match filters
{:team team}
(ik/get-routes {:owned-by-team team} innkeeper-config)
:else
(ik/get-routes innkeeper-config))
filtered-routes (map #(select-keys % [:id :name :endpoint]) routes)]
(println "List routes")
(t/table filtered-routes)))
(defn list-route [id innkeeper-config]
(let [route (ik/get-route id innkeeper-config)
filtered-route (select-keys route [:id :name :path-id :created-by
:activate-at :created-at
:uses-common-filters :endpoint])]
(println "List route wiht id" id)
(t/table filtered-route)))
| (in-ns 'instaskip.actions)
(defn list-routes [filters innkeeper-config]
(let [routes (m/match filters
{:team team}
(ik/get-routes {:owned-by-team team} innkeeper-config)
:else
(ik/get-routes innkeeper-config))
filtered-routes (map #(select-keys % [:id :name :endpoint]) routes)]
(println "List routes")
(t/table filtered-routes)))
(defn list-route [id innkeeper-config]
(let [route (ik/get-route id innkeeper-config)
filtered-route (select-keys route [:id :name :path-id :created-by
:activate-at :created-at
:uses-common-filters :endpoint])]
(println "List route wiht id" id)
(t/table filtered-route)
(println "Filters for the route")
(t/table (route :filters))
(println "Predicates for the route")
(t/table (route :predicates))))
|
Replace :whitespace optimization with :none | (require '[cljs.build.api :as b]
'[cljs.tagged-literals])
(alter-var-root #'cljs.tagged-literals/*cljs-data-readers*
assoc 'ux/tr (fn [v] `(uxbox.locales/tr ~v)))
(println "Building ...")
(let [start (System/nanoTime)]
(b/build
(b/inputs "src" "test")
{:main 'uxbox.test-runner
:output-to "out/tests.js"
:output-dir "out"
:parallel-build false
:optimizations :whitespace
:language-in :ecmascript5
:language-out :ecmascript5
:target :nodejs
:verbose true})
(println "... done. Elapsed" (/ (- (System/nanoTime) start) 1e9) "seconds"))
| (require '[cljs.build.api :as b]
'[cljs.tagged-literals])
(alter-var-root #'cljs.tagged-literals/*cljs-data-readers*
assoc 'ux/tr (fn [v] `(uxbox.locales/tr ~v)))
(println "Building ...")
(let [start (System/nanoTime)]
(b/build
(b/inputs "src" "test")
{:main 'uxbox.test-runner
:output-to "out/tests.js"
:output-dir "out"
:parallel-build false
:optimizations :none
:language-in :ecmascript5
:language-out :ecmascript5
:target :nodejs
:verbose true})
(println "... done. Elapsed" (/ (- (System/nanoTime) start) 1e9) "seconds"))
|
Add cats.labs.channel-spec to testing namespaces. | (ns user
(:require [clojure.tools.namespace.repl :as repl]
[clojure.walk :refer [macroexpand-all]]
[clojure.pprint :refer [pprint]]
[clojure.test :as test]))
(defonce ^:dynamic
*namespaces*
['cats.core-spec
'cats.builtin-spec
'cats.applicative.validation-spec
'cats.monad.identity-spec
'cats.monad.either-spec
'cats.monad.exception-spec
'cats.monad.maybe-spec])
(defn run-tests'
[]
(apply test/run-tests *namespaces*))
(defn run-tests
[& nss]
(if (pos? (count nss))
(binding [*namespaces* nss]
(repl/refresh :after 'user/run-tests'))
(repl/refresh :after 'user/run-tests')))
(defn trace
"Asynchronous friendly println variant."
[& strings]
(locking println
(apply println strings)))
;; (require '[cats.core :as m]
;; '[cats.context :as mc]
;; '[cats.monad.either :as either]
;; '[cats.builtin])
| (ns user
(:require [clojure.tools.namespace.repl :as repl]
[clojure.walk :refer [macroexpand-all]]
[clojure.pprint :refer [pprint]]
[clojure.test :as test]))
(defonce ^:dynamic
*namespaces*
['cats.core-spec
'cats.builtin-spec
'cats.applicative.validation-spec
'cats.labs.channel-spec
'cats.monad.identity-spec
'cats.monad.either-spec
'cats.monad.exception-spec
'cats.monad.maybe-spec])
(defn run-tests'
[]
(apply test/run-tests *namespaces*))
(defn run-tests
[& nss]
(if (pos? (count nss))
(binding [*namespaces* nss]
(repl/refresh :after 'user/run-tests'))
(repl/refresh :after 'user/run-tests')))
(defn trace
"Asynchronous friendly println variant."
[& strings]
(locking println
(apply println strings)))
;; (require '[cats.core :as m]
;; '[cats.context :as mc]
;; '[cats.monad.either :as either]
;; '[cats.builtin])
|
Update Clojure 1.7 test profile to 1.7.0-beta2 | (defproject compojure "1.3.3"
:description "A concise routing library for Ring"
:url "https://github.com/weavejester/compojure"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:dependencies [[org.clojure/clojure "1.5.1"]
[org.clojure/tools.macro "0.1.5"]
[clout "2.1.1"]
[medley "0.5.5"]
[ring/ring-core "1.3.2"]
[ring/ring-codec "1.0.0"]]
:plugins [[codox "0.8.10"]]
:codox {:src-dir-uri "http://github.com/weavejester/compojure/blob/1.3.3/"
:src-linenum-anchor-prefix "L"}
:profiles
{:dev {:jvm-opts ^:replace []
:dependencies [[ring/ring-mock "0.2.0"]
[criterium "0.4.3"]
[javax.servlet/servlet-api "2.5"]]}
:1.6 {:dependencies [[org.clojure/clojure "1.6.0"]]}
:1.7 {:dependencies [[org.clojure/clojure "1.7.0-alpha6"]]}})
| (defproject compojure "1.3.3"
:description "A concise routing library for Ring"
:url "https://github.com/weavejester/compojure"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:dependencies [[org.clojure/clojure "1.5.1"]
[org.clojure/tools.macro "0.1.5"]
[clout "2.1.1"]
[medley "0.5.5"]
[ring/ring-core "1.3.2"]
[ring/ring-codec "1.0.0"]]
:plugins [[codox "0.8.10"]]
:codox {:src-dir-uri "http://github.com/weavejester/compojure/blob/1.3.3/"
:src-linenum-anchor-prefix "L"}
:profiles
{:dev {:jvm-opts ^:replace []
:dependencies [[ring/ring-mock "0.2.0"]
[criterium "0.4.3"]
[javax.servlet/servlet-api "2.5"]]}
:1.6 {:dependencies [[org.clojure/clojure "1.6.0"]]}
:1.7 {:dependencies [[org.clojure/clojure "1.7.0-beta2"]]}})
|
Print less information on startup | (ns tttclj.web
(:require [chord.http-kit :refer [wrap-websocket-handler]]
[clojure.core.async :refer [<! >! put! close! go go-loop timeout]]
[compojure.core :refer [defroutes GET]]
[compojure.route :refer [resources]]
[org.httpkit.server :refer [run-server]]))
(defn index [req]
{:status 200
:headers {"Content-Type" "text/html"}
:body "Hello HTTP via Compojure!"})
(defn ws-handler [{:keys [ws-channel] :as req}]
(prn (:remote-addr req))
(go-loop [i 10]
(<! (timeout 1000))
(>! ws-channel (str "Hello from server" i))
(prn req)
(when (> i 0)
(recur (dec i)))))
(defroutes app
(resources "/")
(GET "/ws" [] (-> ws-handler
(wrap-websocket-handler)))
(GET "/" [] index))
(defn -main [& args]
(run-server app {:port 8080})
(println "Started server on http://localhost:8080"))
| (ns tttclj.web
(:require [chord.http-kit :refer [wrap-websocket-handler]]
[clojure.core.async :refer [<! >! put! close! go go-loop timeout]]
[compojure.core :refer [defroutes GET]]
[compojure.route :refer [resources]]
[org.httpkit.server :refer [run-server]]))
(defn index [req]
{:status 200
:headers {"Content-Type" "text/html"}
:body "Hello HTTP via Compojure!"})
(defn ws-handler [{:keys [ws-channel] :as req}]
(prn (:async-channel req))
(go-loop [i 10]
(<! (timeout 1000))
(>! ws-channel (str "Hello from server" i))
(when (> i 0)
(recur (dec i)))))
(defroutes app
(resources "/")
(GET "/ws" [] (-> ws-handler
(wrap-websocket-handler)))
(GET "/" [] index))
(defn -main [& args]
(run-server #'app {:port 8080})
(println "Started server on http://localhost:8080"))
|
Use edn for reading strings | (ns ansel.session
(:import java.util.UUID)
(:require [ring.middleware.session.store :refer :all]
[ansel.util :refer [when-slurp]]))
(defn new-key []
(str (UUID/randomUUID)))
(deftype FileSystemSessionStore [session-filename]
SessionStore
(read-session [s session-key]
(let [session-text (when-slurp session-filename)
session-data (read-string (or session-text "{}"))]
(when session-data
(session-data (keyword session-key)))))
(write-session [_ session-key data]
(let [k (or session-key (new-key))
session-text (when-slurp session-filename)
session-data (read-string (or session-text "{}"))
updated-data (assoc session-data (keyword k) data)]
(spit session-filename updated-data)
k))
(delete-session [_ session-key]
(let [session-data (read-string (when-slurp session-filename))
updated-data (dissoc session-data (keyword session-key))]
(spit session-filename updated-data)
nil)))
(defn filesystem-store [session-filename]
(FileSystemSessionStore. session-filename))
| (ns ansel.session
(:import java.util.UUID)
(:require [ring.middleware.session.store :refer :all]
[clojure.edn :as e]
[ansel.util :refer [when-slurp]]))
(defn new-key []
(str (UUID/randomUUID)))
(deftype FileSystemSessionStore [session-filename]
SessionStore
(read-session [s session-key]
(let [session-text (when-slurp session-filename)
session-data (e/read-string (or session-text "{}"))]
(when session-data
(session-data (keyword session-key)))))
(write-session [_ session-key data]
(let [k (or session-key (new-key))
session-text (when-slurp session-filename)
session-data (e/read-string (or session-text "{}"))
updated-data (assoc session-data (keyword k) data)]
(spit session-filename updated-data)
k))
(delete-session [_ session-key]
(let [session-data (e/read-string (when-slurp session-filename))
updated-data (dissoc session-data (keyword session-key))]
(spit session-filename updated-data)
nil)))
(defn filesystem-store [session-filename]
(FileSystemSessionStore. session-filename))
|
Add paths paremeter on story-component | (ns storemi.js
(:require
[clj-rhino :as js]
[clojure.walk :refer [keywordize-keys]]))
(def parser-scope
(doto (js/new-safe-scope)
(js/eval (slurp "resources/public/js/underscore-min.js"))
(js/eval (slurp "resources/public/js/parser.js"))))
(defn parse-script [script]
(let [sc (js/new-scope nil parser-scope)]
(js/set! sc "script" script)
(-> (js/eval sc "parseScript(script)")
js/from-js)))
(def react-scope
(let [scripts ["resources/public/js/underscore-min.js"
"resources/public/js/react.min.js"
"resources/public/js/parser.js"
"resources/public/js/react/story-ui.react.js"]
scope (js/new-scope)]
(js/eval scope "var global = this")
(doseq [s scripts]
(js/eval scope (slurp s)))
scope))
(defn render-story-component [data & [paths]]
(let [sc (js/new-scope nil react-scope)]
(js/set! sc "data" (js/to-js data sc))
(js/set! sc "paths" (js/to-js paths sc))
(js/eval
sc "React.renderComponentToString(
Story({data: data, paths: paths}))")))
| (ns storemi.js
(:require
[clj-rhino :as js]
[clojure.walk :refer [keywordize-keys]]))
(def parser-scope
(doto (js/new-safe-scope)
(js/eval (slurp "resources/public/js/underscore-min.js"))
(js/eval (slurp "resources/public/js/parser.js"))))
(defn parse-script [script]
(let [sc (js/new-scope nil parser-scope)]
(js/set! sc "script" script)
(-> (js/eval sc "parseScript(script)")
js/from-js)))
(def react-scope
(let [scripts ["resources/public/js/underscore-min.js"
"resources/public/js/react.min.js"
"resources/public/js/parser.js"
"resources/public/js/react/story-ui.react.js"]
scope (js/new-scope)]
(js/eval scope "var global = this")
(doseq [s scripts]
(js/eval scope (slurp s)))
scope))
(defn render-story-component [data paths]
(let [sc (js/new-scope nil react-scope)]
(js/set! sc "data" (js/to-js data sc))
(js/set! sc "paths" (js/to-js paths sc))
(js/eval
sc "React.renderComponentToString(
Story({data: data,
paths: paths}))")))
|
Remove the shell based duration detection | (ns mdr2.dtb
"Functions to query DAISY Talking Books"
(:require [clojure.data.xml :as xml]
[clojure.java.io :refer [file]]
[clojure.java.shell :refer [sh]]
[clojure.string :refer [trim-newline]])
(:import javax.sound.sampled.AudioSystem))
(defn file-audio-length
"Get the length of the audio in seconds for a given audio file"
[file]
;; see http://stackoverflow.com/questions/3009908/how-do-i-get-a-sound-files-total-time-in-java
(let [stream (AudioSystem/getAudioInputStream file)
format (.getFormat stream)
frameRate (.getFrameRate format)
frames (.getFrameLength stream)
durationInSeconds (/ frames frameRate)]
durationInSeconds))
;; admitedly this is kinda hackish but the "Java-way" using
;; AudioSystem et al doesn't seem to work inside immutant
;; see https://issues.jboss.org/browse/IMMUTANT-457
;; (defn file-audio-length [file]
;; (-> (sh "soxi" "-D" (.getPath file))
;; :out
;; trim-newline
;; Double/parseDouble))
(defn wav-file? [file]
(and (.isFile file)
(.endsWith (.getName file) ".wav")))
(defn audio-length [dtb]
(let [audio-files (filter wav-file? (file-seq (file dtb)))]
(reduce + (map file-audio-length audio-files))))
| (ns mdr2.dtb
"Functions to query DAISY Talking Books"
(:require [clojure.data.xml :as xml]
[clojure.java.io :refer [file]])
(:import javax.sound.sampled.AudioSystem))
(defn file-audio-length
"Get the length of the audio in seconds for a given audio file"
[file]
;; see http://stackoverflow.com/questions/3009908/how-do-i-get-a-sound-files-total-time-in-java
(let [stream (AudioSystem/getAudioInputStream file)
format (.getFormat stream)
frameRate (.getFrameRate format)
frames (.getFrameLength stream)
durationInSeconds (/ frames frameRate)]
durationInSeconds))
(defn wav-file? [file]
(and (.isFile file)
(.endsWith (.getName file) ".wav")))
(defn audio-length [dtb]
(let [audio-files (filter wav-file? (file-seq (file dtb)))]
(reduce + (map file-audio-length audio-files))))
|
Set content-type for index. Note about serving index.html from classpath | (ns saapas.server
(:require [clojure.java.io :as io]
[compojure.core :refer [GET defroutes]]
[compojure.route :refer [resources]]
[compojure.handler :refer [api]]
[ring.util.response :refer [redirect]]
[ring.util.http-response :refer :all]
[ring.middleware.reload :refer [wrap-reload]]
[org.httpkit.server :refer [run-server]]
[saapas.index :refer [index-page]]))
(defroutes routes
(resources "/" {:root "public"})
; FIXME: boot-cljs will provide reverse routing fn which we
; can use to generate proper urls
(resources "/public" {:root "public"})
(resources "/cljsjs" {:root "cljsjs"})
(GET "/" []
(ok index-page)))
(defn stop
[{:keys [http-kit] :as ctx}]
(when http-kit
(http-kit))
{})
(defn start
[ctx & [{:keys [port reload reload-dirs]}]]
(let [handler (cond-> #'saapas.server/routes
reload (wrap-reload {:dirs (seq reload-dirs)}))
port (Integer. (or port 10555))
http-kit (run-server handler {:port port :join? false})]
(println "Starting web server on port" port)
{:http-kit http-kit}))
| (ns saapas.server
(:require [clojure.java.io :as io]
[compojure.core :refer [GET defroutes]]
[compojure.route :refer [resources]]
[compojure.handler :refer [api]]
[ring.util.response :refer [redirect]]
[ring.util.http-response :refer :all]
[ring.middleware.reload :refer [wrap-reload]]
[org.httpkit.server :refer [run-server]]
[saapas.index :refer [index-page]]))
(defroutes routes
(resources "/" {:root "public"})
; FIXME: boot-cljs will provide reverse routing fn which we
; can use to generate proper urls
(resources "/public" {:root "public"})
(resources "/cljsjs" {:root "cljsjs"})
(GET "/" []
; Use (resource-response "index.html") to serve index.html from classpath
(-> (ok index-page) (content-type "text/html"))))
(defn stop
[{:keys [http-kit] :as ctx}]
(when http-kit
(http-kit))
{})
(defn start
[ctx & [{:keys [port reload reload-dirs]}]]
(let [handler (cond-> #'saapas.server/routes
reload (wrap-reload {:dirs (seq reload-dirs)}))
port (Integer. (or port 10555))
http-kit (run-server handler {:port port :join? false})]
(println "Starting web server on port" port)
{:http-kit http-kit}))
|
Return tagging actions from environments. | (defproject lspector/clojush "1.2.27"
:description "The Push programming language and the PushGP genetic programming
system implemented in Clojure.
See http://hampshire.edu/lspector/push.html"
:dependencies [[org.clojure/clojure "1.3.0"]
[org.clojure/math.numeric-tower "0.0.1"]
[local-file "0.0.4"]
[clojure-csv "2.0.0-alpha2"]
[org.clojure/data.json "0.1.3"]]
:main clojush.core)
| (defproject lspector/clojush "1.2.28"
:description "The Push programming language and the PushGP genetic programming
system implemented in Clojure.
See http://hampshire.edu/lspector/push.html"
:dependencies [[org.clojure/clojure "1.3.0"]
[org.clojure/math.numeric-tower "0.0.1"]
[local-file "0.0.4"]
[clojure-csv "2.0.0-alpha2"]
[org.clojure/data.json "0.1.3"]]
:main clojush.core)
|
Add tests for resolve operation. | (ns bide.core-tests
(:require [cljs.test :as t]
[bide.core :as r]))
(t/deftest router-tests
(t/testing "Simple match"
(let [r (r/build [["/a/b" :r1]
["/b/:c" :r2]
["/d/:e/f" :r3]])]
(t/is (= [:r1 nil] (r/match r "/a/b")))
(t/is (= [:r2 {:c "1"}] (r/match r "/b/1")))
(t/is (= [:r3 {:e "2"}] (r/match r "/d/2/f")))
(t/is (= nil (r/match r "/foo/bar"))))))
(enable-console-print!)
(set! *main-cli-fn* #(t/run-tests))
(defmethod t/report [:cljs.test/default :end-run-tests]
[m]
(if (t/successful? m)
(set! (.-exitCode js/process) 0)
(set! (.-exitCode js/process) 1)))
| (ns bide.core-tests
(:require [cljs.test :as t]
[bide.core :as r]))
(t/deftest match-tests
(let [r (r/build [["/a/b" :r1]
["/b/:c" :r2]
["/d/:e/f" :r3]])]
(t/is (= [:r1 nil] (r/match r "/a/b")))
(t/is (= [:r2 {:c "1"}] (r/match r "/b/1")))
(t/is (= [:r3 {:e "2"}] (r/match r "/d/2/f")))
(t/is (= nil (r/match r "/foo/bar")))))
(t/deftest resolve-tests
(let [r (r/build [["/a/b" :r1]
["/b/:c" :r2]
["/d/:e/f" :r3]])]
(t/is (= "/a/b" (r/resolve r :r1)))
(t/is (= "/b/4" (r/resolve r :r2 {:c 4})))
(t/is (= "/d/5/f" (r/resolve r :r3 {:e 5})))))
(enable-console-print!)
(set! *main-cli-fn* #(t/run-tests))
(defmethod t/report [:cljs.test/default :end-run-tests]
[m]
(if (t/successful? m)
(set! (.-exitCode js/process) 0)
(set! (.-exitCode js/process) 1)))
|
Prepare for next release cycle. | (defproject org.onyxplatform/onyx-bookkeeper "0.8.0.0-alpha5"
:description "Onyx plugin for BookKeeper"
:url "https://github.com/onyx-platform/onyx-bookkeeper"
: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}}
:dependencies [[org.clojure/clojure "1.7.0"]
^{:voom {:repo "git@github.com:onyx-platform/onyx.git" :branch "master"}}
[org.onyxplatform/onyx "0.8.0-alpha5"]]
:profiles {:dev {:plugins [[lein-set-version "0.4.1"]
[lein-update-dependency "0.1.2"]
[lein-pprint "1.1.1"]]}
:circle-ci {:jvm-opts ["-Xmx4g"]}})
| (defproject org.onyxplatform/onyx-bookkeeper "0.8.0.0-SNAPSHOT"
:description "Onyx plugin for BookKeeper"
:url "https://github.com/onyx-platform/onyx-bookkeeper"
: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}}
:dependencies [[org.clojure/clojure "1.7.0"]
^{:voom {:repo "git@github.com:onyx-platform/onyx.git" :branch "master"}}
[org.onyxplatform/onyx "0.8.0-alpha5"]]
:profiles {:dev {:plugins [[lein-set-version "0.4.1"]
[lein-update-dependency "0.1.2"]
[lein-pprint "1.1.1"]]}
:circle-ci {:jvm-opts ["-Xmx4g"]}})
|
Update Clojure version 1.7.0 -> 1.10.0 | (defproject nhl-score-api "0.24.0"
:description "A JSON API that returns the scores and goals from the latest finished NHL games."
:license {:name "MIT"
:url "https://opensource.org/licenses/MIT"}
:dependencies [[org.clojure/clojure "1.7.0"]
[org.clojure/data.json "0.2.6"]
[clj-http-lite "0.3.0"] ; clj-http-lite supports SNI (unlike http-kit or clj-http)
[clj-time "0.11.0"]
[camel-snake-kebab "0.3.2"]
[com.taoensso/carmine "2.12.0"]
[enlive "1.1.6"]
[http-kit "2.1.19"]
[yleisradio/new-reliquary "1.0.1"]]
:main nhl-score-api.core
:profiles {:uberjar {:aot :all}}
:plugins [[lein-heroku "0.5.3"]]
:uberjar-name "server.jar"
:heroku {:app-name "nhl-score-api"
:include-files ["target" "newrelic"]
:process-types { "web" "java -javaagent:newrelic/newrelic.jar -jar target/server.jar" }})
| (defproject nhl-score-api "0.24.0"
:description "A JSON API that returns the scores and goals from the latest finished NHL games."
:license {:name "MIT"
:url "https://opensource.org/licenses/MIT"}
:dependencies [[org.clojure/clojure "1.10.0"]
[org.clojure/data.json "0.2.6"]
[clj-http-lite "0.3.0"] ; clj-http-lite supports SNI (unlike http-kit or clj-http)
[clj-time "0.11.0"]
[camel-snake-kebab "0.3.2"]
[com.taoensso/carmine "2.19.1"]
[enlive "1.1.6"]
[http-kit "2.1.19"]
[yleisradio/new-reliquary "1.0.1"]]
:main nhl-score-api.core
:profiles {:uberjar {:aot :all}}
:plugins [[lein-heroku "0.5.3"]]
:uberjar-name "server.jar"
:heroku {:app-name "nhl-score-api"
:include-files ["target" "newrelic"]
:process-types { "web" "java -javaagent:newrelic/newrelic.jar -jar target/server.jar" }})
|
Use snapshot version of puget. | (defproject mvxcvi/vault "0.3.0-SNAPSHOT"
:description "Content-addressible datastore."
:url "https://github.com/greglook/vault"
:license {:name "Public Domain"
:url "http://unlicense.org/"}
:dependencies [[org.clojure/clojure "1.5.1"]
[org.clojure/data.codec "0.1.0"]
[org.clojure/tools.cli "0.2.4"]
[org.bouncycastle/bcpg-jdk15on "1.49"]
[mvxcvi/directive "0.1.0"]
[mvxcvi/puget "0.2.0"]
[digest "1.4.3"]
[fipp "0.4.1"]]
:main vault.tool)
| (defproject mvxcvi/vault "0.3.0-SNAPSHOT"
:description "Content-addressible datastore."
:url "https://github.com/greglook/vault"
:license {:name "Public Domain"
:url "http://unlicense.org/"}
:dependencies [[org.clojure/clojure "1.5.1"]
[org.clojure/data.codec "0.1.0"]
[org.clojure/tools.cli "0.2.4"]
[org.bouncycastle/bcpg-jdk15on "1.49"]
[mvxcvi/directive "0.1.0"]
[mvxcvi/puget "0.3.0-SNAPSHOT"]
[digest "1.4.3"]
[fipp "0.4.1"]]
:main vault.tool)
|
Update server to clojure 1.5 | (defproject nightweb-server/Nightweb "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url "http://example.com/FIXME"
:license {:name "Public Domain"
:url "http://unlicense.org/UNLICENSE"}
:dependencies [[org.clojure/clojure "1.4.0"]]
:main nightweb-server.core
:source-paths ["src" "../common/clojure"]
:java-source-paths ["../common/java"])
| (defproject nightweb-server/Nightweb "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url "http://example.com/FIXME"
:license {:name "Public Domain"
:url "http://unlicense.org/UNLICENSE"}
:dependencies [[org.clojure/clojure "1.5.0"]]
:main nightweb-server.core
:source-paths ["src" "../common/clojure"]
:java-source-paths ["../common/java"])
|
Make secretary use a rooted prefix | (ns comic-reader.routes
(:require [comic-reader.history :as h]
[re-frame.core :as rf]
[secretary.core :as secretary
:refer-macros [defroute]]))
;; Have secretary pull apart URL's and then dispatch with re-frame
(defroute sites-path "/" []
(rf/dispatch [:sites]))
(defroute comics-path "/comics/:site" {:keys [site]
{:keys [filter]}
:query-params}
(rf/dispatch [:comics site filter]))
(defroute read-path "/read/:site/:comic/:chapter/:page"
{site :site
:as location}
(let [location (dissoc location :site)]
(rf/dispatch [:read site location])))
(defroute "*" {:as _}
(rf/dispatch [:unknown]))
(defn go-to [page]
(h/set-token page))
(defn setup-secretary! []
(secretary/set-config! :prefix "#"))
| (ns comic-reader.routes
(:require [comic-reader.history :as h]
[re-frame.core :as rf]
[secretary.core :as secretary
:refer-macros [defroute]]))
;; Have secretary pull apart URL's and then dispatch with re-frame
(defroute sites-path "/" []
(rf/dispatch [:sites]))
(defroute comics-path "/comics/:site" {:keys [site]
{:keys [filter]}
:query-params}
(rf/dispatch [:comics site filter]))
(defroute read-path "/read/:site/:comic/:chapter/:page"
{site :site
:as location}
(let [location (dissoc location :site)]
(rf/dispatch [:read site location])))
(defroute "*" {:as _}
(rf/dispatch [:unknown]))
(defn go-to [page]
(h/set-token page))
(defn setup-secretary! []
(secretary/set-config! :prefix "/#"))
|
Add :exclusions to quil template | (defproject {{app-name}} "0.0.1-SNAPSHOT"
:description "FIXME: write description"
:url "http://example.com/FIXME"
:dependencies [[org.clojure/clojure "1.6.0"]
[quil "2.2.5"]]
:main {{namespace}})
| (defproject {{app-name}} "0.0.1-SNAPSHOT"
:description "FIXME: write description"
:url "http://example.com/FIXME"
:dependencies [[org.clojure/clojure "1.6.0"]
[quil "2.2.5" :exclusions [org.clojure/clojure]]]
:main {{namespace}})
|
Fix work in browser without webscoket support | (ns subman.push
(:require [cljs.reader :refer [read-string]]
[goog.net.WebSocket]
[goog.events :as gevents]))
(defn init-push
"Init push connection"
[total-count]
(let [ws (goog.net.WebSocket.)]
(gevents/listen ws goog.net.WebSocket.EventType.MESSAGE
(fn [msg] (->> (.-message msg)
read-string
:total-count
(reset! total-count)))
false ws)
(.open ws (str "ws://" (.-hostname js/location)
":" (.-port js/location)
"/notifications/"))
ws))
| (ns subman.push
(:require [cljs.reader :refer [read-string]]
[goog.net.WebSocket]
[goog.events :as gevents]
[jayq.util :refer [log]]))
(defn create-push-connection
"Create push connection"
[total-count]
(let [ws (goog.net.WebSocket.)]
(gevents/listen ws goog.net.WebSocket.EventType.MESSAGE
(fn [msg] (->> (.-message msg)
read-string
:total-count
(reset! total-count)))
false ws)
(.open ws (str "ws://" (.-hostname js/location)
":" (.-port js/location)
"/notifications/"))
ws))
(defn init-push
"Initiale push connection"
[total-count]
(try (create-push-connection total-count)
(catch js/Error e (log e))))
|
Remove unnecessary nickname generation code | (ns braid.server.events
(:require
[clojure.string :as string]
[clavatar.core :refer [gravatar]]
[braid.server.crypto :refer [random-nonce]]
[braid.server.db :as db]
[braid.server.sync :as sync]))
(defn register-user!
[email group-id]
(let [id (db/uuid)
; XXX: copied from braid.common.util/nickname-rd
disallowed-chars #"[ \t\n\]\[!\"#$%&'()*+,.:;<=>?@\^`{|}~/]"
nick (-> (first (string/split email #"@"))
(string/replace disallowed-chars ""))
; TODO: guard against duplicate nickname?
u (db/create-user! {:id id
:email email
:password (random-nonce 50)
:avatar (gravatar email
:rating :g
:default :identicon)
:nickname nick})]
(sync/user-join-group! id group-id)
id))
| (ns braid.server.events
(:require
[clavatar.core :refer [gravatar]]
[braid.server.crypto :refer [random-nonce]]
[braid.server.db :as db]
[braid.server.sync :as sync]))
(defn register-user!
[email group-id]
(let [id (db/uuid)
; TODO: guard against duplicate nickname?
u (db/create-user! {:id id
:email email
:password (random-nonce 50)
:avatar (gravatar email
:rating :g
:default :identicon)})]
(sync/user-join-group! id group-id)
id))
|
Use let, not def. Fix docs | (ns riemann.keenio
"Forwards events to Keen IO"
(:require [clj-http.client :as client])
(:require [cheshire.core :as json]))
(def ^:private event-url
"https://api.keen.io/3.0/projects/")
(defn post
"POST to Keen IO."
[collection project-id write-key request]
(let [final-event-url
(str event-url project-id "/events/" collection)]
(client/post final-event-url
{:body (json/generate-string request)
:query-params { "api_key" write-key }
:socket-timeout 5000
:conn-timeout 5000
:content-type :json
:accept :json
:throw-entire-message? true})))
(defn keenio
"Creates a keen adapter. Takes your Keen project id and write key, and
returns a function that accepts an event and sends it to Keen IO. The full
event will be sent.
(streams
(let [kio (keenio \"COLLECTION_NAME\" \"PROJECT_ID\" \"WRITE_KEY\")]
(where (state \"error\") kio)))"
[collection project-id write-key]
(fn [event]
(post collection project-id write-key event)))
| (ns riemann.keenio
"Forwards events to Keen IO"
(:require [clj-http.client :as client])
(:require [cheshire.core :as json]))
(def ^:private event-url
"https://api.keen.io/3.0/projects/")
(defn post
"POST to Keen IO."
[collection project-id write-key request]
(let [final-event-url
(str event-url project-id "/events/" collection)]
(client/post final-event-url
{:body (json/generate-string request)
:query-params { "api_key" write-key }
:socket-timeout 5000
:conn-timeout 5000
:content-type :json
:accept :json
:throw-entire-message? true})))
(defn keenio
"Creates a keen adapter. Takes your Keen project id and write key, and
returns a function that accepts an event and sends it to Keen IO. The full
event will be sent.
(streams
(let [kio (keenio \"COLLECTION_NAME\" \"PROJECT_ID\" \"WRITE_KEY\")]
(where (state \"error\") kio)))"
[collection project-id write-key]
(fn [event]
(post collection project-id write-key event)))
|
Call read-project from leiningen.core ns. | (ns leiningen.checkout-deps
(:use [leiningen.core :only [read-project]]
[clojure.contrib.java-utils :only [file]]))
(defn checkout-deps-paths [project]
(apply concat (for [dep (.listFiles (file (:root project) "checkouts"))]
;; Note that this resets the leiningen.core/project var!
(let [proj (read-project (.getAbsolutePath
(file dep "project.clj")))]
(for [d [:source-path :compile-path :resources-path]]
(proj d))))))
(defn checkout-deps [project]
;; TODO: look at all deps that have version-control repo information
;; in their jar and check them out into the checkouts directory.
)
| (ns leiningen.checkout-deps
(:use [leiningen.core :only [read-project]]
[clojure.contrib.java-utils :only [file]]))
(defn checkout-deps-paths [project]
(apply concat (for [dep (.listFiles (file (:root project) "checkouts"))]
;; Note that this resets the leiningen.core/project var!
(let [proj (binding [*ns* (find-ns 'leiningen.core)]
(read-project (.getAbsolutePath
(file dep "project.clj"))))]
(for [d [:source-path :compile-path :resources-path]]
(proj d))))))
(defn checkout-deps [project]
;; TODO: look at all deps that have version-control repo information
;; in their jar and check them out into the checkouts directory.
)
|
Add url definitions for chapters and scenes | (ns storemi.urlfor
(:require
[storemi.lib.urldef :refer [defurl]]))
(defurl login "/login")
(defurl logout "/logout")
(defurl register "/register")
(defurl about "/about")
(defurl upload-image "/upload")
(defurl list-images "/images/:username")
(defurl image "/images/:username/:filename")
(defurl story-index "/story")
(defurl story-create story-index "/create")
(defurl user-index story-index "/:username")
(defurl story user-index "/:story-id")
(defurl chapter story "/chapter/:chapter")
(defurl scene chapter "/scene/:scene")
(defurl story-delete story "/delete")
(defurl story-edit story "/edit")
(defurl story-data story "/data")
| (ns storemi.urlfor
(:require
[storemi.lib.urldef :refer [defurl]]))
(defurl login "/login")
(defurl logout "/logout")
(defurl register "/register")
(defurl about "/about")
(defurl upload-image "/upload")
(defurl list-images "/images/:username")
(defurl image "/images/:username/:filename")
(defurl story-index "/story")
(defurl story-create story-index "/create")
(defurl user-index story-index "/:username")
(defurl story user-index "/:story-id")
(defurl chapter story "/chapter/:chapter-id")
(defurl scene chapter "/scene/:scene-id")
(defurl story-delete story "/delete")
(defurl story-edit story "/edit")
(defurl story-data story "/data")
|
Change test format - input is defined as a JS string that gets eval'd. | (ns javascript-externs-generator.extern-test
(:require [cljs.test :refer-macros [deftest is testing run-tests]]
[javascript-externs-generator.extern :as extern]))
(enable-console-print!)
(deftest function
(let [js-object (clj->js {"testFunction" #()})]
(is (= "var TEST = {\"testFunction\": function () {}};"
(extern/extract "TEST" js-object)))))
(deftest property
(let [js-object (clj->js {"testProperty" "value"})]
(is (= "var TEST = {\"testProperty\": {}};"
(extern/extract "TEST" js-object)))))
(deftest object
(let [js-object (clj->js {"testObject" {"testProperty" "value"}})]
(is (= "var TEST = {\"testObject\": {\"testProperty\": {}}};"
(extern/extract "TEST" js-object)))))
(deftest prototype
(let [js-object (clj->js {"testFunction" #()})]
(set! (.. js-object -testFunction -prototype -testPrototypeFunction) #())
(is (= "var TEST = {\"testFunction\": function () {}};TEST.testFunction.prototype = {\"testPrototypeFunction\": function () {}};"
(extern/extract "TEST" js-object)))))
| (ns javascript-externs-generator.extern-test
(:require [cljs.test :refer-macros [deftest is testing run-tests]]
[javascript-externs-generator.extern :as extern]))
(enable-console-print!)
(defn compare! [expected, js-string]
(js/eval js-string)
(is (= expected (extern/extract "TEST" js/TEST))))
(deftest function
(let [js-string "function TEST() {}"
expected "var TEST = {\"testFunction\": function () {}};"]
(compare! expected js-string)))
(deftest property
(let [js-string "var TEST = {testProperty: \"value\"}"
expected "var TEST = {\"testProperty\": {}};"]
(compare! expected js-string)))
(deftest object
(let [js-string "var TEST = {testObject: {testProperty: \"value\"}}"
expected "var TEST = {\"testObject\": {\"testProperty\": {}}};"]
(compare! expected js-string)))
(deftest prototype
(let [js-string "var TEST = {testFunction: function(){}}; TEST.testFunction.prototype = {testPrototypeFunction: function() {}}"
expected "var TEST = {\"testFunction\": function () {}};TEST.testFunction.prototype = {\"testPrototypeFunction\": function () {}};"]
(compare! expected js-string)))
|
Bring Voom in as a dependnecy. | (defproject org.onyxplatform/onyx-kafka "0.7.3-SNAPSHOT"
:description "Onyx plugin for Kafka"
:url "https://github.com/MichaelDrogalis/onyx-kafka"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:dependencies [[org.clojure/clojure "1.7.0"]
^{:voom {:repo "git@github.com:onyx-platform/onyx.git" :branch "master"}}
[org.onyxplatform/onyx "0.7.3-20150821_215046-g67feccf"]
[clj-kafka "0.2.8-0.8.1.1" :exclusions [org.apache.zookeeper/zookeeper zookeeper-clj]]
[cheshire "5.4.0"]
[zookeeper-clj "0.9.1" :exclusions [io.netty/netty org.apache.zookeeper/zookeeper]]]
:profiles {:dev {:dependencies [[midje "1.7.0" :exclusions [commons-codec]]]
:plugins [[lein-midje "3.1.3"]]}
:circle-ci {:jvm-opts ["-Xmx4g"]}})
| (defproject org.onyxplatform/onyx-kafka "0.7.3-SNAPSHOT"
:description "Onyx plugin for Kafka"
:url "https://github.com/MichaelDrogalis/onyx-kafka"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:dependencies [[org.clojure/clojure "1.7.0"]
^{:voom {:repo "git@github.com:onyx-platform/onyx.git" :branch "master"}}
[org.onyxplatform/onyx "0.7.3-20150821_215046-g67feccf"]
[clj-kafka "0.2.8-0.8.1.1" :exclusions [org.apache.zookeeper/zookeeper zookeeper-clj]]
[cheshire "5.4.0"]
[zookeeper-clj "0.9.1" :exclusions [io.netty/netty org.apache.zookeeper/zookeeper]]]
:profiles {:dev {:dependencies [[midje "1.7.0" :exclusions [commons-codec]]]
:plugins [[lein-midje "3.1.3"]
[lein-voom "0.1.0-20150822_000839-g763d315"]]}
:circle-ci {:jvm-opts ["-Xmx4g"]}})
|
Add clj-kondo to default profile | ;; https://github.com/technomancy/leiningen/blob/stable/doc/PROFILES.md
{:user {:plugins [[lein-pprint "1.3.2"]]
:dependencies [[alembic "0.3.2"]]}}
| ;; https://github.com/technomancy/leiningen/blob/stable/doc/PROFILES.md
{:user {:plugins [[lein-pprint "1.3.2"]]
:dependencies [[alembic "0.3.2"]
[clj-kondo "RELEASE"]]
:aliases {"clj-kondo" ["run" "-m" "clj-kondo.main"]}}}
|
Update PMD ontology to include attachments | (ns grafter.rdf.ontologies.pmd
"Some convenience terms for the Publish My Data vocabulary."
(:require [grafter.rdf.ontologies.util :refer :all]))
(def pmd (prefixer "http://publishmydata.com/def/dataset#"))
(def pmd:Dataset (pmd "Dataset"))
(def pmd:contactEmail (pmd "contactEmail"))
(def pmd:graph (pmd "graph"))
(def folder (prefixer "http://publishmydata.com/def/ontology/folder/"))
(def folder:Folder (folder "Folder"))
(def folder:hasTree (folder "hasTree"))
(def folder:defaultTree (folder "defaultTree"))
(def folder:parentFolder (folder "parentFolder"))
(def folder:inFolder (folder "inFolder"))
(def folder:inTree (folder "inTree"))
| (ns grafter.rdf.ontologies.pmd
"Some convenience terms for the Publish My Data vocabulary."
(:require [grafter.rdf.ontologies.util :refer :all]))
(def pmd (prefixer "http://publishmydata.com/def/dataset#"))
(def pmd:Dataset (pmd "Dataset"))
(def pmd:LinkedDataset (pmd "LinkedDataset"))
(def pmd:FileDataset (pmd "FileDataset"))
(def pmd:DeprecatedDataset (pmd "DeprecatedDataset"))
(def pmd:contactEmail (pmd "contactEmail"))
(def pmd:graph (pmd "graph"))
(def pmd:fileName (pmd "fileName"))
(def pmd:fileExtension (pmd "fileExtension"))
(def pmd:mediaType (pmd "mediaType"))
(def pmd:sizeInBytes (pmd "sizeInBytes"))
(def pmd:downloadURL (pmd "downloadURL"))
(def folder (prefixer "http://publishmydata.com/def/ontology/folder/"))
(def folder:Folder (folder "Folder"))
(def folder:hasTree (folder "hasTree"))
(def folder:defaultTree (folder "defaultTree"))
(def folder:parentFolder (folder "parentFolder"))
(def folder:inFolder (folder "inFolder"))
(def folder:inTree (folder "inTree"))
|
Use the right syntax for :require. | (ns grafter.rdf.ontologies.rdf
"Some convenience terms for the RDF and RDFS vocabularies."
(:require grafter.rdf.ontologies.util :refer :all))
(def rdf (prefixer "http://www.w3.org/1999/02/22-rdf-syntax-ns#"))
(def rdfs (prefixer "http://www.w3.org/2000/01/rdf-schema#"))
(def rdf:a (rdf "type"))
(def rdf:Property (rdf "Property"))
(def rdfs:subPropertyOf (rdfs "subPropertyOf"))
(def rdfs:Class (rdfs "Class"))
(def rdfs:subClassOf (rdfs "subClassOf"))
(def rdfs:label (rdfs "label"))
(def rdfs:comment (rdfs "comment"))
(def rdfs:isDefinedBy (rdfs "isDefinedBy"))
(def rdfs:range (rdfs "range"))
(def rdfs:domain (rdfs "domain"))
| (ns grafter.rdf.ontologies.rdf
"Some convenience terms for the RDF and RDFS vocabularies."
(:require [grafter.rdf.ontologies.util :refer :all]))
(def rdf (prefixer "http://www.w3.org/1999/02/22-rdf-syntax-ns#"))
(def rdfs (prefixer "http://www.w3.org/2000/01/rdf-schema#"))
(def rdf:a (rdf "type"))
(def rdf:Property (rdf "Property"))
(def rdfs:subPropertyOf (rdfs "subPropertyOf"))
(def rdfs:Class (rdfs "Class"))
(def rdfs:subClassOf (rdfs "subClassOf"))
(def rdfs:label (rdfs "label"))
(def rdfs:comment (rdfs "comment"))
(def rdfs:isDefinedBy (rdfs "isDefinedBy"))
(def rdfs:range (rdfs "range"))
(def rdfs:domain (rdfs "domain"))
|
Add tools.trace to user deps. | {:user {:dependencies [[clj-stacktrace "0.2.5"]
[redl "0.1.0"]
[spyscope "0.1.3"]
[slamhound "1.3.3"]]
:plugins [[lein-difftest "1.3.7"]
[lein-drip "0.1.1-SNAPSHOT"]
[lein-clojars "0.9.1"]
[lein-pprint "1.1.1"]
[lein-ring "0.8.0"]
[lein-cljsbuild "0.1.9"]
[lein-deps-tree "0.1.2"]
[lein-marginalia "0.7.1"]]
:repl-options {:timeout 120000}
:injections [(require '[redl core complete])
(require 'spyscope.core)
(let [orig (ns-resolve (doto 'clojure.stacktrace require)
'print-cause-trace)
new (ns-resolve (doto 'clj-stacktrace.repl require)
'pst)]
(alter-var-root orig (constantly @new)))]
:vimclojure-opts {:repl true}}}
| {:user {:dependencies [[clj-stacktrace "0.2.5"]
[org.clojure/tools.trace "0.7.5"]
[redl "0.1.0"]
[spyscope "0.1.3"]
[slamhound "1.3.3"]]
:plugins [[lein-difftest "1.3.7"]
[lein-drip "0.1.1-SNAPSHOT"]
[lein-clojars "0.9.1"]
[lein-pprint "1.1.1"]
[lein-ring "0.8.0"]
[lein-cljsbuild "0.1.9"]
[lein-deps-tree "0.1.2"]
[lein-marginalia "0.7.1"]]
:repl-options {:timeout 120000}
:injections [(require '[redl core complete])
(require 'spyscope.core)
(let [orig (ns-resolve (doto 'clojure.stacktrace require)
'print-cause-trace)
new (ns-resolve (doto 'clj-stacktrace.repl require)
'pst)]
(alter-var-root orig (constantly @new)))]
:vimclojure-opts {:repl true}}}
|
Add special routes for single-query test with response not in a vector | (ns hello.routes.home
(:use compojure.core
hello.models.db)
(:require [hello.views.layout :as layout]
[noir.response :as response]))
(defroutes home-routes
(GET "/" [] "Hello, World!")
(GET "/json" [] (response/json {:message "Hello, World!"}))
(GET "/db/:queries" [queries] (response/json (run-queries (get-query-count queries))))
(GET "/dbraw/:queries" [queries] (response/json (run-queries-raw (get-query-count queries))))
(GET "/fortune" [] (layout/render "home.html" {:messages (get-fortunes)})))
| (ns hello.routes.home
(:use compojure.core
hello.models.db)
(:require [hello.views.layout :as layout]
[noir.response :as response]))
(defroutes home-routes
(GET "/" [] "Hello, World!")
(GET "/json" [] (response/json {:message "Hello, World!"}))
(GET "/db" [] (response/json (first (run-queries 1))))
(GET "/db/:queries" [queries] (response/json (run-queries (get-query-count queries))))
(GET "/dbraw" [] (response/json (first (run-queries-raw 1))))
(GET "/dbraw/:queries" [queries] (response/json (run-queries-raw (get-query-count queries))))
(GET "/fortune" [] (layout/render "home.html" {:messages (get-fortunes)})))
|
Use :name instead of :gem | (ns hu.ssh.github-changelog.dependencies.bundler
(:require
[clojure.string :refer [split-lines]]))
(defn- get-specs [file]
(->> (split-lines file)
(drop-while #(not= % " specs:"))
(drop 1)
(take-while seq)))
(defn- parse-spec [spec]
{:gem (second spec) :version (nth spec 2)})
(defn- parse-specs [specs]
(->> (map #(re-matches #"^\s{4}(\S+) \((.*)\)$" %) specs)
(remove empty?)
(map parse-spec)))
(defn parse [file]
(->> (slurp file)
get-specs
parse-specs))
| (ns hu.ssh.github-changelog.dependencies.bundler
(:require
[clojure.string :refer [split-lines]]))
(defn- get-specs [file]
(->> (split-lines file)
(drop-while #(not= % " specs:"))
(drop 1)
(take-while seq)))
(defn- parse-spec [spec]
{:name (second spec) :version (nth spec 2)})
(defn- parse-specs [specs]
(->> (map #(re-matches #"^\s{4}(\S+) \((.*)\)$" %) specs)
(remove empty?)
(map parse-spec)))
(defn parse [file]
(->> (slurp file)
get-specs
parse-specs))
|
Fix error with percent encoded input | (ns subman.history
(:require [cljs.reader :refer [read-string]]
[goog.events :as gevents]
[goog.history.EventType :as history-event]
[goog.string :as string]
[goog.history.Html5History :as history5]
[jayq.util :refer [wait]]))
(defn get-history
"Get html5 history obj or fallback"
[]
(doto (goog.history.Html5History.)
(.setUseFragment false)
(.setPathPrefix "/search/")
(.setEnabled true)))
(defn init-history
"Init history and spy to atom"
[value]
(when (history5/isSupported)
(let [history (get-history)]
(add-watch value :history
(fn [_ _ _ new-value]
(wait 500 #(when (= new-value @value)
(.setToken history new-value)))))
(gevents/listen history history-event/NAVIGATE
#(let [token (.-token %)]
(when (and (= (.-isNavigatopn %))
(not= token @value))
(reset! value token))))
(->> (.getToken history)
string/urlDecode
(reset! value)))))
| (ns subman.history
(:require [cljs.reader :refer [read-string]]
[goog.events :as gevents]
[goog.history.EventType :as history-event]
[goog.history.Html5History :as history5]
[jayq.util :refer [wait]]))
(defn get-history
"Get html5 history obj or fallback"
[]
(doto (goog.history.Html5History.)
(.setUseFragment false)
(.setPathPrefix "/search/")
(.setEnabled true)))
(defn init-history
"Init history and spy to atom"
[value]
(when (history5/isSupported)
(let [history (get-history)]
(add-watch value :history
(fn [_ _ _ new-value]
(wait 500 #(when (= new-value @value)
(.setToken history new-value)))))
(gevents/listen history history-event/NAVIGATE
#(let [token (-> % .-token js/decodeURIComponent)]
(when (and (= (.-isNavigatopn %))
(not= token @value))
(reset! value token))))
(->> (.getToken history)
js/decodeURIComponent
(reset! value)))))
|
Fix requirements and test arguments | (ns riemann.xymon-test
(:use riemann.xymon
[riemann.time :only [unix-time]]
clojure.test)
(:require [riemann.logging :as logging]))
(logging/init)
(deftest ^:xymon ^:integration xymon-test
(let [k (xymon)]
(k {:host "riemann.local"
:service "xymon test"
:state "green"
:description "all clear, uh, situation normal"
:metric -2
:time (unix-time)}))
(let [k (xymon)]
(k {:service "xymon test"
:state "green"
:description "all clear, uh, situation normal"
:metric 3.14159
:time (unix-time)}))
(let [k (xymon)]
(k {:host "riemann.local"
:service "xymon test"
:state "ok"
:description "all clear, uh, situation normal"
:metric 3.14159
:time (unix-time)}))
(let [k (xymon)]
(k {:host "no-service.riemann.local"
:state "ok"
:description "Missing service, not transmitted"
:metric 4
:time (unix-time)})))
| (ns riemann.xymon-test
(:use riemann.xymon
[riemann.time :only [unix-time]]
clojure.test)
(:require [riemann.logging :as logging]))
(logging/init)
(deftest ^:xymon ^:integration xymon-test
(let [k (xymon nil)]
(k {:host "riemann.local"
:service "xymon test"
:state "green"
:description "all clear, uh, situation normal"
:metric -2
:time (unix-time)}))
(let [k (xymon nil)]
(k {:service "xymon test"
:state "green"
:description "all clear, uh, situation normal"
:metric 3.14159
:time (unix-time)}))
(let [k (xymon nil)]
(k {:host "riemann.local"
:service "xymon test"
:state "ok"
:description "all clear, uh, situation normal"
:metric 3.14159
:time (unix-time)}))
(let [k (xymon nil)]
(k {:host "no-service.riemann.local"
:state "ok"
:description "Missing service, not transmitted"
:metric 4
:time (unix-time)})))
|
Migrate to google custom search instead of dead image search. | (ns yetibot.core.models.google-search
(:require
[yetibot.core.util.http :refer [get-json map-to-query-string]]))
(def endpoint "http://ajax.googleapis.com/ajax/services/search/images")
(def configured? true)
(def ^:private format-result (juxt :url :contentNoFormatting))
(defn- fetch-image [q n]
(let [uri (str endpoint "?" (map-to-query-string
{:v "1.0" :rsz n
:q q :safe "active"}))]
(get-json uri)))
(defn image-search
([q] (image-search q 8))
([q n]
(map format-result
(-> (fetch-image q n) :responseData :results))))
| (ns yetibot.core.models.google-search
(:require
[yetibot.core.config :refer [get-config conf-valid?]]
[yetibot.core.util.http :refer [get-json map-to-query-string]]))
(def config (get-config :yetibot :models :google-search))
(def endpoint "https://www.googleapis.com/customsearch/v1")
(def configured? (conf-valid? config))
(defn- format-result [result]
[(-> (get-in result [:pagemap :cse_image])
rand-nth
:src)
(:title result)
(:link result)])
(defn- fetch-image [q n]
(let [uri (str endpoint "?" (map-to-query-string
{:key (:key config) :cx (:cx config)
:num n :q q :safe "high"}))]
(get-json uri)))
(defn image-search
([q] (image-search q 8))
([q n]
(map format-result
(-> (fetch-image q n) :items))))
|
Use :force true instead of production so that the airbrake appears in the right category on the website, and won't bother us. | (ns circle.util.test-airbrake
(:use circle.airbrake)
(:use midje.sweet))
(def div-by-zero (try (/ 1 0) (catch Exception e e)))
(fact "airbrake works"
(circle.airbrake/airbrake :exception div-by-zero) => (contains {:id integer? :error-id integer? :url string?})
(provided
(circle.env/env) => :production))
| (ns circle.util.test-airbrake
(:use circle.airbrake)
(:use midje.sweet))
(def div-by-zero (try (/ 1 0) (catch Exception e e)))
(fact "airbrake works"
(airbrake :exception div-by-zero :force true) => (contains {:id integer? :error-id integer? :url string?}))
|
Update dependency org.onyxplatform/onyx to version 0.7.3-20150901_142736-gd0de107. | (defproject org.onyxplatform/onyx-kafka "0.7.3-SNAPSHOT"
:description "Onyx plugin for Kafka"
:url "https://github.com/MichaelDrogalis/onyx-kafka"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:dependencies [[org.clojure/clojure "1.7.0"]
^{:voom {:repo "git@github.com:onyx-platform/onyx.git" :branch "master"}}
[org.onyxplatform/onyx "0.7.3-20150901_140443-g6e4750b"]
[clj-kafka "0.3.2" :exclusions [org.apache.zookeeper/zookeeper zookeeper-clj]]
[com.stuartsierra/component "0.2.3"]
[cheshire "5.5.0"]
[zookeeper-clj "0.9.3" :exclusions [io.netty/netty org.apache.zookeeper/zookeeper]]]
:profiles {:dev {:dependencies [[midje "1.7.0"]]
:plugins [[lein-midje "3.1.3"]]}
:circle-ci {:jvm-opts ["-Xmx4g"]}})
| (defproject org.onyxplatform/onyx-kafka "0.7.3-SNAPSHOT"
:description "Onyx plugin for Kafka"
:url "https://github.com/MichaelDrogalis/onyx-kafka"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:dependencies [[org.clojure/clojure "1.7.0"]
^{:voom {:repo "git@github.com:onyx-platform/onyx.git" :branch "master"}}
[org.onyxplatform/onyx "0.7.3-20150901_142736-gd0de107"]
[clj-kafka "0.3.2" :exclusions [org.apache.zookeeper/zookeeper zookeeper-clj]]
[com.stuartsierra/component "0.2.3"]
[cheshire "5.5.0"]
[zookeeper-clj "0.9.3" :exclusions [io.netty/netty org.apache.zookeeper/zookeeper]]]
:profiles {:dev {:dependencies [[midje "1.7.0"]]
:plugins [[lein-midje "3.1.3"]]}
:circle-ci {:jvm-opts ["-Xmx4g"]}})
|
Move custom collection check to test profile | (defproject lean-map "0.2.0"
:description "Lean Hash Array Mapped Trie implementation in ClojureScript"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:clean-targets ^{:protect false} ["resources/out"]
:jvm-opts ^:replace ["-Xms512m" "-Xmx512m" "-server"]
:dependencies [[org.clojure/clojure "1.7.0"]
[org.clojure/clojurescript "1.7.170"]
[collection-check "0.1.7-SNAPSHOT"]]
:plugins [[lein-doo "0.1.6-rc.1"]]
:cljsbuild {:builds
[{:id "test"
:source-paths ["src/main" "test"]
:compiler {:output-to "resources/public/js/testable.js"
:main cljs.lean-map.test.runner
:optimizations :none}}
{:id "node-test"
:source-paths ["src/main" "test"]
:compiler {:output-to "resources/public/js/testable.js"
:main cljs.lean-map.test.runner
:output-dir "target"
:target :nodejs
:optimizations :none}}]}) | (defproject lean-map "0.2.0"
:description "Lean Hash Array Mapped Trie implementation in ClojureScript"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:clean-targets ^{:protect false} ["resources/out"]
:jvm-opts ^:replace ["-Xms512m" "-Xmx512m" "-server"]
:dependencies [[org.clojure/clojure "1.7.0"]
[org.clojure/clojurescript "1.7.170"]]
:profiles {:test {:dependencies [[collection-check "0.1.7-SNAPSHOT"]]}}
:plugins [[lein-doo "0.1.6-rc.1"]]
:cljsbuild {:builds
[{:id "test"
:source-paths ["src/main" "test"]
:compiler {:output-to "resources/public/js/testable.js"
:main cljs.lean-map.test.runner
:optimizations :none}}
{:id "node-test"
:source-paths ["src/main" "test"]
:compiler {:output-to "resources/public/js/testable.js"
:main cljs.lean-map.test.runner
:output-dir "target"
:target :nodejs
:optimizations :none}}]}) |
Update dependency org.onyxplatform/onyx to version 0.7.3-20150901_140443-g6e4750b. | (defproject org.onyxplatform/onyx-kafka "0.7.3-SNAPSHOT"
:description "Onyx plugin for Kafka"
:url "https://github.com/MichaelDrogalis/onyx-kafka"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:dependencies [[org.clojure/clojure "1.7.0"]
^{:voom {:repo "git@github.com:onyx-platform/onyx.git" :branch "master"}}
[org.onyxplatform/onyx "0.7.3-20150828_160954-g51b5cf8"]
[clj-kafka "0.3.2" :exclusions [org.apache.zookeeper/zookeeper zookeeper-clj]]
[com.stuartsierra/component "0.2.3"]
[cheshire "5.5.0"]
[zookeeper-clj "0.9.3" :exclusions [io.netty/netty org.apache.zookeeper/zookeeper]]]
:profiles {:dev {:dependencies [[midje "1.7.0"]]
:plugins [[lein-midje "3.1.3"]]}
:circle-ci {:jvm-opts ["-Xmx4g"]}})
| (defproject org.onyxplatform/onyx-kafka "0.7.3-SNAPSHOT"
:description "Onyx plugin for Kafka"
:url "https://github.com/MichaelDrogalis/onyx-kafka"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:dependencies [[org.clojure/clojure "1.7.0"]
^{:voom {:repo "git@github.com:onyx-platform/onyx.git" :branch "master"}}
[org.onyxplatform/onyx "0.7.3-20150901_140443-g6e4750b"]
[clj-kafka "0.3.2" :exclusions [org.apache.zookeeper/zookeeper zookeeper-clj]]
[com.stuartsierra/component "0.2.3"]
[cheshire "5.5.0"]
[zookeeper-clj "0.9.3" :exclusions [io.netty/netty org.apache.zookeeper/zookeeper]]]
:profiles {:dev {:dependencies [[midje "1.7.0"]]
:plugins [[lein-midje "3.1.3"]]}
:circle-ci {:jvm-opts ["-Xmx4g"]}})
|
Create 'report an issue' form ui | ;; Functions for sending feedback
(ns robinson.feedback
(:require [clj-http.client :as client]
[seesaw.core :as ss]
[clojure.data.json :as json]))
(defn send-report [state]
nil)
| ;; Functions for sending feedback
(ns robinson.feedback
(:require [clj-http.client :as client]
[seesaw.core :as ss]
[seesaw.forms :as ss-forms]
[clojure.data.json :as json]))
(defn frame-content
[]
(ss-forms/forms-panel
"pref,4dlu,80dlu,8dlu,pref,4dlu,80dlu"
:column-groups [[1 5]]
:items [(ss-forms/separator "General")
"Company" (ss-forms/span (ss/text) 5)
"Contact" (ss-forms/span (ss/text) 5)
(ss-forms/separator "Propeller")
"PTI/kW" (ss/text :columns 10) "Power/kW" (ss/text :columns 10)
"R/mm" (ss/text :columns 10) "D/mm" (ss/text :columns 10)]
:default-dialog-border? true))
(defn send-report [state]
(let [
upload-input (ss/checkbox :selected? true)
description-input (ss/text :columns 80 :rows 25 :multi-line? true :wrap-lines? true)
send-button (ss/button :text "Send")
cancel-button (ss/button :text "Cancel")
content (ss-forms/forms-panel
"right:pref,4dlu,pref"
:items [
"Date:" (str (new java.util.Date))
"Version:" (get state :version)
"User-id:" (get state :user-id)
"Upload save?" upload-input
"What happened?" description-input
"" send-button (ss-forms/next-line)
"" cancel-button])]
(->
(ss/frame :title "Report an Issue",
:content content
:resizable? false
:on-close :hide)
ss/pack!
ss/show!)))
|
Switch to the canonical markdown-clj. | ;; Copyright 2014 Red Hat, Inc, and individual contributors.
;;
;; 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.
;; *** NOTE: update the version in docs.clj when you change it here ***
(defproject org.immutant/build-helper "0.1.6"
:description "A plugin to aid in building Immutant"
:url "https://github.com/immutant/immutant"
:license {:name "Apache Software License - v 2.0"
:url "http://www.apache.org/licenses/LICENSE-2.0"
:distribution :repo}
:dependencies [[org.clojars.tcrawley/codox.core "0.8.0a"]
;;[codox/codox.core "0.8.0"]
[org.clojars.tcrawley/markdown-clj "0.9.43a"]
;;[markdown-clj "0.9.43"]
]
:eval-in-leiningen true
:signing {:gpg-key "BFC757F9"})
| ;; Copyright 2014 Red Hat, Inc, and individual contributors.
;;
;; 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.
;; *** NOTE: update the version in docs.clj when you change it here ***
(defproject org.immutant/build-helper "0.1.6"
:description "A plugin to aid in building Immutant"
:url "https://github.com/immutant/immutant"
:license {:name "Apache Software License - v 2.0"
:url "http://www.apache.org/licenses/LICENSE-2.0"
:distribution :repo}
:dependencies [[org.clojars.tcrawley/codox.core "0.8.0a"]
;;[codox/codox.core "0.8.0"]
[markdown-clj "0.9.44"]]
:eval-in-leiningen true
:signing {:gpg-key "BFC757F9"})
|
Fix bug on stop http-kit server. | (ns pfrt.web
(:require [compojure.handler :as handler]
[org.httpkit.server :as hkit]
[pfrt.web.routes :refer [app]]
[pfrt.core.lifecycle :refer [ILifecycle]]))
(defrecord Web
[webserver app]
ILifecycle
(init [this system]
(assoc system :web this))
(start [this system]
(let [port (get-in system [:config :port] 9090)
stopfn (hkit/run-server app {:port port})]
(swap! webserver (fn [_] stopfn))
(println (format "Listening: http://localhost:%s/" port))
system))
(stop [_ system]
(let [stopfn (deref webserver)]
(@stopfn)
system)))
(defn web-server
[config pf]
(let [wrap-context (fn [h]
(fn [req]
(h (assoc req :ctx {:pf pf}))))]
(->Web (atom nil) (handler/api (wrap-context app)))))
| (ns pfrt.web
(:require [compojure.handler :as handler]
[org.httpkit.server :as hkit]
[pfrt.web.routes :refer [app]]
[pfrt.core.lifecycle :refer [ILifecycle]]))
(defrecord Web
[webserver app]
ILifecycle
(init [this system]
(assoc system :web this))
(start [this system]
(let [port (get-in system [:config :port] 9090)
stopfn (hkit/run-server app {:port port})]
(swap! webserver (fn [_] stopfn))
(println (format "Listening: http://localhost:%s/" port))
system))
(stop [_ system]
(let [stopfn (deref webserver)]
(stopfn)
system)))
(defn web-server
[config pf]
(let [wrap-context (fn [h]
(fn [req]
(h (assoc req :ctx {:pf pf}))))]
(->Web (atom nil) (handler/api (wrap-context app)))))
|
Allow rolling logs to be disabled | (ns yetibot.core.logging
(:require
[schema.core :as s]
[yetibot.core.config :refer [get-config]]
[yetibot.core.util :refer [with-fresh-db]]
[yetibot.core.db.log :as log]
[taoensso.timbre.appenders.3rd-party.rolling :refer [rolling-appender]]
[taoensso.timbre.appenders.core :refer [println-appender]]
[taoensso.timbre
:as timbre
:refer [trace debug info warn error fatal spy with-log-level]]))
(def config-schema String)
(defn log-level []
(let [v (get-config config-schema [:yetibot :log :level])]
(if (:error v)
;; default config level
:warn
(keyword (:value v)))))
(defn start []
(timbre/set-config!
{:level (log-level)
:appenders
;; stdout
{:println (println-appender {:stream :auto})
;; rolling log files
:rolling-appender (rolling-appender {:path "/var/log/yetibot/yetibot.log"
:pattern :daily})}})
)
| (ns yetibot.core.logging
(:require
[schema.core :as s]
[yetibot.core.config :refer [get-config]]
[yetibot.core.util :refer [with-fresh-db]]
[yetibot.core.db.log :as log]
[taoensso.timbre.appenders.3rd-party.rolling :refer [rolling-appender]]
[taoensso.timbre.appenders.core :refer [println-appender]]
[taoensso.timbre
:as timbre
:refer [trace debug info warn error fatal spy with-log-level]]))
(def config-schema String)
(defn log-level []
(let [v (get-config config-schema [:yetibot :log :level])]
(if (:error v)
;; default config level
:warn
(keyword (:value v)))))
(defn rolling-appender-enabled?
"Rolling appender is enabled by default. Disable it by setting enabled=false"
[]
(let [v (get-config String [:yetibot :log :rolling :enabled])]
(if-let [enabled (:value v)]
(not= enabled "false")
true)))
(defn start []
(if (rolling-appender-enabled?)
(timbre/set-config!
{:level (log-level)
:appenders
;; stdout
{:println (println-appender {:stream :auto})
;; rolling log files
:rolling-appender (rolling-appender
{:path "/var/log/yetibot/yetibot.log"
:pattern :daily})}})))
|
Refactor RocksDB test to improve DB directory handling | (ns clstreams.rocksdb-test
(:require [clstreams.rocksdb :as sut]
[clojure.test :refer :all]))
(defn delete-recursively [fname]
(let [file (clojure.java.io/file fname)]
(if (.exists (clojure.java.io/as-file file))
(doseq [f (reverse (file-seq file))]
(clojure.java.io/delete-file f)))))
(deftest rocksdb-open-test
(testing "can open a rocksdb DB"
(delete-recursively "/tmp/ddeDB")
(with-open [db (sut/create-db "/tmp/ddeDB/somedb")]
(is (instance? Object db)))
(delete-recursively "/tmp/ddeDB")))
| (ns clstreams.rocksdb-test
(:require [clstreams.rocksdb :as sut]
[clojure.test :refer :all]
[clojure.java.io :as io]))
(def db-dir "/tmp/ddeDB/somedb")
(def db-dir-file (io/file db-dir))
(defn delete-recursively [file]
(if (.exists file)
(doseq [f (reverse (file-seq file))]
(io/delete-file f))))
(defn clean-db-fixture [run-test]
(let [base-dir-file (.getParentFile db-dir-file)]
(delete-recursively base-dir-file)
(run-test)
(delete-recursively base-dir-file)))
(use-fixtures :each clean-db-fixture)
(deftest rocksdb-open-test
(testing "can open a rocksdb DB"
(with-open [db (sut/create-db db-dir)]
(is (instance? Object db)))))
|
Send e-mail to rightful subscribers. | (ns clj.medusa.alert
(:require [amazonica.aws.simpleemail :as ses]
[amazonica.core :as aws]
[clojure.string :as string]
[clj.medusa.config :as config]
[clj.medusa.db :as db]
[clj.medusa.config :as config]))
(defn send-email [subject body destinations]
(let [destinations ["rvitillo@mozilla.com"]] ;; TODO: remove once everything works
(when-not (:dry-run @config/state)
(ses/send-email :destination {:to-addresses destinations}
:source "telemetry-alerts@mozilla.com"
:message {:subject subject
:body {:html (str "<a href=\"" body "\">" body "</a>")}}))))
(defn notify-subscribers [{:keys [metric_id date emails]}]
(let [{:keys [hostname]} @config/state
foreign_subscribers (string/split emails #",")
{metric_name :name,
detector_id :detector_id
metric_id :id} (db/get-metric metric_id)
{detector_name :name} (db/get-detector detector_id)
subscribers (db/get-subscribers-for-metric metric_id)]
(send-email (str "Alert for " metric_name " (" detector_name ") on the " date)
(str "http://" hostname "/index.html#/detectors/" detector_id "/"
"metrics/" metric_id "/alerts/?from=" date "&to=" date)
(concat subscribers foreign_subscribers ["dev-telemetry-alerts@lists.mozilla.org"]))))
| (ns clj.medusa.alert
(:require [amazonica.aws.simpleemail :as ses]
[amazonica.core :as aws]
[clojure.string :as string]
[clj.medusa.config :as config]
[clj.medusa.db :as db]
[clj.medusa.config :as config]))
(defn send-email [subject body destinations]
(when-not (:dry-run @config/state)
(ses/send-email :destination {:to-addresses destinations}
:source "telemetry-alerts@mozilla.com"
:message {:subject subject
:body {:html (str "<a href=\"" body "\">" body "</a>")}})))
(defn notify-subscribers [{:keys [metric_id date emails]}]
(let [{:keys [hostname]} @config/state
foreign_subscribers (string/split emails #",")
{metric_name :name,
detector_id :detector_id
metric_id :id} (db/get-metric metric_id)
{detector_name :name} (db/get-detector detector_id)
subscribers (db/get-subscribers-for-metric metric_id)]
(send-email (str "Alert for " metric_name " (" detector_name ") on the " date)
(str "http://" hostname "/index.html#/detectors/" detector_id "/"
"metrics/" metric_id "/alerts/?from=" date "&to=" date)
(concat subscribers foreign_subscribers ["dev-telemetry-alerts@lists.mozilla.org"]))))
|
Fix missing require for clojure.java.io | ;-
; Copyright 2011 (c) Meikel Brandmeyer.
; All rights reserved.
;
; Permission is hereby granted, free of charge, to any person obtaining a copy
; of this software and associated documentation files (the "Software"), to deal
; in the Software without restriction, including without limitation the rights
; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
; copies of the Software, and to permit persons to whom the Software is
; furnished to do so, subject to the following conditions:
;
; The above copyright notice and this permission notice shall be included in
; all copies or substantial portions of the Software.
;
; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
; THE SOFTWARE.
(ns vimclojure.core)
(defn init-server
[]
(binding [*ns* *ns*]
(in-ns 'user)
(refer-clojure)
; Check for doc macro. 1.2 in c.core, 1.3 in c.repl
(when-not (ns-resolve 'clojure.core 'doc)
(use 'clojure.repl))
(when (io/resource "user.clj")
(load "user"))))
| ;-
; Copyright 2011 (c) Meikel Brandmeyer.
; All rights reserved.
;
; Permission is hereby granted, free of charge, to any person obtaining a copy
; of this software and associated documentation files (the "Software"), to deal
; in the Software without restriction, including without limitation the rights
; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
; copies of the Software, and to permit persons to whom the Software is
; furnished to do so, subject to the following conditions:
;
; The above copyright notice and this permission notice shall be included in
; all copies or substantial portions of the Software.
;
; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
; THE SOFTWARE.
(ns vimclojure.core
(:require
[clojure.java.io :as io]))
(defn init-server
[]
(binding [*ns* *ns*]
(in-ns 'user)
(refer-clojure)
; Check for doc macro. 1.2 in c.core, 1.3 in c.repl
(when-not (ns-resolve 'clojure.core 'doc)
(use 'clojure.repl))
(when (io/resource "user.clj")
(load "user"))))
|
Add equality fixes on Person class, so we can find clashes | (in-ns 'herder.solver.types)
(gen-class
:name ^{PlanningEntity {}} herder.solver.types.Person
:prefix "person-"
:init init
:state state
:constructors {[] []
[java.util.UUID] []}
:methods [[getId [] java.util.UUID]
[getName [] String]
[setName [String] void]])
(defn- person-init
([] (person-init (java.util.UUID/randomUUID)))
([uuid] [[] (ref {:id uuid :name ""})]))
(defn- person-getId [this]
(getValue this :id))
(defn- person-getName [this]
(getValue this :name))
(defn- person-setName [this item]
(setValue this :name item))
| (in-ns 'herder.solver.types)
(gen-class
:name ^{PlanningEntity {}} herder.solver.types.Person
:prefix "person-"
:init init
:state state
:constructors {[] []
[java.util.UUID] []}
:methods [[getId [] java.util.UUID]
[getName [] String]
[setName [String] void]])
(defn- person-init
([] (person-init (java.util.UUID/randomUUID)))
([uuid] [[] (ref {:id uuid :name ""})]))
(defn- person-getId [this]
(getValue this :id))
(defn- person-getName [this]
(getValue this :name))
(defn- person-setName [this item]
(setValue this :name item))
(defn- person-equals [this b]
(= (person-getId this) (person-getId b)))
(defn- person-hashCode [this]
(.hashCode (person-getId this)))
|
Fix Reagent-related bug in bindings. | ; Copyright (c) 2015 Designed.ly, Marcin Bilski
; The use and distribution terms for this software are covered by the
; Eclipse Public License which can be found in the file LICENSE 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 reforms.binding.core
(:refer-clojure :exclude [reset! swap! deref get-in -deref -reset!])
(:require
[reforms.binding.protocol :refer [-valid? -deref -reset! -get-in -path]]))
(defn valid? [x]
(-valid? x))
(defn deref [x]
(-deref x))
(defn reset!
([x v]
(-reset! x v))
([x ks v]
(if (not-empty ks)
(-reset! x ks v)
(-reset! x v))))
(defn get-in [x ks]
(if (not-empty ks)
(-get-in x ks)
x))
(defn path [x]
(-path x))
| ; Copyright (c) 2015 Designed.ly, Marcin Bilski
; The use and distribution terms for this software are covered by the
; Eclipse Public License which can be found in the file LICENSE 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 reforms.binding.core
(:refer-clojure :exclude [reset! swap! deref get-in -deref -reset!])
(:require
[reforms.binding.protocol :refer [-valid? -deref -reset! -get-in -path]]))
(defn valid? [x]
(-valid? x))
(defn deref [x]
(-deref x))
(defn reset!
([x v]
(-reset! x v))
([x ks v]
(js/console.log "reset!" (prn-str x) (prn-str ks) (prn-str v))
(if (not-empty ks)
(-reset! x ks v)
(-reset! x v))))
(defn get-in [x ks]
(let [result (if (not-empty ks)
(-get-in x ks)
(-deref x))]
(js/console.log "get-in" (prn-str x) (prn-str ks) (prn-str result))
result))
(defn path [x]
(-path x))
|
Define meta->write-path and modify behaviour of Parse->path. | (ns incise.parsers.helpers
(:require (clj-time [core :as tm]
[coerce :as tc])
[clojure.string :as s])
(:import [java.io File]))
(defn dashify
"Dashify a title, replacing all non word characters with a dash."
[^String title]
(-> title
(s/lower-case)
(s/replace #"[^\w]" "-")))
(defn date-time->path
"Convert a DateTime to a path like string."
[date-time]
(str (when date-time
(str (tm/year date-time) \/
(tm/month date-time) \/
(tm/day date-time) \/))))
(def date-str->path (comp date-time->path tc/from-string))
(defn Parse->path
[^Parse {:keys [path date title extension]}]
(or path
(str (date-str->path date)
(dashify title)
extension)))
(defn extension [^File file]
"Get the extension, enforcing lower case, on the given file."
(-> file
(.getName)
(s/split #"\.")
(last)
(s/lower-case)))
| (ns incise.parsers.helpers
(:require (clj-time [core :as tm]
[coerce :as tc])
[clojure.string :as s])
(:import [java.io File]))
(defn dashify
"Dashify a title, replacing all non word characters with a dash."
[^String title]
(-> title
(s/lower-case)
(s/replace #"[^\w]" "-")))
(defn date-time->path
"Convert a DateTime to a path like string."
[date-time]
(str (when date-time
(str (tm/year date-time) \/
(tm/month date-time) \/
(tm/day date-time) \/))))
(def date-str->path (comp date-time->path tc/from-string))
(defn meta->write-path
[{:keys [path date title extension]}]
(or path
(str (date-str->path date)
(dashify title)
extension)))
(defn remove-trailing-index-html [path]
(s/replace path #"/index\.html$" "/"))
(defn Parse->path [parse]
(->> parse
(:path)
(remove-trailing-index-html)
(str \/)))
(defn extension [^File file]
"Get the extension, enforcing lower case, on the given file."
(-> file
(.getName)
(s/split #"\.")
(last)
(s/lower-case)))
|
Include mock-monad tests in CLJS test runner. | (ns active.clojure.test-runner
(:require [doo.runner :refer-macros [doo-tests]]
[active.clojure.condition-test]
[active.clojure.debug-test]
[active.clojure.lens-test]
[active.clojure.monad-test]
[active.clojure.record-test]
[active.clojure.record-spec-test]
[active.clojure.match-test]
[active.clojure.config-test]))
(doo-tests 'active.clojure.condition-test
'active.clojure.debug-test
'active.clojure.lens-test
'active.clojure.monad-test
'active.clojure.record-test
'active.clojure.record-spec-test
'active.clojure.match-test
'active.clojure.config-test)
| (ns active.clojure.test-runner
(:require [doo.runner :refer-macros [doo-tests]]
[active.clojure.condition-test]
[active.clojure.debug-test]
[active.clojure.lens-test]
[active.clojure.monad-test]
[active.clojure.mock-monad-test]
[active.clojure.record-test]
[active.clojure.record-spec-test]
[active.clojure.match-test]
[active.clojure.config-test]))
(doo-tests 'active.clojure.condition-test
'active.clojure.debug-test
'active.clojure.lens-test
'active.clojure.monad-test
'active.clojure.mock-monad-test
'active.clojure.record-test
'active.clojure.record-spec-test
'active.clojure.match-test
'active.clojure.config-test)
|
Revert to released version of the Kafka libraries. | (defproject clstreams "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url "http://example.com/FIXME"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:dependencies [[org.clojure/clojure "1.8.0"]
[org.clojure/tools.namespace "0.3.0-alpha3"]
[org.apache.kafka/kafka-clients "0.10.2.1-rc2"]
[org.apache.kafka/kafka-clients "0.10.2.1-rc2" :classifier "test"]
[org.apache.kafka/kafka-streams "0.10.2.1-rc2"]
[org.apache.kafka/kafka-streams "0.10.2.1-rc2" :classifier "test"]]
:main ^:skip-aot clstreams.core
:target-path "target/%s"
:profiles {:uberjar {:aot :all}})
| (defproject clstreams "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url "http://example.com/FIXME"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:dependencies [[org.clojure/clojure "1.8.0"]
[org.clojure/tools.namespace "0.3.0-alpha3"]
[org.apache.kafka/kafka-clients "0.10.2.0"]
[org.apache.kafka/kafka-clients "0.10.2.0" :classifier "test"]
[org.apache.kafka/kafka-streams "0.10.2.0"]
[org.apache.kafka/kafka-streams "0.10.2.0" :classifier "test"]]
:main ^:skip-aot clstreams.core
:target-path "target/%s"
:profiles {:uberjar {:aot :all}})
|
Return only the name of an attack move | (ns cruncher.moves.main
(:require [cruncher.moves.data :as data]))
(defn get
"Return move object from moves-database by the move id."
[id]
(id data/all)) | (ns cruncher.moves.main
(:require [cruncher.moves.data :as data]))
(defn get-name
"Return move object from moves-database by the move id."
[id]
(:name (get data/all id))) |
Revert "Add warning for people that upgrade to newer versions" | (ns day8.re-frame.trace.preload
(:require [day8.re-frame.trace :as trace]
[mranderson047.re-frame.v0v10v2.re-frame.core :as rf]))
;; Use this namespace with the :preloads compiler option to perform the necessary setup for enabling tracing:
;; {:compiler {:preloads [day8.re-frame.trace.preload] ...}}
(js/console.warn "re-frame-trace has been renamed to re-frame-10x: (https://clojars.org/day8.re-frame/re-frame-10x). Update to newer versions of this library by using the `day8.re-frame/re-frame-10x` artifact ID. Thanks!")
(rf/clear-subscription-cache!)
(trace/init-db!)
(defonce _ (trace/init-tracing!))
(trace/inject-devtools!)
| (ns day8.re-frame.trace.preload
(:require [day8.re-frame.trace :as trace]
[mranderson047.re-frame.v0v10v2.re-frame.core :as rf]))
;; Use this namespace with the :preloads compiler option to perform the necessary setup for enabling tracing:
;; {:compiler {:preloads [day8.re-frame.trace.preload] ...}}
(rf/clear-subscription-cache!)
(trace/init-db!)
(defonce _ (trace/init-tracing!))
(trace/inject-devtools!)
|
Return nil if URI fragment is not found | (ns trak.globals
(:require-macros [trak.config :refer [cljs-env]])
(:require [trak.utils :as utils]
[clojure.string :as str])
(:import goog.Uri
goog.Uri.QueryData
goog.string))
(defn build-query-params [kws]
(utils/info kws)
(utils/info (.createFromKeysValues QueryData (map name (keys kws)) (vals kws)))
(reduce #(.add %1
(name (first %2))
(second %2))
(QueryData.)
kws)
)
(defn spotify-authorization-link [scope]
(doto (Uri. "https://accounts.spotify.com/authorize")
(.setQuery (build-query-params {:response_type "token"
:client_id (cljs-env :spotify-client-id)
:scope scope
:redirect_uri (cljs-env :spotify-redirect-url)
:state (.getRandomString string)}))))
(defn get-spotify-auth-token []
(let [fragment (.getFragment (Uri. (.-href (.-location js/document))))
fragment (str/split fragment "&")]
(reduce (fn [acc part]
(let [kw (str/split part "=")]
(merge acc {(keyword (first kw)) (second kw)})))
{}
fragment)))
| (ns trak.globals
(:require-macros [trak.config :refer [cljs-env]])
(:require [trak.utils :as utils]
[clojure.string :as str])
(:import goog.Uri
goog.Uri.QueryData
goog.string))
(defn build-query-params [kws]
(utils/info kws)
(utils/info (.createFromKeysValues QueryData (map name (keys kws)) (vals kws)))
(reduce #(.add %1
(name (first %2))
(second %2))
(QueryData.)
kws)
)
(defn spotify-authorization-link [scope]
(doto (Uri. "https://accounts.spotify.com/authorize")
(.setQuery (build-query-params {:response_type "token"
:client_id (cljs-env :spotify-client-id)
:scope scope
:redirect_uri (cljs-env :spotify-redirect-url)
:state (.getRandomString string)}))))
(defn get-spotify-auth-token []
(let [fragment (.getFragment (Uri. (.-href (.-location js/document))))]
(cond (= "" fragment) nil
:else (let [fragment (str/split fragment "&")]
(reduce (fn [acc part]
(let [kw (str/split part "=")]
(merge acc {(keyword (first kw)) (second kw)})))
{}
fragment)))))
|
Add repl-utils dep to have a dormant show laying around. | (defproject com.draines/postal "1.8-SNAPSHOT"
:repositories {"java.net" "http://download.java.net/maven/2"}
:dependencies [[org.clojure/clojure "1.3.0"]
[javax.mail/mail "1.4.4"
:exclusions [javax.activation/activation]]])
| (defproject com.draines/postal "1.8-SNAPSHOT"
:repositories {"java.net" "http://download.java.net/maven/2"}
:dependencies [[org.clojure/clojure "1.3.0"]
[javax.mail/mail "1.4.4"
:exclusions [javax.activation/activation]]
[org.clojure.contrib/repl-utils "1.3.0-alpha4"]])
|
Prepare for next release cycle. | (defproject org.onyxplatform/onyx-metrics "0.8.0.7"
:description "Instrument Onyx workflows"
:url "https://github.com/MichaelDrogalis/onyx"
: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}}
:dependencies [[org.clojure/clojure "1.7.0"]
[interval-metrics "1.0.0"]
[stylefruits/gniazdo "0.4.0"]]
:java-opts ^:replace ["-server" "-Xmx3g"]
:global-vars {*warn-on-reflection* true
*assert* false
*unchecked-math* :warn-on-boxed}
:profiles {:dev {:dependencies [^{:voom {:repo "git@github.com:onyx-platform/onyx.git" :branch "master"}}
[org.onyxplatform/onyx "0.8.0"]
[riemann-clojure-client "0.4.1"]]
:plugins [[lein-set-version "0.4.1"]
[lein-update-dependency "0.1.2"]
[lein-pprint "1.1.1"]]}})
| (defproject org.onyxplatform/onyx-metrics "0.8.0.8-SNAPSHOT"
:description "Instrument Onyx workflows"
:url "https://github.com/MichaelDrogalis/onyx"
: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}}
:dependencies [[org.clojure/clojure "1.7.0"]
[interval-metrics "1.0.0"]
[stylefruits/gniazdo "0.4.0"]]
:java-opts ^:replace ["-server" "-Xmx3g"]
:global-vars {*warn-on-reflection* true
*assert* false
*unchecked-math* :warn-on-boxed}
:profiles {:dev {:dependencies [^{:voom {:repo "git@github.com:onyx-platform/onyx.git" :branch "master"}}
[org.onyxplatform/onyx "0.8.0"]
[riemann-clojure-client "0.4.1"]]
:plugins [[lein-set-version "0.4.1"]
[lein-update-dependency "0.1.2"]
[lein-pprint "1.1.1"]]}})
|
Attach ^:riak metadata to ns | (ns icecap.store.riak-integration-test
(:require [icecap.store.riak :refer :all]
[icecap.store.test-props :refer :all]
[clojure.test.check.clojure-test :refer [defspec]]
[clojure.test :refer :all]
[clojurewerkz.welle.buckets :as wb]
[clojurewerkz.welle.core :as wc]))
(def ^:private riak-test-url "http://localhost:8098/riak")
(def ^:private riak-test-store)
(defn connect
[f]
(let [conn (wc/connect riak-test-url)
store (riak-store conn "test-bucket")]
(try
(wb/update conn "test-bucket" (bucket-props))
(with-redefs-fn {#'riak-test-store store} f)
(finally
(wc/shutdown conn)))))
(use-fixtures :once connect)
(defspec ^:riak riak-store-roundtrip
(roundtrip-prop riak-test-store))
(defspec ^:riak riak-store-delete
(delete-prop riak-test-store))
| (ns ^:riak icecap.store.riak-integration-test
(:require [icecap.store.riak :refer :all]
[icecap.store.test-props :refer :all]
[clojure.test.check.clojure-test :refer [defspec]]
[clojure.test :refer :all]
[clojurewerkz.welle.buckets :as wb]
[clojurewerkz.welle.core :as wc]))
(def ^:private riak-test-url "http://localhost:8098/riak")
(def ^:private riak-test-store)
(defn connect
[f]
(let [conn (wc/connect riak-test-url)
store (riak-store conn "test-bucket")]
(try
(wb/update conn "test-bucket" (bucket-props))
(with-redefs-fn {#'riak-test-store store} f)
(finally
(wc/shutdown conn)))))
(use-fixtures :once connect)
(defspec riak-store-roundtrip
(roundtrip-prop riak-test-store))
(defspec riak-store-delete
(delete-prop riak-test-store))
|
Fix migration 2 (spec->project) which didn't migrate :inferred, and had a bad assertion. | (ns circle.db.migrations
(:require [clojure.set :as set])
(:use circle.db.migration-lib)
(:require [somnium.congomongo :as mongo])
(:use [circle.util.core :only (apply-if)]))
(clear-migrations)
(def-migration "failed? -> failed"
:num 0
:coll :builds
:transform #(set/rename-keys % {:failed? :failed}))
(def-migration "infer empty specs"
:num 1
:coll :projects
:transform (fn [project]
(let [spec (mongo/fetch-one :specs :where {:project_id (-> project :_id)})
inferred? (or
(nil? spec)
(every? empty? ((juxt :dependencies :test :compile :setup) spec)))]
(assoc project :inferred inferred?))))
(def-migration "move specs into project"
:num 2
:coll :projects
:transform (fn [p]
(assert (= 1 (mongo/fetch :specs :where {:project_id (:_id p)} :count? true)))
(let [spec (mongo/fetch-one :specs :where {:project_id (:_id p)})]
(apply-if spec merge p (select-keys spec [:dependencies :setup :compile :test])))))
;; (def-migration "old builds w/ git commit info")
"action tags; inferred, infrastructure, spec, test, setup"
"add end time to old builds"
| (ns circle.db.migrations
(:require [clojure.set :as set])
(:use circle.db.migration-lib)
(:require [somnium.congomongo :as mongo])
(:use [circle.util.core :only (apply-if)]))
(clear-migrations)
(def-migration "failed? -> failed"
:num 0
:coll :builds
:transform #(set/rename-keys % {:failed? :failed}))
(def-migration "infer empty specs"
:num 1
:coll :projects
:transform (fn [project]
(let [spec (mongo/fetch-one :specs :where {:project_id (-> project :_id)})
inferred? (or
(nil? spec)
(every? empty? ((juxt :dependencies :test :compile :setup) spec)))]
(assoc project :inferred inferred?))))
(def-migration "move specs into project"
:num 2
:coll :projects
:transform (fn [p]
(assert (> 2 (mongo/fetch-count :specs :where {:project_id (:_id p)})))
(let [spec (mongo/fetch-one :specs :where {:project_id (:_id p)})]
(apply-if spec merge p (select-keys spec [:dependencies :setup :compile :test :inferred])))))
;; (def-migration "old builds w/ git commit info")
"action tags; inferred, infrastructure, spec, test, setup"
"add end time to old builds"
|
Remove clj->js function, now that it's in cljs.core. | (ns c2.util
(:require [singult.core :as singult]))
(def clj->js singult/clj->js)
(defn ->coll
"Convert something into a collection, if it's not already."
[x]
(if (coll? x) x [x]))
| (ns c2.util
(:require [singult.core :as singult]))
(defn ->coll
"Convert something into a collection, if it's not already."
[x]
(if (coll? x) x [x]))
|
Move a pixel pair from second segment to first segment in geodesic layout. | (hash-map
:layout
(layout/geodesic-grid
:radius 3.688
:pixel-spacing 0.02
:strut-pixels
[48 64 64 64]
:strip-struts
[[0 6 15 8]
[2 14 22 16]
[4 18 20 23]
[3 10 12 19]
[1 5 7 11]])
#_
(layout/star
:radius 3.688 ; 12.1'
:pixel-spacing 0.02 ; 2 cm
:strip-pixels 240
:strips 6)
:event-handler
(-> state/update-mode
handler/mode-selector
(handler/autocycle-modes
(comp #{:button/press :button/repeat} :type)))
:web-options
{:port 8080
:min-threads 2
:max-threads 5
:max-queued 25}
:modes
{:rainbow
(mode/rainbow)
:strobe
(mode/strobe
[(color/rgb 1 0 0)
(color/rgb 0 1 0)
(color/rgb 0 0 1)])
:lantern
(mode/lantern 0.5)}
:playlist
[:rainbow
:strobe
:lantern])
| (hash-map
:layout
(layout/geodesic-grid
:radius 3.688
:pixel-spacing 0.02
:strut-pixels
[50 62 64 64]
:strip-struts
[[0 6 15 8]
[2 14 22 16]
[4 18 20 23]
[3 10 12 19]
[1 5 7 11]])
#_
(layout/star
:radius 3.688 ; 12.1'
:pixel-spacing 0.02 ; 2 cm
:strip-pixels 240
:strips 6)
:event-handler
(-> state/update-mode
handler/mode-selector
(handler/autocycle-modes
(comp #{:button/press :button/repeat} :type)))
:web-options
{:port 8080
:min-threads 2
:max-threads 5
:max-queued 25}
:modes
{:rainbow
(mode/rainbow)
:strobe
(mode/strobe
[(color/rgb 1 0 0)
(color/rgb 0 1 0)
(color/rgb 0 0 1)])
:lantern
(mode/lantern 0.5)}
:playlist
[:rainbow
:strobe
:lantern])
|
Use lein-bin to generate a jar-packed .bat file. | (defproject kwho "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url "https://github.com/jacobmorzinski/kwho"
:license {:name "The MIT License"
:url "http://opensource.org/licenses/MIT"}
:dependencies [[org.clojure/clojure "1.6.0"]]
:main ^:skip-aot kwho.core
:target-path "target/%s"
:profiles {:uberjar {:aot :all}})
| (defproject kwho "0.1.0"
:description "FIXME: write description"
:url "https://github.com/jacobmorzinski/kwho"
:license {:name "The MIT License"
:url "http://opensource.org/licenses/MIT"}
:dependencies [[org.clojure/clojure "1.6.0"]]
:plugins [[lein-bin "0.3.6-SNAPSHOT"]] #_ "https://github.com/jacobmorzinski/lein-bin"
:bin {:name "kwho.bat"} #_ "I wish I could use a conditional..."
:main ^:skip-aot kwho.core
:target-path "target/%s"
:jar-exclusions [#"(^|\\|/)[._](.*\.|)s[a-w][a-z]$"] #_ "vim .swp files"
:profiles {:uberjar {:aot :all}})
|
Add refer-clojure to avoid 1.9 compilation warning | ;; Copyright © 2015, JUXT LTD.
(ns yada.boolean
(:require
[schema.core :as s]))
(defn boolean? [x]
(contains? #{true false} x))
(declare BooleanExpression)
(s/defschema NotExpression
[(s/one (s/eq :not) "not") (s/one (s/recursive #'BooleanExpression) "not expr")])
(s/defschema AndExpression
[(s/one (s/eq :and) "and") (s/recursive #'BooleanExpression)])
(s/defschema OrExpression
[(s/one (s/eq :or) "or") (s/recursive #'BooleanExpression)])
(s/defschema CompositeExpression
(s/conditional
(comp (partial = :not) first) NotExpression
(comp (partial = :and) first) AndExpression
(comp (partial = :or) first) OrExpression))
(s/defschema BooleanExpression
(s/conditional
boolean? s/Bool
vector? CompositeExpression
:else s/Any))
| ;; Copyright © 2015, JUXT LTD.
(ns yada.boolean
(:refer-clojure :exclude [boolean?])
(:require
[schema.core :as s]))
(defn boolean? [x]
(contains? #{true false} x))
(declare BooleanExpression)
(s/defschema NotExpression
[(s/one (s/eq :not) "not") (s/one (s/recursive #'BooleanExpression) "not expr")])
(s/defschema AndExpression
[(s/one (s/eq :and) "and") (s/recursive #'BooleanExpression)])
(s/defschema OrExpression
[(s/one (s/eq :or) "or") (s/recursive #'BooleanExpression)])
(s/defschema CompositeExpression
(s/conditional
(comp (partial = :not) first) NotExpression
(comp (partial = :and) first) AndExpression
(comp (partial = :or) first) OrExpression))
(s/defschema BooleanExpression
(s/conditional
boolean? s/Bool
vector? CompositeExpression
:else s/Any))
|
Connect blocking to avoid duplicate connections | (ns uk.org.potentialdifference.darknet.websocket
(:import [org.java_websocket.client WebSocketClient]
[org.java_websocket.drafts Draft_10]
[java.net URI]))
(defn connect! [url options]
(.connect (proxy [WebSocketClient]
[(new URI url) (new Draft_10)]
(onOpen [handshake]
((:on-open options) handshake))
(onClose [code reason remote]
((:on-close options) code reason remote))
(onMessage [message]
((:on-message options) message))
(onError [^java.lang.Exception e]
((:on-error options) e)))))
| (ns uk.org.potentialdifference.darknet.websocket
(:import [org.java_websocket.client WebSocketClient]
[org.java_websocket.drafts Draft_10]
[java.net URI]))
(defn connect! [url options]
(.connectBlocking
(proxy [WebSocketClient]
[(new URI url) (new Draft_10)]
(onOpen [handshake]
((:on-open options) handshake))
(onClose [code reason remote]
((:on-close options) code reason remote))
(onMessage [message]
((:on-message options) message))
(onError [^java.lang.Exception e]
((:on-error options) e)))))
|
Use global for simple-chapter version | (ns ^{:doc "Simple Chapters extension: http://podlove.org/simple-chapters.
Specification: http://podlove.org/simple-chapters"}
qcast.feed.ext.simple-chapters
(:require [hiccup.util :refer [escape-html]]))
;;; Interface
;; Channel
;; Channel or Item
;; Item
(defn chapter
([start title]
[:psc:chapter {:start start, :title (escape-html title)}])
([start title link-url]
(assoc-in (chapter start title) [1 :href] link-url))
([start title link-url image-url]
(assoc-in (chapter start title link-url) [1 :image] image-url)))
(defn chapters [& chapters]
[:psc:chapters {:version "1.2"} (map #(apply chapter %) chapters)])
| (ns ^{:doc "Simple Chapters extension: http://podlove.org/simple-chapters.
Specification: http://podlove.org/simple-chapters"}
qcast.feed.ext.simple-chapters
(:require [hiccup.util :refer [escape-html]]))
;;; Globals
(def ^:private version "1.2")
;;; Interface
;; Channel
;; Channel or Item
;; Item
(defn chapter
([start title]
[:psc:chapter {:start start, :title (escape-html title)}])
([start title link-url]
(assoc-in (chapter start title) [1 :href] link-url))
([start title link-url image-url]
(assoc-in (chapter start title link-url) [1 :image] image-url)))
(defn chapters [& chapters]
[:psc:chapters {:version version} (map #(apply chapter %) chapters)])
|
Add junit as a test dependency | (set-env!
:source-paths #{"src"})
(def +version+ "0.1.0")
(task-options!
pom {:project 'http-server
:version +version+
:description "A Java HTTP server."
:url "https://github.com/RadicalZephyr/http-server"
:scm {:url "https://github.com/RadicalZephyr/http-server.git"}
:licens {"MIT" "http://opensource.org/licenses/MIT"}})
(deftask build
"Build my http server."
[]
(comp (javac)
(pom)
(jar)))
| (set-env!
:source-paths #{"src"}
:dependencies '[[junit "4.12" :scope "test"]])
(def +version+ "0.1.0")
(task-options!
pom {:project 'http-server
:version +version+
:description "A Java HTTP server."
:url "https://github.com/RadicalZephyr/http-server"
:scm {:url "https://github.com/RadicalZephyr/http-server.git"}
:licens {"MIT" "http://opensource.org/licenses/MIT"}})
(deftask build
"Build my http server."
[]
(comp (javac)
(pom)
(jar)))
|
Attach interns new vars instead of using a single var | (ns lazytest.attach
(:use [lazytest.groups :only (group?)]))
(defn groups-var
"Creates or returns the Var storing Groups in namespace n."
[n]
(or (ns-resolve n '*lazytest-groups*)
(intern n (with-meta '*lazytest-groups* {:private true}) #{})))
(defn groups
"Returns the Groups for namespace n"
[n]
(var-get (groups-var n)))
(defn all-groups
"Returns a sequence of all Groups in all namespaces."
[]
(mapcat (comp seq groups) (all-ns)))
(defn add-group
"Adds Group g to namespace n."
[n g]
{:pre [(group? g)
(the-ns n)]}
{:post [(some #{g} (seq (groups n)))]}
(alter-var-root (groups-var (the-ns n)) conj g))
| (ns lazytest.attach)
(defn groups
"Returns the Groups for namespace n"
[n]
(map var-get (filter #(::group (meta %)) (vals (ns-interns n)))))
(defn all-groups
"Returns a sequence of all Groups in all namespaces."
[]
(mapcat groups (all-ns)))
(defn add-group
"Adds Group g to namespace n."
[n g]
(intern n (with-meta (gensym "lazytest-group-") {::group true}) g))
(defn clear-groups
"Removes all test groups from namespace n."
[n]
(doseq [[sym v] (ns-interns n)]
(when (::group (meta v))
(ns-unmap n sym))))
|
Fix a bug where FileUtils throws when the root dir isn't present | (ns circle.util.fs
"utilities for working with files and directories"
(:require fs)
(:require [clojure.java.io :as io])
(:import org.apache.commons.io.FileUtils)
(:require [circle.sh :as sh]))
(defn all-files
"Returns a list of all files in the repos"
[dir]
(FileUtils/listFiles (io/as-file dir) nil true))
(defn files-matching
"Returns a list of files that match re."
[dir re]
(->> dir
(all-files)
(filter #(re-find re %))))
(defn re-file?
"True if the contents of the file match the regex"
[file re]
(when (fs/exists? file)
(boolean (seq (re-find re (slurp file))))))
(defn line-count
"returns the number of lines in the file"
[file]
(->> file (slurp) (re-seq #"\n") (count))) | (ns circle.util.fs
"utilities for working with files and directories"
(:require fs)
(:require [clojure.java.io :as io])
(:import org.apache.commons.io.FileUtils)
(:require [circle.sh :as sh]))
(defn all-files
"Returns a list of all files in the repos"
[dir]
(when (fs/exists? dir)
(FileUtils/listFiles (io/as-file dir) nil true)))
(defn files-matching
"Returns a list of files that match re."
[dir re]
(->> dir
(all-files)
(filter #(re-find re %))))
(defn re-file?
"True if the contents of the file match the regex"
[file re]
(when (fs/exists? file)
(boolean (seq (re-find re (slurp file))))))
(defn line-count
"returns the number of lines in the file"
[file]
(->> file (slurp) (re-seq #"\n") (count))) |
Add warnings and errors keys to context | (ns vip.data-processor.pipeline
(:require [clojure.tools.logging :as log]
[clojure.stacktrace :as stacktrace]))
(defn try-validation [validation ctx]
(try
(validation ctx)
(catch Throwable e
(log/error e)
(assoc ctx :stop "Exception caught"
:exception e))))
(defn run-pipeline [c]
(loop [ctx c]
(if-let [next-step (-> ctx :pipeline first)]
(let [next-ctx (try-validation next-step ctx)]
(if (:stop next-ctx)
next-ctx
(recur (assoc next-ctx :pipeline (rest (:pipeline ctx))))))
ctx)))
(defn process [pipeline initial-input]
(let [ctx {:input initial-input
:pipeline pipeline}
result (run-pipeline ctx)]
(log/info result)
(when-let [ex (:exception result)]
(log/error (with-out-str (stacktrace/print-stack-trace ex)))
(throw (ex-info "Exception during processing" {:exception ex
:initial-ctx ctx
:final-ctx result})))
result))
| (ns vip.data-processor.pipeline
(:require [clojure.tools.logging :as log]
[clojure.stacktrace :as stacktrace]))
(defn try-validation [validation ctx]
(try
(validation ctx)
(catch Throwable e
(log/error e)
(assoc ctx :stop "Exception caught"
:exception e))))
(defn run-pipeline [c]
(loop [ctx c]
(if-let [next-step (-> ctx :pipeline first)]
(let [next-ctx (try-validation next-step ctx)]
(if (:stop next-ctx)
next-ctx
(recur (assoc next-ctx :pipeline (rest (:pipeline ctx))))))
ctx)))
(defn process [pipeline initial-input]
(let [ctx {:input initial-input
:warnings []
:errors []
:pipeline pipeline}
result (run-pipeline ctx)]
(log/info result)
(when-let [ex (:exception result)]
(log/error (with-out-str (stacktrace/print-stack-trace ex)))
(throw (ex-info "Exception during processing" {:exception ex
:initial-ctx ctx
:final-ctx result})))
result))
|
Modify delete-recursively to fail gracefully for nil root. | (ns incise.utils
(:import [java.io File]))
(defn- gitignore-file? [^File file]
(= (.getName file) ".gitignore"))
(defn delete-recursively
"Delete a directory tree."
[^File root]
(when (.isDirectory root)
(doseq [file (remove gitignore-file? (.listFiles root))]
(delete-recursively file)))
(.delete root))
| (ns incise.utils
(:import [java.io File]))
(defn- gitignore-file? [^File file]
(= (.getName file) ".gitignore"))
(defn delete-recursively
"Delete a directory tree."
[^File root]
(when root
(when (.isDirectory root)
(doseq [file (remove gitignore-file? (.listFiles root))]
(delete-recursively file)))
(.delete root)))
|
Sort by score not status | (ns made-merits.service.leaderboard-users
(:require [made-merits.service.winner-calculator :as winner-calculator]
[made-merits.service.score-calculator :as score-calculator]))
(defn with-winner-first
[scored-users-with-merits]
(reverse (sort-by #(= "winner" (:status %)) scored-users-with-merits)))
(defn presentable
[db-users]
(with-winner-first
(winner-calculator/with-winner
(score-calculator/with-score db-users))))
| (ns made-merits.service.leaderboard-users
(:require [made-merits.service.winner-calculator :as winner-calculator]
[made-merits.service.score-calculator :as score-calculator]))
(defn with-winner-first
[scored-users-with-merits]
(reverse (sort-by :score scored-users-with-merits)))
(defn presentable
[db-users]
(with-winner-first
(winner-calculator/with-winner
(score-calculator/with-score db-users))))
|
Prepare for next release cycle. | (defproject onyx-app/lein-template "0.9.7.0-alpha21"
: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)
|
Remove AOT options and bump dependencies versions | (defproject lein-droid/lein-droid "0.2.0-SNAPSHOT"
:description "Plugin for easy Clojure/Android development and deployment"
:url "https://github.com/alexander-yakushev/lein-droid"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:dependencies [[org.clojure/clojure "1.5.0"]
[leiningen "2.1.3"]
[leiningen-core "2.1.3"]
[robert/hooke "1.1.2"]
[org.clojure/data.zip "0.1.0"]
[com.cemerick/pomegranate "0.2.0"]]
:min-lein-version "2.0.0"
:resource-paths ["res"]
:eval-in-leiningen false
:java-source-paths ["src"]
:javac-options ["-target" "1.6" "-source" "1.6"]
:warn-on-reflection true
:aot [#"leiningen\.droid"])
| (defproject lein-droid/lein-droid "0.2.0-SNAPSHOT"
:description "Plugin for easy Clojure/Android development and deployment"
:url "https://github.com/alexander-yakushev/lein-droid"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:dependencies [[robert/hooke "1.3.0"]
[org.clojure/data.zip "0.1.1"]]
:min-lein-version "2.0.0"
:resource-paths ["res"]
:eval-in-leiningen true)
|
Move example to latest versions | (defproject simple-re-frame "0.5.0"
:dependencies [[org.clojure/clojure "1.7.0"]
[org.clojure/clojurescript "1.7.145"]
[reagent "0.5.1"]
[re-frame "0.5.0-alpha3"]
[figwheel "0.2.6"]]
:plugins [[lein-cljsbuild "1.1.0"]
[lein-figwheel "0.3.8"]]
:hooks [leiningen.cljsbuild]
:profiles {:dev {:cljsbuild
{:builds {:client {:source-paths ["devsrc"]
:compiler {:main simpleexample.dev
:asset-path "js"
:optimizations :none
:source-map true
:source-map-timestamp true}}}}}
:prod {:cljsbuild
{:builds {:client {:compiler {:optimizations :advanced
:elide-asserts true
:pretty-print false}}}}}}
:figwheel {:repl false}
:clean-targets ^{:protect false} ["resources/public/js"]
:cljsbuild {:builds {:client {:source-paths ["src"]
:compiler {:output-dir "resources/public/js"
:output-to "resources/public/js/client.js"}}}})
| (defproject simple-re-frame "0.5.0"
:dependencies [[org.clojure/clojure "1.7.0"]
[org.clojure/clojurescript "1.7.145"]
[reagent "0.5.1"]
[re-frame "0.5.0"]]
:plugins [[lein-cljsbuild "1.1.0"]
[lein-figwheel "0.4.1"]]
:hooks [leiningen.cljsbuild]
:profiles {:dev {:cljsbuild
{:builds {:client {:source-paths ["devsrc"]
:compiler {:main simpleexample.dev
:asset-path "js"
:optimizations :none
:source-map true
:source-map-timestamp true}}}}}
:prod {:cljsbuild
{:builds {:client {:compiler {:optimizations :advanced
:elide-asserts true
:pretty-print false}}}}}}
:figwheel {:repl false}
:clean-targets ^{:protect false} ["resources/public/js"]
:cljsbuild {:builds {:client {:source-paths ["src"]
:compiler {:output-dir "resources/public/js"
:output-to "resources/public/js/client.js"}}}})
|
Fix transit dep on common-codec | ;; Copyright © 2014-2017, JUXT LTD.
(def VERSION "1.3.0-alpha3")
(defproject yada/transit VERSION
:description "Support for transit media-types"
:license {:name "The MIT License"
:url "https://opensource.org/licenses/MIT"}
:pedantic? :abort
:dependencies [[yada/core ~VERSION]
[com.cognitect/transit-clj "0.8.297"]])
| ;; Copyright © 2014-2017, JUXT LTD.
(def VERSION "1.3.0-alpha3")
(defproject yada/transit VERSION
:description "Support for transit media-types"
:license {:name "The MIT License"
:url "https://opensource.org/licenses/MIT"}
:pedantic? :abort
:dependencies [[yada/core ~VERSION]
[com.cognitect/transit-clj "0.8.313"]
[com.cognitect/transit-java "0.8.337" :exclusions [commons-codec]]])
|
Add ongoing requests counter to test server | (ns clj-tutorials.main
(:require [compojure.core :refer :all]
[compojure.handler :as handler]
[org.httpkit.server :refer [run-server]]))
(defroutes app-routes
(GET "/ping" [] "pong"))
(defn run []
(run-server (handler/api app-routes) {:port 8080 :join? false}))
| (ns clj-tutorials.main
(:require [compojure.core :refer :all]
[compojure.handler :as handler]
[org.httpkit.server :refer [run-server]]))
(def ongoing-requests (atom 0))
(defn- pong []
(let [ongoing-reqs (swap! ongoing-requests inc)
start (System/currentTimeMillis)]
(when (= 0 (mod ongoing-reqs 10))
(prn "Ongoing requests " ongoing-reqs))
(Thread/sleep 50)
(swap! ongoing-requests #(- % 1))
"pong"))
(defroutes app-routes
(GET "/ping" [] (pong)))
(defn run []
(run-server (handler/api app-routes) {:port 8080 :join? false}))
|
Change watch -> wait in audio tempalte | (set-env!
:source-paths #{"src"}
:resource-paths #{"resources"}
:dependencies '[[org.clojure/clojure "1.8.0"]
[alda "1.0.0-rc34"]])
(task-options!
pom {:project '{{app-name}}
:version "0.1.0-SNAPSHOT"
:description "FIXME: write description"}
aot {:namespace #{'{{namespace}}}}
jar {:main '{{namespace}}})
(require '{{namespace}})
(deftask run []
(comp
(watch)
(with-pre-wrap fileset
({{namespace}}/-main)
fileset)))
(deftask build []
(comp (aot) (pom) (uber) (jar) (target)))
| (set-env!
:source-paths #{"src"}
:resource-paths #{"resources"}
:dependencies '[[org.clojure/clojure "1.8.0"]
[alda "1.0.0-rc34"]])
(task-options!
pom {:project '{{app-name}}
:version "0.1.0-SNAPSHOT"
:description "FIXME: write description"}
aot {:namespace #{'{{namespace}}}}
jar {:main '{{namespace}}})
(require '{{namespace}})
(deftask run []
(comp
(wait)
(with-pre-wrap fileset
({{namespace}}/-main)
fileset)))
(deftask build []
(comp (aot) (pom) (uber) (jar) (target)))
|
Disable eftest multi threading by default | (ns scratch
(:require [clojure.test :as test]
[clojure.repl :as repl]
[eftest.runner :as eftest]
[clojure.tools.namespace.find :as ns.find]
[clojure.tools.namespace.repl :as ns.repl]
[clojure.java.io :as io])
(:import (java.io File)))
(defn init! []
(ns.repl/disable-reload! *ns*))
(def refresh ns.repl/refresh)
(def refresh-all ns.repl/refresh-all)
(defn list-ns
"Return list of symbols of namespaces found in src dir"
[]
(ns.find/find-namespaces-in-dir (File. "./src/")))
(defn t
"Reload and run tests. Without arguments run all tests.
If argument is passed (String) is interpreted as a regex to
find a namespace"
([]
(refresh)
(eftest/run-tests (eftest/find-tests "test")))
([pattern]
(let [regex (re-pattern pattern)
nss (filter (fn [v] (re-find regex (str v)))
(eftest/find-tests "test"))]
(refresh)
(eftest/run-tests nss))))
(println "yo")
(init!)
| (ns scratch
(:require [clojure.test :as test]
[clojure.repl :as repl]
[eftest.runner :as eftest]
[clojure.tools.namespace.find :as ns.find]
[clojure.tools.namespace.repl :as ns.repl]
[clojure.java.io :as io])
(:import (java.io File)))
(def multithread (atom false))
(defn init! []
(ns.repl/disable-reload! *ns*))
(def refresh ns.repl/refresh)
(def refresh-all ns.repl/refresh-all)
(defn list-ns
"Return list of symbols of namespaces found in src dir"
[]
(ns.find/find-namespaces-in-dir (File. "./src/")))
(defn t
"Reload and run tests. Without arguments run all tests.
If argument is passed (String) is interpreted as a regex to
find a namespace"
([]
(refresh)
(eftest/run-tests (eftest/find-tests "test")
{:multithread? @multithread}))
([pattern]
(let [regex (re-pattern pattern)
nss (filter (fn [v] (re-find regex (str v)))
(eftest/find-tests "test"))]
(refresh)
(eftest/run-tests nss
{:multithread? @multithread}))))
(println "yo")
(init!)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.