FAQ Database Discussion Community


Registering multiple handlers while running server

clojure,ring,compojure,http-kit
Is there any way to register multiple handlers while running an http-kit server: (defroutes rest-main-app (GET "/" "Welcome")) (defroutes rest-events-app (GET "/events" "Event API")) (defn -main [] (run-server rest-main-app {:port 5000})) How can I pass both routes to the run-server e.g both rest-main-app and rest-events-app ?...

Clojure: Idiomatic/clean way to avoid NPE in a monad-like way

clojure
I'm a little chagrinned that some of the built-in Clojure functions have what seems to me to be an inconsistent behavior. I'm trying to do this: (let [kwns (namespace (keyword v))] ...) in a context where v might be nil. The keyword function works as I'd expect (returns nil), but...

Why is my streamparse topology definition complaining about a wrong number of arguments to thrift$mk-topology?

python,clojure,storm
I'm trying to get a very simple streamparse (i.e. Apache Storm) spout working, but I'm getting the error below when running sparse run -t 120: Caught exception: Wrong number of args (1) passed to: thrift$mk-topology clojure.lang.ArityException: Wrong number of args (1) passed to: thrift$mk-topology at clojure.lang.AFn.throwArity (AFn.java:437) clojure.lang.AFn.invoke (AFn.java:39) clojure.lang.AFn.applyToHelper...

Loop in clojure with or condition

function,clojure,clojurescript
I'm trying to write a function in clojure that calls a condition for each value in a vector; the function should return the OR of the result of the condition applied to each value. Eg I have a vector [1 2 3 4] and a condition (>= x 3) where...

Is there a formal way of proposing/discussing changes to Clojure?

clojure,tacit-programming,reader-macro
Is there a formal way of proposing/discussing changes to Clojure?

Datomic and HornetQException “unable to validate user”

clojure,datomic
I'm trying to connect to Datomic "dev" running on a separate host, but get the following error: "Error communicating with HOST (some-IP-address) on PORT (some-port-number) ...." Then further down the stack trace: Caused by: HornetQException[errorType=SECURITY_EXCEPTION ... Unable to validate user: (some-string) This is with "Seattle" sample schema that comes with...

clojure - take-while to include last item when predicate is false

