eclipse,clojure,counterclockwise
The problem was I was using Java 1.6 by default. Install Java 7 or higher or make eclipse use that vm with the -vm option in eclipse.ini. See here: http://wiki.eclipse.org/FAQ_How_do_I_run_Eclipse%3F#eclipse.ini...
asynchronous,clojure,core.async
You're only ever getting the first message out of the echo-buffer, and since the buffer size is 2, trying to add a fourth message to the buffer will block until another value is removed from the buffer (which will never happen). In other words, you seem to expect that (go...
The only guarantee is that the order will be preserved within messages from a single go block. For example, when reading from the channel you will see all messages from a certain go block in the same order they were put to the channel by that go block. However, those...
You have unbalanced parantheses in clojurenet.core (ns clojurenet.core) ;; <- remove ) to fix (:require clojurenet.hello) (:gen-class)) I recommend using a balancing editing mode like ParEdit. You may want to try out this implementation if you are using Sublime....
This content is maintained not by Leiningen itself, but the lein-search plugin. I'd suggest uninstalling it (the plugin, that is) unless you consider its benefits worth the cost in time and storage. To do so, remove references to lein-search/lein-search or org.clojars.wuschel/lein-search from your ~/.lein/profiles.clj -- or, if this content was...
A brief history of the ^ macro character In Clojure v1.0, the ^ character is the "meta reader macro". In other words, ^x was shorthand for (meta x). #^ was used to associate metadata with an object. (See the Macro Characters documentation from November 2009.) At some point, someone probably...
Apparently pre and post conditions are designed for usecases where reporting the clauses provides enough information to the developer, i.e. it is self-explanatory. If you wish to provide more explanation, it is idiomatic to use assert. But you can abuse the fact that the whole condition is always reported e.g....
Heroku is limiting your process memory, which is different from the memory allocated by the JVM. See for example: Why is my JVM process larger than max heap size?...
Kevin You were close, this should do the work (basically, you should unquote the local var in the quoted statement) (let [foo 1] (eval `(print ~foo))) Also, while eval is certainly a valid language function, what is the overall goal? There may be better ways altogether. Frank...
heroku,clojure,procfile,luminus
My best guess is that you need to build the project with the command lein uberjar. This sequence works: $ lein new luminus foobar Retrieving ... Generating a Luminus project. $ cd foobar $ lein uberjar Retrieving ... Compiling foobar.session Compiling foobar.layout Compiling foobar.handler Compiling foobar.routes.home Compiling foobar.core Compiling foobar.middleware...
The instantiated channel is from ManyToManyChannel type, you can access the internal buffer for the channel using the buf property. (.buf c) => #<FixedBuffer [email protected]> That buffer implements clojure.lang.Counted so it's countable. (count (.buf c)) => 0 ...
the + is in the wrong place in: ((math/expt x 2)+ (math/expt y 2))) should be: (+ (math/expt x 2) (math/expt y 2))) and the same for y1 as well. Since you have this correct elsewhere it looks like a simple typo. While it's very normal to see ))))))) in...
clojure,namespaces,read-eval-print-loop
in-ns does not load code. It switches to an ns, creating it if needed. It also does not do the default ns setup (eg. referring clojure.core). The proper way to load a namespace from code in the repl is with require (require 'some.ns), which can then be followed by (in-ns...
SwingUtilities/invokeLater takes a Runnable. Clojure functions implement Runnable. However you're passing the results of (println "Hi") which is nil to invokeLater, hence the NPE. You need to pass it as a function to be called, instead of calling it yourself. This example passes an anonymous function to invokeLater. (import 'javax.swing.SwingUtilities)...
Doing (loop [urls [start-url] index n] ... should make urls into a vector containing the single string start-url, without the destructuring. The reason '(start-url) doesn't do the same is that the quote applies to the whole structure, including start-url. (list start-url) should work, but a vector is typically preferable in...
multithreading,clojure,core.async
I don't usually rant like this so I hope you will forgive me this one transgression: In a more prefect world every programmer would repeat to themselves "there is no such thing as an unbounded queue" five times before sleeping and first thing upon waking. This mode of thinking requires...
You need to explicitly opt-in to implicit type checking. Change your ns form like so: (ns ^:core.typed typedclj.rps-async ...) ...
Here's kind of the default template I use for new projects. It allows you to do dependency injection into ring apps and run the app from the command line as an uberjar. You can read more here: http://www.sparxeng.com/blog/software/improved-clojure-workflow ; handler.clj (defn wrap-inject-deps "Ring middleware that injects the dependencies into each...
You're shadowing the str symbol from clojure.core with your str parameter. Inside moving-shift's scope, str refers to "I should have known..." and not clojure.core/str, hence when you call your apply function, you get a ClassCastException, stating that a string is not a function. Use another name for your string parameter.
Not sure how you can run lein run without a -main method, so here is some sample code: project.clj (defproject testi "0.1.0-SNAPSHOT" :main fstego.core :dependencies [[org.clojure/clojure "1.6.0"]]) src/fstego/core.clj (ns fstego.core (:import [javax.imageio ImageIO]) (:import [java.io File])) (defn -main[& args] (if-let [ path (first args) ] (let[ img (ImageIO/read (File. path))]...
This error occurs when there's a licensing issue, the transactor refuses to accept a new connection. Do you have multiple peers connected?
There is no built-in function for this. You can refer to clojure.core API reference and the cheatsheet to look up what's available. I would say Clojure's syntax is light enough that it feels sufficient to use a combination of map and an accessor utility like get-in. This also demonstrates a...
On Linux you can fork a process and then collect it later, as illustrated on the help page ?parallel::mccollect(); this is more of a hack than a robust feature like future. > p <- mcparallel({ Sys.sleep(5); "done" }) > sqrt(1:5) [1] 1.000000 1.414214 1.732051 2.000000 2.236068 > mccollect(p) $`15666` [1]...
EDIT: As an answer to the updated question, the wrap-edn-params function consumes the body of the request by fully reading the :body InputStream. Compojure routes passes the request to each parameter handler until a non nil value is returned. In this case, whichever handler is passed to routes as the...
1) Yes, Leiningen offers profiles for just these purposes 2) No, referals from one namespace are not "inherited" between namespaces. You can't express "I want to refer to everything in this namespace, that some other namespace refers"...
java,scala,clojure,spark-graphx
Finally got it right (I think). Here is the code that appears to be working: (ns spark-tests.core (:require [flambo.conf :as conf] [flambo.api :as f] [flambo.tuple :as ft]) (:import (org.apache.spark.graphx Edge Graph) (org.apache.spark.api.java JavaRDD StorageLevels) (scala.reflect ClassTag$))) (defonce c (-> (conf/spark-conf) (conf/master "local") (conf/app-name "flame_princess"))) (defonce sc (f/spark-context c)) (def users...
This is an attempt to use your site as a proxy tunnel. If you use a reverse proxy like nginx in front of your site, you can prevent requests like this from hitting your app.
Ignoring the specifics on the syntax of requiring records, there are two main ways to write ns declarations (or any platform specific code) for multiple Clojure variants while sharing the majority of your code. CLJX is a Clojure preprocessor that runs before the Clojure compiler. You write platform specific code...
function,clojure,clojurescript
Have a look at the function some, that takes a predicate and a collection as arguments, and returns true iff the predicate returns true for some item in the collection. (some #(>= % 3) [1 2 3 4]) ; => true (some #(>= % 3) [0 1 0 1]) ;...
The result set is a sequence of maps, so if you wanted to obtain one field (e.g. one called name) then: (sql/with-connection db (sql/with-query-results rs ["select * from user where UserID=?" 10000] (doseq [rec rs] (let [name (:name rec)] (println "User name:" name) (println "Full record (including name):" rec))))) But...
As with most things functional, the answer is recursion. It's in fact tremendously easier to do functionally than it would be to do by mutating a bunch of lists of lists in java. You just define a function that converts a single ArrayList into a clojure list, and then have...
Yes, I think macros is the way to do this in clojure. Taking your code and doing some liberal assumptions about bad-request, error and the other stuff, I made up the following example: (require '[clojure.test :refer [deftest testing is]]) ; dummy implementations, here will be your real bad-request & error...
clojure,dependencies,jackson,leiningen
I put the exclusion on itsy rather than amazonica and it worked. Also fixed the NS form in core.clj. project.clj: (defproject blabla "0.1.0-SNAPSHOT" :description "FIXME: write description" :url "http://example.com/FIXME" :license {:name "Eclipse Public License" :url "http://www.eclipse.org/legal/epl-v10.html"} :dependencies [[org.clojure/clojure "1.6.0"] [itsy "0.1.1" :exclusions [com.fasterxml.jackson.core/jackson-core]] [amazonica "0.3.22" :exclusions [commons-logging org.apache.httpcomponents/httpclient]]]) core.clj: (ns...
There are two paths to consider to improve your REPL and debugging experience: Using a REPL and debugger integrated with your editor or IDE of choice Using an embedded nREPL server The first is an essential part of setting up your local Clojure development environment and should be done regardless....
Long live lib-noir and its wrap-force-ssl fn. I just needed to change it a bit to fit my needs (I have a SSL cert. for one subdomain even if my clojure app handles more then one domain) Here's my fn: (defn wrap-force-ssl "Almost like in lib-noir. If the request's scheme...
clojure,scheme,lisp,common-lisp
The empty product is 1. The reason is that 1 is a neutral element for *. If you have the product of 2 and 3 and then multiply by the product of nothing, you will get 2*3*1 = 6. We can write (product (product 2 3) (product)) = (product 6...
You can try this: (println (with-open [rdr (clojure.java.io/reader "file")] (let [ls (line-seq rdr)] (doall (take 5 ls))))) This will print first 5 lines of the specified file. If you need skip some lines that does not satisfy the condition, you can add filter. The following code will print first five...
clojure,functional-programming,lisp
You are misunderstanding the format of a function definition. In your function, the single argument 'colors' is untyped and can be anything. The square brackets are used to denote the beginning and end of the arguments list (i.e. the symbols for the arguments are wrapped in a vector to distinguish...
Here's the JavaScript that generates an object attached to the window. It has too properties. foo which is a function and .bar which is a string. (let [my-object (set! (.-myobj js/window (clj->js {}))) some-func (fn [] (+ 1 1))] (set! (.-foo my-object) some-func) (set! (.-bar my-object) "something")) ...
You are missing an if, and you need to end the loop on idxs, not pts (or you will miss the final index pair): (if (empty? idxs) deck (recur (first pts) (exchange deck idxs) (rest pts))) should work better....
You have def'd access_key so it is being evaluated when you load the application. You probably want to make it a function instead.
clojure,functional-programming
Assuming that by variable you mean a refer to a mutable storage location, I guess the main difference(depending against which language you compare) is that if you dynamically rebind the var in Clojure is on a per-thread basis. But the long answer is that you don't usually use a var...
Yes, map? is the inbuilt function (map? {:a 1}) => true (map? [1]) => false ...
map-indexed is a decent choice. call a function you pass with the value of one of the items form your input and the index where it was found (index first). that function can choose to produce a new value or return the existing one. user> (map-indexed (fn [i v] (if-not...
clojure,tacit-programming,reader-macro
The proper place to propose language changes is the Clojure project jira project. Open a new issue marked as "enhancement". It's also good to check in on the #clojure freenode irc as well as searching the back issues to see if this has been proposed before
The built in function clojure.set/rename-keys will do this nicely, though like all things in clojure there are several approaches. So lets walk through the process. What you have is very close to working. If I just lookup each by it's original string key, we can see it work: user> (def...
(defn current-stack-trace [] (.getStackTrace (Thread/currentThread))) (defn is-repl-stack-element [stack-element] (and (= "clojure.main$repl" (.getClassName stack-element)) (= "doInvoke" (.getMethodName stack-element)))) (defn is-in-repl [] (some is-repl-stack-element (current-stack-trace))) (defn my-log [msg] (if (is-in-repl) (prn (str "RUNNING IN REPL : " msg)) (prn msg))) ...
clojure,sqlite3,korma,sqlkorma
Like mentioned in issue #251 the reason is the entity-fields expression. It defines the default fields for queries. The fields function adds more fields to the defaults. Works as designed. Therefore I removed entity-fields within defentity. ;; models.clj (defentity issue (has-many comment)) ;; repl test=> (-> (select* issue) #_=> (fields...
Would some-> work for you? user=> (doc some->) ------------------------- clojure.core/some-> ([expr & forms]) Macro When expr is not nil, threads it into the first form (via ->), and when that result is not nil, through the next etc nil user=> (some-> nil keyword namespace) nil user=> (some-> "user/a" keyword namespace)...
a sequence of a map produces MapEntry values as you've noted, which look like and can be compared with vectors user=> (= (first {:a 1 :b 2}) [:a 1]) true but aren't the same class user=> (= (class (first {:a 1 :b 2})) (class [:a 1])) false So although the...
The issue is that a topology definition needs a list of two maps. One map is for spout definitions, the second map is for bolt definitions. The solution to creating a spout-only topography is to add a second empty map to the .clj file: (ns facetrack (:use [streamparse.specs]) (:gen-class)) (defn...
They need to be maps with :name and :address keys, like: {:name "A Person", :address {:zip-code 19103}} for will take each element from people and assign each one to {:keys [name address]}. This is called destructuring, and it's just a convenience. It's the same as saying: (for [person people :let...
when, is a clojure macro defined as: (when test & body) So, in your first example, the body of when would be: (do r (recur (dec i) (conj r i))) The when test itself is evaluated to false so the body of the when macro is not executed. The return...
You have a map, and I'm guessing you don't want the [ ... ] round the values, so that your collection should be: (def coll { :key1 "string1" :key2 "string2"}) In that case, your first attempt wasn't far off: (clojure.string/join (vals coll)) ;"string1string2" If you do need the vectors, because...
The idiomatic way to do this is to use leiningen profiles, using the :dev profile. You can then ensure inside the dev profile that your ClojureScript build is happening without optimization, cf. the leiningen cljsbuild compilation profiles. If you want to be able to identify the devserver running, you can...
here's a basic outline of using clojure.tools.cli (def command-line-spec [["-m" "--mode 0|1" "description of option that takes 1 or 0" :parse-fn #(case (s/lower-case %) ("1" "true" "create") :one ("0" "false" "destroy") :zero :invalid) :default :one :validate [#{:one :zero} "Unsupported mode"]] ["-c" "--config type1|type2|..." :desc "config specifies what to do" :default...
java,maven,clojure,interop,leiningen
You probably want to change the last period in your :import statement into a space: (ns mynamespace (:import [com.ollio.nlp Transformer])) (EDIT: You can't use wildcards here. Every class that in com.ollio.nlp must be listed explicitly, separated by spaces.) That will allow you to use Transformer unqualified: (.transform (Transformer. <add constructor...
You are redundantly calling reverse on every iteration of the reduce: user=> (let [c [1 2 3] noisey-reverse #(doto (reverse %) println)] (reduce (fn [acc e] (conj acc (noisey-reverse c) e)) [] [:a :b :c])) (3 2 1) (3 2 1) (3 2 1) [(3 2 1) :a (3 2...
Clojure's equivalent of || is the macro or . You can view its implementation here. If you want to use the symbol ||, you can just alias the or macro: (def #^{:macro true} || #'or) You can then use either: (or (get a 0) (b)) or (|| (get a 0)...
The problem with your program is the form: (def fibVal (assoc fibVal x (+ (fibonacci (- x 1)) (fibonacci (- x 2))))) The fibVal you are using in the first line is evaluated to its current value before the recursive calls write new versions of it. Whatever they do to...
clojure,zookeeper,watch,stm,cap-theorem
This seems to be a limitation in the way ZooKeeper implements watches, not a limitation of the CAP theorem. There is an open feature request to add continuous watch to ZooKeeper: https://issues.apache.org/jira/browse/ZOOKEEPER-1416. etcd has a watch function that uses long polling. The limitation here which you need to account for...
Example 1 is wrong and Example 2 is correct. the first one only works because it's recuring only twice and doesn't blow the stack. The call to trampoline does nothing because the function never returns a function, so the trampoline function simply returns the value it returned. it works in...
If you comment out (deref ~q), the code passed with q is never evaluated, so the nested futures don't come into existence. Macroexpansion: (macroexpand '(-> (future (wait 200 (println "'Ello, gov'na!"))) (enqueue saying (wait 400 "Pip pip!") (println @saying)) (enqueue saying (wait 100 "Cheerio!") (println @saying)))) ;;-> .... (clojure.pprint/pp) (let*...
Start off with something simple: (defmacro looper [ifc & fn-names] `(do [email protected](for [curr-fn fn-names] [curr-fn] ))) (println (macroexpand-1 '(looper IFC fun1 fun2 fun3))) ;=> (do [fun1] [fun2] [fun3]) the backquote (backtick?) starts an inline code template. The [email protected] turns off the template part and starts live code execution (try substituting...
Yes this is true, and changing it would break everything. Channels are identical? if they are the same chan object, and therefore are equal in all cases. All other comparisons of chans are explicitly not equal, and this is good for you. You want removal to remove the exact chan...
I'm not sure if it's the simplest way to write it, but I think this is more clear about your intentions: (->> maps (filter #(= (:id %) id)) first) ...
clojure,ring,compojure,http-kit
You can use compojure's routes function. You can also pass several handlers to defroutes, an example is provided below: (defroutes get-routes (GET "/events" [] "Event API") (GET "/" [] "Welcome")) (defroutes post-routes (POST "/events" [] "Post Event API")) (def all-routes (routes get-routes post-routes)) (defn -main [] (run-server all-routes {:port 5000}))...
There actually is, and it's named group-by. (vals (group-by first '([AA moo foo boo] [AA soo doo foo] [BB woo roo too] [BB koo ooo yoo]))) ;; => ([[AA moo foo boo] [AA soo doo foo]] ;; [[BB woo roo too] [BB koo ooo yoo]]) group-by returns a map of...
Since you have exactly two branches here, it'll be best to dispatch parallel jobs to separate threads using future function. future will return you a future object (a special promise which will be automatically resolved when the job will be completed). Here is how it will look: (defn some-entry-point [obja...
Yes, you declare your functions in the protocol definition Shape, and then you define your implementations in your various record implementations Square, Circle, etc. (defprotocol Shape (area [this]) (perimeter [this])) (defrecord Square [side] Shape (area [this] (* (:side this) (:side this))) (perimeter [this] (* 4 (:side this)))) (defrecord Rect [w...
If you can rearrange the definition of f so that y is the first parameter, you can do it this way: (defn f [y x] ...) (map (partial f y) xs) partial returns a function in which y is "baked in" as the first argument to f. For functions that...
conj does not modify its argument. In fact, without resorting to evil reflection tricks, nothing will modify a vector, it's an immutable data structure. This is one of the fundamental principles of Clojure. In functional programming, instead of modifying data, we replace it with another immutable value. So you need...
#^floats is a legacy syntax, with newer Clojure versions ^floats is preferred.
The runScriptOnNode has several forms. As defined in the ComputeService interface, the script can be provided as a Statement object or as a simple String. If you want to use the Statement then you can build it by using the helper methods in the Statements class (something like: Statements.exec("ls")), but...
caching,clojure,wildfly,immutant
This was being caused by an error with our deployment scripts. A hack had been done to deploy the same .war twice for an application requirement. The hack stopped the application from shutting down cleanly when a redeployment happened, and was causing the issue with the cache.
The idiomatic way to do this is to use some->. See the documentation of this macro for more details. Don't let that stop you from making your own, of course!...
I ended up finding a solution: (def ^{:a :b} my-var) (defmacro my-macro [s] (prn (meta (resolve s)))) (my-macro my-var) ;; Prints {:a :b, :name my-var, ...} So the key part here is to use resolve function to get the var associated to the symbol....
The ring middleware wrap-reload will do this for you. There is also a very nice leiningen template called Chestnut which will set up a project for you with Figwheel and an auto reloading Ring backend. This question shows an example of wrap-reload usage Compojure development without web server restarts...
clojure,metadata,read-eval-print-loop
^ is a reader macro which attaches metadata to the form that follows it. However, 'x is not a form to which metadata can be applied; it expands to (quote x) via the ' reader macro. When you type ^{:hi 10} 'x, the metadata gets attached to the un-evaluated (quote...
clojure,basic-authentication,compojure
You can provide a totally different credential-fn, or stick to the demo where credential-fn is implemented using cemerick.friend.credentials/bcrypt-credential-fn. Read the doc of bcrypt-credential-fn at https://github.com/cemerick/friend/blob/master/src/cemerick/friend/credentials.clj, it is quite long. It expects a load-credentials-fn that loads a user given a username string, then checks if the password matches. In the demo,...
There is no problem that AngularJS sends an OPTIONS request, that is because CORS standards force to do so. Be sure that the server is configured to allow a GET method.
You could do something like this, based on the source of take-while: (defn take-while+ [pred coll] (lazy-seq (when-let [[f & r] (seq coll)] (if (pred f) (cons f (take-while+ pred r)) [f])))) ...
This is correct behaviour - cheshire/parse-string parses the first JSON object it can find. If you want the whole file to be parsed as a single JSON object you should make an array: [{"load": {"meta": 12345}}, {"load": {"meta": 54321}}, ...] Alternatively, if you want to parse each line separately you...
list-perfect is already lazy due to your usage of filter: (filter pred coll) Returns a lazy sequence of the items in coll for which (pred item) returns true. pred must be free of side-effects. Whether code is idiomatic or not might be a matter of opinion (and hence off-topic), but...
zipmap combines a series of keys and values, so you could do: (zipmap (iterate inc 1) data-vector) (with data-vector being your vector of maps) The reverse would basically be sorting by key, then taking all values, which can be written exactly like that: (->> data-map (sort-by key) (map val)) ...
def* would match things like defffffff. In a regex, the star does not mean match anything. It means match the previous pattern any number of times. In your case, the previous pattern is f. Try def[a-z]* to match def followed by any combination of lowercase letters.
You could use cond-> threading macro to merge only defined variables: (defn create ([code error] {:statusCode code :error error}) ([code error & [message data]] (cond-> (create code error) message (assoc :message message) data (assoc :data data )))) or you could define small assoc-if-defined helper and use ordinary -> threading macro:...
No, for the Secure Messaging they use the same algorithm, it's just that they don't pad data explicitly in the MuthualAuth example (because it's already of required length) and do that in the SM example. Try to compute MAC with your code of "887022120C06C2270CA4020C800000008709016375432908C044F6" (which is a SSC + M...
Yes, it's a performance optimization. I'ts not just about not calling concat - it's about the fact that & in the argument list requires a collection to be created as well. The clojure core libraries tend to take performance seriously, under the assumption that the basic building blocks of the...
require is the preferred method for referring to other namespaces. You use :as to give a prefix for the namespace you're requiring. You can use :refer to refer specific symbols into the namespace without needing to be qualified. If you want to import all symbols into the namespace, you can...
The solution I found was to use setInterval before the component function rather than setTimeout inside the component function: (defn reset-component [seconds] [:input {:type "button" :value "Reset" :on-click #(reset! seconds 60)}]) (defn countdown-component [] (let [seconds-left (atom 60)] (js/setInterval #(swap! seconds-left dec) 1000) (fn [] [:div.timer [:div "Time Remaining: "...
oauth,clojure,twitter-oauth,clj-http
I've had difficulty in the past trying to use clj-oauth (mostly because of my own understanding of clojure) but I found twitter-api pretty straightforward to use. It makes use of clj-oauth internally.
defs should only be top level. (def oldX (atom nil)) and (reset! oldX x) is more correct.
Clojure macros apply to the result of the clojure reader's parsing of the source text. Has two effects: You will only get valid clojure datastructures as arguments to a macro. You can only output one valid clojure datastructure from a macro. One of the consequences of this is that certain...