clojure
I have the following function that uses take-while (defn process [[cash amount wrappers]] (let [bought (int (Math/floor (/ cash amount))) free (->> (iterate (partial unwrapper wrappers) bought) (take-while (partial (fn [w a] (prn (str "a = " a)) (>= a w) ) wrappers)))] The problem I have is that I...

Mutable tree to persistent tree

java,clojure,tree
Learning Clojure (and Functional Programming) I have stumbled upon the problem of converting a mutable n-ary tree represented as nested java.util.ArrayLists into a persistent tree. Using non-functional programming you would normally create the tree from the root to the leaves. This does not seem to be possible using persistent data...

Change last element in list

clojure
I have a nested list: (def mylist '(+ '(+ 1 2) 3)) When I eval it, I get 6 as expected: (eval mylist) How can I change the last element (3)? I'd like to get a list like this: (+ (+ 1 2) 4) I've tried (list (butlast mylist) 4)...

Join string elements from set literal in Clojure

string,clojure
Newish Clojure developer with a Python and C# background. I have something similar to: (def coll #{ :key1 ["string1"] :key2 ["string2"]}) I need to define a new string that concats the values of the two key vectors. I have tried (clojure.string/join (get coll :key1 :key2)) (concat (get coll :key1 :key2))...

Apply a sequence of functions to data

clojure
I wish apply a sequence of functions to a data, like pipe: http://ramdajs.com/0.14/docs/#pipe I know it has ->>and ->, also I have difficulty in defining the internal functions (defn create ([code error] {:statusCode code :error error}) ([code error & [message data]] (create code error) - I want pipe it result...

How to iterate over a result set and extract one particular value in clojure?

clojure
Below is my attempt to iterate over a result set and get its values (sql/with-connection db (sql/with-query-results rs ["select * from user where UserID=?" 10000] (doseq [rec rs s rec] (println (val s)) ))) But how do you extract one particular value from it; i need only the user name...

Clojure Ring: How to determine if development server is running?

clojure,leiningen,ring
I have a project containing both Clojure & ClojureScript code. I would like to include unoptimized ClojureScript when I run my server via lein ring server and optimized ClojureScript otherwise. What is the idiomatic way to do this? I am using: [[bidi "1.19.0"] [hiccup "1.0.5"] [org.clojure/clojure "1.7.0-beta3"] [org.clojure/clojurescript "0.0-3269"]] [[lein-cljsbuild...

What is clojure.core equivalent of lodash _.pluck

javascript,clojure,lodash
Lodash _.pluck does this var users = [ { 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 } ]; _.pluck(users, 'user'); // → ['barney', 'fred'] Good thing about it is it can also go deep like this: var users = [ { 'user': {name: 'barney'}, 'age': 36 },...

Converting defmulti to defprotocol

clojure
Is it possible to convert the below code so it uses defprotocol and defrecord instead of defmulti and defmethod? (defmulti test-multimethod (fn [keyword] keyword)) (defmethod test-multimethod :foo [a-map] "foo-method was called") (defmethod test-multimethod :bar [a-map] "bar-method was called") (defmulti perimeter (fn [shape] (:shape-name shape))) (defmethod perimeter :circle [circle] (* 2...

Clojure - map values

clojure
I'm trying get a clojure function to detect if the value passed is a map. For example, user=> (if-map {:foo 1}) ;Should return true true user=> (if-map "hello") ;Returns false false Is there a pre-built function serving this already? ...

ImageIO import not working Clojure

java,clojure
I'm a bit of a Clojure novice, but I don't understand what's wrong about my code. The code bellow to my knowledge should set imgto a new BufferedImage object. (import javax.imageio.ImageIO) (import java.io.File) (def img (ImageIO/read (File. "C:\\input.png"))) However, when I execute lein run I get this exception: Exception in...

Sequentially calling a function with elements from a vector

clojure
Suppose I have a function f that accepts two arguments x & y. I also have a vector X composed of elements x1, x2, ... xn. How can I write a function g, where g(X, y) calls f(xi, y) for all x? Further specification: I would like g to return...

Clojure: difference between applying directly or by way of a function

clojure
The aim is to play with a slight modification of the Caesar cipher. First a function to move a character: (defn move-char [c shift idx encode-or-decode] (let [ch (int c) val (mod (* encode-or-decode (+ shift idx)) 26)] (cond (and (>= ch (int \A)) (<= ch (int \Z))) (char (+...

Clarifying Clojure “Use as” semantics

clojure
The effect of (use '[clojure.string :as str]) seems to be loading everything from clojure.string into the current namespace without namespace qualification. The effect of (use '[clojure.string :as str :only (join)]) seems to be loading only join into the current namespace, making the rest of the clojure.string namespace accessible with the...

Clojure: wrap-ssl-redirect on heroku?

https,clojure,ring
I've just tried add this wrapper (-> routes (wrap-ssl-redirect)) for auto redirecting http to https, but when I deploy to heroku, the https:// doesn't get green in my browser, and the website doesn't load. Isn't the default heroku port 443, which should also be the default from wrap-ssl-redirectfunction? What is...

Keeping a string variable from being destructured

clojure
Pretty simple question here, but it is really stumping me up. I have a small function here: (defn something [start-url n] (loop [urls start-url index n] (if (= index 0) (set urls) (recur (flatten (pmap #(str *base-url* %) urls)) (dec index))))) I have changed the important parts of the code,...

Clojure's Cheshire JSON API not reading entire JSON file

clojure
I have JSON data in the following format: {"load":{"meta" 12345}} {"load":{"meta" 54321}} ... When I attempt to load the data with Cheshire I get back only the first line of data translated into edn: (def read-json-data (parse-string (slurp "data/json_data") true)) => {:load {:meta 12345}} If anybody has come accross this...

Idiomatic clojure to parse command line switches and args from string

clojure
I'd like to parse a command line string, and group any command switches with their subsequent arguments. So, for example: (parse "git branch -d f1 f2 -a -m message") => [["-d" "f1" "f2"]["-a"]["-m" "message"]] I ignore args not immediately following a switch. The code I wrote to do this is...

Clojure map a set to another set directly?

clojure
user=> (map inc #{1 2 3}) (2 4 3) user=> (into #{} (map inc #{1 2 3})) #{4 3 2} Is there a way to apply a function to a set and return a set directly?...

How to check whether Clojure code is being evaluated inside a REPL?

clojure,leiningen
I would like to format my logs differently depending on whether my code is being run from a REPL or if I'm running the compiled jar. Is there any simple way to do this? I was thinking maybe Leiningen leaves a trace somewhere when running the REPL....

Why such implementation of partial in clojure.core

clojure
I stumbled across implementation of partial function in cojure.core. It looks like this: (defn partial "Takes a function f and fewer than the normal arguments to f, and returns a fn that takes a variable number of additional args. When called, the returned function calls f with args + additional...

How to require dependencies in Clojure?

clojure,clojure-testing
I have two questions regarding dependencies in Clojure project. Is there something like :dev-dependencies or :test-dependencies so that I don't have to download them all on lein run? So until I run my tests I don't need to have these extra libraries. Can I load dependencies in one file and...

previous function input parameter correct storing

clojure
I started to learn clojure so pardon for noob question I try to implement following function pseudo code: function(x y) { if (x != oldX) dosomething(y); oldX = x; } oldX is global variable How can i properly do this the clojure way? I wrote something this but is this...

Why does leiningen download 1GB (almost) of jar indexes and how to stop that?

clojure,leiningen
Leiningen downloaded nearly 1GB of jar index information from repo1.maven.org and clojars.org. Why does it need to download that huge amount of information? And is there any way to prevent that? The directory in question is: ~/.lein/indeces It contains the following folders: https___clojars.org_repo_ https___repo1.maven.org_maven2_ The maven.org folder contains 849MB! Here...

Read file until certain line in Clojure using doseq

clojure
This would normally be trivial in other language, but I've found no such example in Clojure. I can println an entire file using: (with-open [rdr (io/reader "file")] (doseq [line (line-seq rdr) :while (< count(line) 10)] (println line))) But how do I get it to stop at line 5? Thanks....

sequence comprehensions to get run

clojure
The below code I have found from a book (Functional Programming Patterns in Scala and Clojure). The for statement uses close-zip? to filter out people outside of the zips and then it generates a greeting to the people who are left. However, I am not quite sure how people should...

How can I create a global object, and attach a string and a function to that object, in ClojureScript?

clojure,clojurescript
How can I create a global object, attached to the window, and attach a string and a function to that object, in ClojureScript? For example, an myobject that looks like: {"foo": function () {..}, "bar": "somestring"} myobject.foo => function () { .. } myobject.bar => "somestring"...

Mandelbrot set function does not perform as expected

performance,clojure
Here is an example from Clojure Programming Paperback by Chas Emerick: (import 'java.awt.image.BufferedImage '(java.awt Color RenderingHints)) (defn- escape [^double a0 ^double b0 ^long depth] (loop [a a0, b b0, iteration 0] (cond (< 4 (+ (* a a) (* b b))) iteration (>= iteration depth) -1 :else (recur (+ a0...

Converting vector to indexed map in Clojure?

dictionary,vector,clojure
Let's say I have the following vector of maps: [{:name "Jack" :age 5} {:name "Joe" :age 15} {:name "Mare" :age 34} {:name "William" :age 64} {:name "Adolf" :age 34}] I want to convert this to an indexed map, like: {1 {:name "Jack" :age 5} 2 {:name "Joe" :age 15} 3...

Idiomatic way to select a map in vector by a key

clojure,clojurescript
Suppose I have this vector of maps: [{:title "Title1" :id 18347125} {:title "Title2" :id 18347123} {:title "Title3" :id 18341121}] And I wish to select the map with :id 18347125, how would I do this? I've tried (for [map maps :when (= (:id map) id)] map) This feels a bit ugly...

ePassport Problems reagrding MAC creation in ICAO 9303 “worked examples” in Java/Clojure

java,clojure,bouncycastle
i work on a application where I need to read Data from epassports. I'm working through the "worked examples" in ICAO Doc 9303 Part 3 Volume 2 (Third Edition). There is a section in the worked examples, where they put together the MUTAUAL_AUTHENTICATE apdu. It involves calculating the MAC of...

clojure performance on badly performing code

clojure
I have completed this problem on hackerrank and my solution passes most test cases but it is not fast enough for 4 out of the 11 test cases. My solution looks like this: (ns scratch.core (require [clojure.string :as str :only (split-lines join split)])) (defn ascii [char] (int (.charAt (str char)...

How to integrate figwheel with ring server to get back-end auto-reload?

clojure,clojurescript,ring
I am new to clojure/clojurescript web development. Use lein ring server and the modifications(for example routes) will be automatically reloaded to the server(hot-deploy). Use lein figwheel, and it will spy on the changes of cljs source files and updated to the page accordingly. Now I started figwheel and modified the...

How to perform synchronous parallel functions in Clojure?

clojure,parallel-processing
I have an application which has an initial flow that can be done in parallel: Fetch two JSON documents (I use clj-http for that) Parse these documents (extract only required data) Join the results Dump them into a one file So there's something like that: some-entry-point /\ / \ /...

Build macro result with loops

clojure,javafx
I'm building a macro that should be called like this: (myMacro MyController something otherthing (defn onFoo [this event] (println "ok")) (defn onBar [this event] (println "ok")) ) After the first three parameters I want to be able to pass a few functions that should be used to build the function...

Is equality properly defined on chan?

clojure,core.async
I want to maintain a collection of channels, with the ability to add and remove channels. Is the equality defined so I can conj and disj correctly? In other words, will this always work? => (def chan-collection (atom #{})) => (def my-chan-1 (chan)) => (def my-chan-2 (chan)) => @chan-collection #{}...

Using resolve to call function - Clojure

clojure,http-kit
I am using resolve to call a function given they name (String), like (call "+" 10 10 10) ;; 30 The call function: (defn call [this & that] (apply (resolve (symbol this)) that)) Everything works fine on REPL. But when I start the project as a server using httpkit http...

Clojure interop with Java: how to call a class?

java,maven,clojure,interop,leiningen
I have a Java app that has a class at this address, inside a standard Maven layout: src/main/java/com/ollio/nlp/Transformer.java The class and method that I want looks like this: package com.ollio.nlp; public class Transformer { public String transform(String JSONInput) { I store the jar artifact locally in my Clojure app at...

Questions about Vars Clojure

clojure,functional-programming
I'm new in Clojure and i read that it is a functional language. It says that Clojure doesn't have variables, still when i find (def n 5), what's the difference between it and a variable? I can change the value of the var after, so is it really that different...

How to wrap oAuth headers in clj-http?

oauth,clojure,twitter-oauth,clj-http
I'm trying to post a twitter status update with clojure... but this probably really is a question about oAuth headers, and using it through the wonderful clj-http library. I've used clj-http before for basic-auth and other type of headers and it was fairly straightforward. The Authorization: Bearer ... was a...

Immutant2 server logs showing fishy error message

clojure,immutant,alipay
I got this error message a couple of times 21:36:01,172 ERROR [io.undertow.request] (default task-18) Undertow request failed HttpServerExchange{ CONNECT www.alipay.com:443}: java.lang.IllegalArgumentException: UT000068: Servlet path match failed at io.undertow.servlet.handlers.ServletPathMatchesData.getServletHandlerByPath(ServletPathMatchesData.java:83) at io.undertow.servlet.handlers.ServletPathMatches.getServletHandlerByPath(ServletPathMatches.java:76) at...

Import Record Type in Clojure/ClojureScript

clojure,clojurescript
Is there any way to import a record type, that works in Clojure as well as ClojureScript? As far as I can tell it's (ns x (:import y [A B])) for Clojure, (ns x (:require y :refer [A B])) for ClojureScript, and each is invalid for the respective other.

core.typed not reporting type error in repl

clojure,clojure-core.typed
Here is a part of the example taken from core.typed github repo: (ns typedclj.rps-async (:require [clojure.core.typed :as t] [clojure.core.async :as a] [clojure.core.typed.async :as ta])) (t/defalias Move "A legal move in rock-paper-scissors" (t/U ':rock ':paper ':scissors)) (t/defalias PlayerName "A player's name in rock-paper-scissors" t/Str) (t/defalias PlayerMove "A move in rock-paper-scissors. A...

Clojure normalize function runtime error

clojure,clojure-contrib
This code that I wrote gives me the error: java.lang.Long cannot be cast to clojure.lang.IFn which means that I am using a number where a function is expected. I think it has to do with the expt functions from clojure.math.numeric-tower but I am not sure. cryptic error messages FTL. (ns...

Cannot Create Project in Eclipse Counterclockwise Clojure Plugin

eclipse,clojure,counterclockwise
I just installed the Eclipse Counterclockwise Clojure Plugin, and I cannot create a new Clojure project. The CCW troubleshooting page here says there's a way to fix this, but unfortunately the link is now broken. When I try to create a project there are no options to select for a...

basic http auth in Clojure/Friend

clojure,basic-authentication,compojure
I am trying to make a basic auth for an API in Clojure with friend. Here is the login request : curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d 'user=myuser%40email.com&pass=super-secret-password' http://localhost:3000/login/ I am using compojure as well, but I'm not sure how to reuse the linked example. Here are the parts...

How do I fix this dependency issue in Clojure?

clojure,dependencies,jackson,leiningen
I'm having a lot of trouble fixing an issue where the dependencies for two different packages are colliding. My project.clj's dependencies look like this: :dependencies [[org.clojure/clojure "1.6.0"] [itsy "0.1.1"] [amazonica "0.3.22" :exclusions [commons-logging org.apache.httpcomponents/httpclient com.fasterxml.jackson.core/jackson-core]]]) My namespace looks like this: (ns crawler.core (:require [itsy.core :refer :all]) (:require [itsy.extract :refer :all])...

Clojure throws an exception when I don't expect it to

clojure,throw
I have this code to get data from sumo logic and other services. core.clj has this, which parses the arguments and routes it to the right function in route.clj (def cli-options [ ["-a" "--app APPNAME" "set app. app can be: sumologic or jira"] ["-?" "--help"] ]) (defn -main [& args]...

in clojure, function argument type mismatch

clojure,functional-programming,lisp
clojure, function argument is vector, but it takes a map without problem. (defn flower-colors [colors] (str "The flowers are " (:flower1 colors) " and " (:flower2 colors))) (flower-colors {:flower1 "red" :flower2 "blue"}) ;; -> "The flowers are red and blue" Function flower-colors suppose to take vector type argument, but with...

Maybe in clojure

clojure
Trying to write a composed function in clojure that exits at the first nil value, (e.g something you'd do by chaining Maybes together in haskell) with the following: (defn wrap [f] (fn [x] (if (nil? x) nil (f x)))) (defn maybe [arg & functs] ( (comp (reverse (map wrap functs)))...

Why does ^metadata 'symbol not work?

clojure,metadata,read-eval-print-loop
The documentation on metadata claims that ^{:hi 10} 'x is equivalent to (with-meta 'x {:hi 10}), but I can't see that. Evaluating the following on a repl, (binding [*print-meta* true] (prn ^{:hi 10} 'x) (prn (with-meta 'x {:hi 10}))) prints the following, which shows that the first case doesn't get...

Clojure: Scala/Java interop issues for Spark Graphx

java,scala,clojure,spark-graphx
I am trying to use Spark/GraphX using Clojure & Flambo. Here is the code I ended up with: In the project.clj file: (defproject spark-tests "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"] [yieldbot/flambo "0.5.0"]] :main ^:skip-aot spark-tests.core :target-path "target/%s" :checksum :warn...

Compute in a new thread and refer to results later in R

r,concurrency,clojure
In clojure I can do something like this: (def x ;; perform some expensive computation in a new thread ;; the repl is not blocked, so you can go on do something else (future (do (Thread/sleep 500) 3.14))) ;; ... do something else ;; now when you need x ;;...

More readable messages with :pre and :post?

clojure,contracts
In clojure I am using :pre like this user=> (defn cannot-take-empty [x] {:pre [((complement empty?) x)]} 1) #'user/cannot-take-empty user=> (cannot-take-empty #{}) AssertionError Assert failed: ((complement empty?) x) user/cannot-take-empty (NO_SOURCE_FILE:186) That's great, but it doesn't explain the business reason why it doesn't make sense to pass in an empty collection. (Or...

When did the metadata reader syntax change from #^ to ^?

clojure
Currently (Clojure v1.6) you can give a type hint two ways: ^floats xs #^floats xs According to Clojure ^floats vs. #^floats?, the latter is legacy syntax, and the former is the current preferred form. When did that change happen?...

Clojure - apply to all but nth element

clojure
I have a vector that looks like: [ "1" "2" "3" "4" ] I wish to write a function returns the vector to: [ 1 "2" 3 4 ] ; Note that the second element is still a string Note that nothing is changed, an entirely new vector is returned....

clojure and ctags, catching def* forms

clojure,ctags,exuberant-ctags
So I found the following snippet from a Gist a while back: --langdef=Clojure --langmap=Clojure:.clj --langmap=Clojure:+.cljx --langmap=Clojure:+.cljs --regex-clojure=/\([ \t]*create-ns[ \t]+([-[:alnum:]*+!_:\/.?]+)/\1/n,namespace/ --regex-clojure=/\([ \t]*def[ \t]+([-[:alnum:]*+!_:\/.?]+)/\1/d,definition/ --regex-clojure=/\([ \t]*defn-?[ \t]+([-[:alnum:]*+!_:\/.?]+)/\1/f,function/ --regex-clojure=/\([ \t]*defmacro[ \t]+([-[:alnum:]*+!_:\/.?]+)/\1/m,macro/ --regex-clojure=/\([ \t]*definline[...

How to specify max memory for clojure heroku app?

heroku,clojure
Running a clojure app on Heroku, I've specified this in my leiningen profiles.clj :jvm-opts ^:replace ["-Xms128m" "-Xmx350m" "-Xss512k" "-XX:MaxMetaspaceSize=150m"] And I'm running my worker with lein trampoline run But, I get these errors currently: 2015-06-20T14:38:14.652680+00:00 heroku[worker.1]: Error R14 (Memory quota exceeded) 2015-06-20T14:38:34.779145+00:00 heroku[worker.1]: Process running mem=552M(107.8%) 2015-06-20T14:38:34.779145+00:00 heroku[worker.1]: Error R14...

clojure quoting inside let

clojure,macros,eval
Quoting (both syntax and non-syntax) seems to fail to detect vars inside a let statement: (let [foo 1] (eval `(print foo))) This will generate an error or use whatever prior value bound was bound to foo in (def foo bar). Is there a way to make the syntax quote use...

How trampoline work with multimethods in Clojure

recursion,clojure
Im trying to understand how trampoline is used to support mutual recursion with tail recursion. However im lost when both the example below compiles with the same result. I believed that each defmethod had to return a function as in example 2 below. But this is clearly not the case...

Querying the number of elements in a buffered core.async/chan

clojure,core.async
Having a buffered chan, say (def c (clojure.core.async/chan 100)) is it possible to query how many elements are currently inside the chan?...

4clojure #57 - Simple Recursion

recursion,clojure
I am going through 4clojure problems and I cannot figure why following code is working user=> ((fn foo [x] (when (> x 0) (conj (foo (dec x)) x))) 5) (5 4 3 2 1) I understand that (foo (dec x)) has to be treated as a PersistentCollection for this to...

Does the Zookeeper Watches system have a bug, or is this a limitation of the CAP theorem?

clojure,zookeeper,watch,stm,cap-theorem
The Zookeeper Watches documentation states: "A client will see a watch event for a znode it is watching before seeing the new data that corresponds to that znode." Furthermore, "Because watches are one time triggers and there is latency between getting the event and sending a new request to get...

Generator pattern code can't return value

clojure
I want to create a generator to do, 1 2 3 4. (defn getNums [] (loop [i 4 r []] (when (<= i 0) r ;<--- point A (recur (dec i) (conj r i))))) (getNums) ;Eval to nil. Nothing get return, why ? Would the code in point A return...

Group vectors with same first element into lists of vectors

clojure
I have ([AA moo foo boo][AA soo doo foo][BB woo roo too][BB koo ooo yoo]) I need to group it so I get lists of vectors with the same first element: ([AA moo foo boo][AA soo doo foo])([BB woo roo too][BB koo ooo yoo]) Is there a grouping function? Thanks...

How can I use single or double quote in Clojure Macro?

clojure
I am making a macro which uses single quotes. However, whenever I parse the macro the single quote text like: 'java' :is expanded to: (quote java') Does anyone know a way around this so that it doesn't expand to the quoted form? Update I have a kind of working workaround...

Clojure invokeLater null pointer

swing,concurrency,clojure
This code: (import 'javax.swing.SwingUtilities) (SwingUtilities/invokeLater (print "hi")) Causes this error: Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209) ... I don't know if this is a problem, since the code itself actually works (printing to the REPL) despite the error. However, modifying swing components does not seem to work properly: a...

Clojure project layout and relative imports

clojure
I'm having a hard time starting out on my first clojure project. I have found a ton of tutorials and answers to questions, but none of the seems to answer my problem. I have created a blank project using Leiningen. This example explains my problem: project.clj: (defproject clojurenet "0.1.0-SNAPSHOT" :description...

go block hangs indefinitely with core.sync

asynchronous,clojure,core.async
Here is the code: (ns typed-clj-test.async (:require [clojure.core.async :as a :refer [>! <! >!! <!! go chan buffer close! thread alts! alts!! timeout]])) (def echo-buffer (chan 2)) (go (do (<! (timeout 5000)) (println (<! echo-buffer)))) (>!! echo-buffer "msg1") (>!! echo-buffer "msg2") (>!! echo-buffer "msg3") (>!! echo-buffer "msg4") This hangs forever...

clojure macro create || comparison?

clojure,macros
I want to create an || comparison with Clojure like other languages. (defmacro || [source & other] `(loop [s# [~source [email protected]]] (println s#) (let [fs# (first s#)] (if fs# fs# (if (= (count s#) 1) fs# (recur (next s#))))))) but this can't work. fs# value is quote data. like this...

Translate encoding of string

clojure,character-encoding,decode,windows-1252
I have a string that is in Windows-1252 encoding, but needs to be converted to UTF-8. This is for a program that fixes a UTF-8 file that has fields containing Russian text encoded in quoted-printable Windows-1252. Here's the code that decodes the quoted-printable: (defn reencode [line] (str/replace line #"=([0-9A-Fa-f]{2})=([0-9A-Fa-f]{2})" (fn...

select's fields function of korma does not reject colums?

clojure,sqlite3,korma,sqlkorma
I play around with clojure and its korma library using an sqlite3 database on windows. I follow an example of the 7web book. It introduces the select* function and its friends. But using the fields function adds fields instead of restricting. ;; models.clj (defentity issue (entity-fields :id :project_id :title :description...

deploy compojure app that is also a CLI app

clojure,compojure
I have a Clojure app that I can use both from the command-line, and as a Compojure app. I did that by putting a ring handler and a main function (clojure.tools.cli) in my leiningen project.clj. {... :main my-app.core :ring {:handler my-app.handler/handler }} The handler is defined (defroutes handler ...). Now...

Clojure loop receiving IllegalArgumentException Key must be integer clojure.lang.APersistentVector.invoke

clojure
I'm stuck trying to get a simple loop in Clojure to work and I don't know how to proceed to get rid of the exception. I'm trying to write an arrange function to exchange items in a vector. Here is the code. (defn exchange [v i] (let [[src dst] i]...

Clojure avoid repetition on tests

clojure
In my tests I need repeat this a block of tests for each function. In this case I'm testing bad-request function, the things that need change between each test is the bad-request call, code, and error. (deftest t-bad-request ... (testing "with data" (equal (merge error code message DATA) (bad-request MESSAGE...

What does clojure 'val' return this value?

clojure
I'm just starting to learn clojure and have been reading some simple examples and then doing my best to rtfm for concepts. However I'm a bit confused by what val is doing in the example below. This has been taken from the Clojure doc examples for val. (first {:one :two})...

Brand new Luminus app giving Error: Could not find or load main class clojure.main

heroku,clojure,procfile,luminus
I just created a Luminus app by running: lein new luminus foobar and when I try to run it with foreman like this: foreman start the way the docs describe, I get this error: Error: Could not find or load main class clojure.main which is also the same error I...

No-argument (and) returns t

clojure,scheme,lisp,common-lisp
Both CL and Scheme define (and) to return t (or #t) with no arguments. I'm trying to understand the rationale for this. My naive assumption is that an empty set is false, and passing in zero arguments feels like passing in nothing that can be true. Edit: clojure follows the...

Clojure ^floats vs. #^floats?

clojure
What is the difference between ^floats and #^floats in Clojure type annotations? In a pull request, someone suggested I use this annotation: (.put #^floats init-fft-array) which did the trick, but I don't know why the '#' is there. I found this worked, too: (.put ^floats init-fft-array) Is there any difference?...

Is order guaranteed when multiple processes are waiting to put data in the same channel?

clojure,core.async
Here is the code: (ns typedclj.core (:require [clojure.core.async :as a :refer [>! <! >!! <!! go chan buffer close! thread alts! alts!! timeout]]) (:gen-class)) (def mychan (chan)) (go (while true (>! mychan "what is this?"))) (go (loop [i 0] (>! mychan (str "msg" i)) (recur (inc i)))) (go (loop [i...

AngularJS $http GET method to backend server: Request Method:OPTIONS 405

angularjs,clojure
$http GET request to a clojure backend, to get a list of services. I get is an OPTIONS request (???), which gets a 405 response... <code> var config = {headers: { 'Authorization': 'Bearer d2VudHdvYW5nZV9tZQ', "X-Testing" : "testing" } }; $http.get(SERVER.MESSAGE_SERVICES, config) .success(function(successCallback) { $scope.services = successCallback; }) .error(function(errorCallback) { console.log(errorCallback.toString);...

Unable to parse out EDN in this server request

clojure,ring
I think I'm doing things right but I can't get my EDN out of the :body input stream. The Ring and Compojure handler is this: dependencies: [ring.middleware.params :as params] [ring.middleware.edn :as edn]; https://github.com/tailrecursion/ring-edn Handler: (defroutes ajax-example (PUT "/ajax-example" r (println r) {:status 200 :headers {"Content-Type" "application/edn"} :body "yo"})) I wrap...

Making a simple countdown timer with Clojure/Reagent

clojure,reagent
I am experimenting with Clojure and Reagent with almost no experience, trying to make a simple timer. (defn reset-component [t] [:input {:type "button" :value "Reset" :on-click #(reset! t 60)}]) (defn countdown-component [] (let [seconds-left (atom 60)] (fn [] (js/setTimeout #(swap! seconds-left dec) 1000) [:div.timer [:div "Time Remaining: " (show-time @seconds-left)]...

Leiningen REPL not autoloading project.core namespace [duplicate]

clojure,namespaces,read-eval-print-loop
This question already has an answer here: how to load ns by default when starting repl 2 answers I'm new to Clojure so this could very well be an easy question. I'm having an issue with the REPL while using Leiningen. Previously, I had created an app project while...

Side effects not realized without deref

concurrency,clojure
From clojure for the brave and true: (defmacro enqueue [q concurrent-promise-name & work] (let [concurrent (butlast work) serialized (last work)] `(let [~concurrent-promise-name (promise)] (future (deliver ~concurrent-promise-name (do [email protected]))) (deref ~q) ~serialized ~concurrent-promise-name))) (defmacro wait "Sleep `timeout` seconds before evaluating body" [timeout & body] `(do (Thread/sleep ~timeout) [email protected])) (time @(-> (future...

How to build a lazy sequence of perfect number in Clojure?

clojure
I tried to find a list of perfect number in this way: (defn classify [num] (let [factors (->> (range 1 (inc num)) (filter #(zero? (rem num %)))) sum (reduce + factors) aliquot-sum (- sum num)] (cond (= aliquot-sum num) :perfect (> aliquot-sum num) :abundant (< aliquot-sum num) :deficient))) (defn is-p...

What is wrong with the following Clojure program ? Memoized version of Fibonacci

clojure
(def fibVal {1 1 2 1}) (defn fibonacci [x] (if (false? (get fibVal x false)) (do (println (str "Evaluating " x)) (def fibVal (assoc fibVal x (+ (fibonacci(- x 1)) (fibonacci(- x 2))))) (println (str x " Evaluated to " (fibVal x))) (fibVal x) ) (get fibVal x) ) )...

How to add keys to a map / create keys in current map clojure

clojure,ring
I have the following map from a get request :form-params {"qu" ["2015 Q2" "2015 Q3" "2015 Q4" "2015 Q2" "2015 Q3" "2015 Q4" "2015 Q2" "2015 Q3" "2015 Q4" "2015 Q2" "2015 Q3" "2015 Q4"], "sh" ["2580" "2580" "2580" "2983" "2983" "2983" "53" "53" "53" "4558" "4558" "4558"], "prin" ["191"...

Accessing argument's metadata in Clojure macro

clojure,macros
Is there a way to retrieve the metadata of the arguments inside a clojure macro without using eval? The only thing I could come up with so far is this: (def ^{:a :b} my-var) (defmacro my-macro [s] (prn (eval `(meta (var ~s))))) (my-macro my-var) ;; Prints {:a :b, :name my-var,...

Simple runscript example with jclouds and clojure (or even just jclouds)

clojure,jclouds
I have this clojure code (let [group-name "my-test-group" compute (compute-service provider user password) node (create-node compute group-name) node-id (.getId node)] (.runScriptOnNode compute node-id ??) (destroy-node compute node-id)) and I would like to run ls on my instance just as an example. What do I put in the ?? to make...

immutant failing to add a cache to a web cache container

caching,clojure,wildfly,immutant
I have a heimdallr application that is deployed via wildfly. In this application I am using the cache functionality that is provided by the namespace immutant.caching. The first time I deploy the application everything goes fine without error. If I attempt to redeploy the application I get the following error:...

Append to clojure vector from within loop

clojure
I have: (defn keep? (def sum []) (loop [i 0] (when (< i 10) (conj sum 10) (recur (inc i)))) sum ) This just gives me and empty vector even though I am conj-ing 10 onto sum. Is this because it is not in-scope within the Loop? How would I...

Is there a better way to debug clojure code?

clojure
I've been working with Clojure for few weeks now, primarily with Lein+Luminus framework. I've been looking for a way to debug code while on the REPL. I really like the way how pry(on Ruby) works, when it comes to debugging and runtime invocation. Is there an equivalent to pry for...

upper limit for number of jobs in a do block?

multithreading,clojure,core.async
Here is the code: (ns typedclj.async (:require [clojure.core.async :as a :refer [>! <! >!! <!! go chan buffer close! thread alts! alts!! timeout]] [clj-http.client :as -cc])) (time (dorun (let [c (chan)] (doseq [i (range 10 1e4)] (go (>! c i)))))) And I got an error: Exception in thread "async-dispatch-12" java.lang.AssertionError:...