This page is not created by, affiliated with, or supported by Slack Technologies, Inc.
2020-09-29
Channels
- # announcements (1)
- # babashka (120)
- # beginners (184)
- # cider (14)
- # clara (2)
- # clj-kondo (25)
- # cljfx (9)
- # cljsrn (43)
- # clojure (46)
- # clojure-australia (2)
- # clojure-berlin (5)
- # clojure-dev (2)
- # clojure-europe (10)
- # clojure-france (3)
- # clojure-nl (1)
- # clojure-spec (14)
- # clojure-uk (30)
- # clojurescript (50)
- # code-reviews (19)
- # conjure (11)
- # core-logic (2)
- # cursive (20)
- # datascript (1)
- # datomic (74)
- # figwheel-main (1)
- # fulcro (10)
- # funcool (2)
- # graphql (1)
- # lambdaisland (1)
- # malli (2)
- # meander (22)
- # nrepl (13)
- # off-topic (28)
- # overtone (3)
- # pathom (7)
- # pedestal (4)
- # re-frame (4)
- # reagent (16)
- # reitit (4)
- # releases (1)
- # ring (8)
- # shadow-cljs (93)
- # specter (6)
- # sql (13)
- # test-check (1)
- # tools-deps (1)
- # tree-sitter (2)
- # vim (8)
- # xtdb (25)
is it possible to embed a clj interpreter (like sci) in a java project to evaluate clj formulas stored in database ? 🙂
the idea is to create a formula engine
clj looks great for that cause it's easy to parse the code stored in a string
@borkdude cool , good to know 🙂
@benoit.caccinolo yes. you can use load-string
from Clojure or eval-string
from sci.
Sci had a Java interface, but since nobody was using it, I deleted it.
https://github.com/borkdude/sci/commit/6bbccc3eec050dd0d4fc9cf017b89577e0269494
Most of the work in the Java API was to create Option classes and convert them into maps. Not a lot of fun
So I figure if you want to use sci, make a little Clojure wrapper with your options and then call that from Java
Here is info how to call Clojure from Java: https://clojure.github.io/clojure/javadoc/clojure/java/api/package-summary.html
Do you mean it would be easier with vanilla clojure ?
Sci is easier to use from Clojure than from Java. So make a little Clojure wrapper around sci (specific for your use case) that you call from Java, if you want to use sci.
ok I look at this
thx for the fast answer, I'll look at this.
I'm considering removing the JS api from sci as well. Most people need specific options. It's easier to just call it from CLJS specific to a project and then compile that to JS
Hi, I have an algorithm to implement that "buys" goods from list of maps [{:name "good 1" :price 12} {:name "good 2" :price 17} ...]
. Every good may have a different price. And I want to keep buying until it has no more cash left (some finite amount). Is there an idiomatic way to do it in Clojure? Something like reduce-until
:thinking_face:
I don't think so -- you'll need to carry the state (e.g. cash left) around, it's cumbersome. I think loop
is a good fit.
I also did not find anything elegant here so my solution:
(def cash-spent (atom 0))
(defn accumulate-price [item limit]
(swap! cash-spent #(+ % (get item "price")))
(>= limit @cash-spent))
(take-while #(accumulate-price % cash-available items))
you can used reduced
to duck out of a reduce
early. I'm not completely sure that this does what you want, but something like:
(reduce
(fn [cash-spent item]
(if (>= limit cash-spent)
(reduced cash-spent)
(+ cash-spent (get item "price"))))
0
items)
What's the magic behind map->ResponseFormat
here? https://github.com/JulianBirch/cljs-ajax/blob/master/src/ajax/interceptors.cljc#L223
I expected to find a regular function with such name defined somethere in cljs-ajax codebase but couldn't.
Is it some sort of a convention?
each defrecord defines few functions:
->RecordName
and map->RecordName
https://github.com/JulianBirch/cljs-ajax/blob/master/src/ajax/interceptors.cljc#L93
Thank you!
Is there a way to ask the Clojure testing env to tell me which tests are running rather than waiting to the end? One of my tests sometimes takes a very long time. I could do a binary search to find it, but it would be nice if I could just turn on a verbose mode
If you are using the clojure.test library for writing tests, there are some ways to write code that is executed at the beginning or end of each deftest
form. An example of using that to print a message when each deftest
begins, and to print how long in elapsed time each one took to finish, is here: https://github.com/clojure/core.rrb-vector/blob/master/src/test/clojure/clojure/core/rrb_vector/test_utils.clj#L52-L64
It has been a while since I wrote that code, but if I recall correctly, I put that code, and some other "test utility functions", into one namespace defined in that file, and then :require
it from all other namespaces in that project that have deftest
forms.
Kaocha test runner will tell you which tests too the longest to run https://cljdoc.org/d/lambdaisland/kaocha/1.0.700/doc/1-introduction There is also a reporter plugin to show progress, although my tests run so fast I cant tell if its doing them one by one (I think it does)
Is the idea of kaocha that I still have the code using the normal testing macros, deftest, is, testing, but I need to require something different?
Kaocha will run clojure.test unit tests and many other things. No changes are required to the tests. Some basic examples here https://practicalli.github.io/clojure/testing/test-runners/kaocha-test-runner.html
Hello all, first time joining, so forgive me if this is the wrong place to ask. I am trying to query postgres using clojure.java.jdbc and then trying to put the results into a vector which I then send inside of a json object. When I try to do this, the results vector sent back is empty. Could someone help me identify the problem? My thoughts were that this is a side effects issue, but I tried enclosing things in a do block and I still had the same issue. Here is the code:
(defn get-meets [request]
Try sharing the code in a GitHub gist file or in a Git repository if you can, it will make it easier (unless its just a few lines of code) Recommend you use the https://github.com/seancorfield/next-jdbc as this replaces clojure.java.jdbc There is also a #sql channel here where you may get specific help. I am also building a website using next.jdbc that talks to H2 and postgresql database which I am documenting here: https://practicalli.github.io/clojure-webapps/projects/banking-on-clojure/ There is also a video series of how I am working through creating this application. Its work in progress, but hopefully you will find it useful
clojure data is immutable, (reduce conj results rs) does not fill up the results vector you have defined above, and the resultset is lost,
(defn get-records [request]
(let [{limit :limit, offset :offset, type :type} (:params request)
results []]
(response
(try
(cheshire/generate-string {:results (doall
(jdbc/query db-spec
["SELECT * FROM records ORDER BY on_date LIMIT ? OFFSET ?;" (Integer/parseInt limit) (Integer/parseInt offset)] ))})
(catch Exception e (cheshire/generate-string {:error (.getMessage e)}))))))
try this, I didn't try but it should workWow that worked! Thank you. Also @U05254DQM I will keep up with your video series as i'm sure it wil be useful, thank you for that as well.
Code of a handful of lines is okay to post here, yours was fine. If you want to post a lot of code then Gist or repo is better.
(defn get-records [request] (let [{limit :limit, offset :offset, type :type} (:params request) results []] (response (try (jdbc/query db-spec ["SELECT * FROM records ORDER BY on_date LIMIT ? OFFSET ?;" (Integer/parseInt limit) (Integer/parseInt offset)] {:result-set-fn (fn [rs] (reduce conj results rs))}) (cheshire/generate-string {:results results}) (catch Exception e (cheshire/generate-string {:error (.getMessage e)}))))))
can someone help me figure out how to stop this macro from wrapping the entire result in an extra ()
?
(defprotocol MyProtocol (foo [x]))
(defmacro my-extend-helper [prot & extensions] (let [protocol (-> prot resolve deref)
m (-> protocol :sigs keys first)
params (-> protocol :sigs first last :arglists first)]
(for [[atype x] extensions]
`@(extend-protocol ~prot ~atype
(~m ~params ~x)))
))
(macroexpand '(my-extend-helper MyProtocol [clojure.lang.PersistentVector (first x)]))
=> ((clojure.core/extend-protocol MyProtocol clojure.lang.PersistentVector (:foo [x] (first x))))
@jeffrey.wayne.evans unquote-splicing
might be of help, if you haven't seen it: https://clojuredocs.org/clojure.core/unquote-splicing
yeah I was playing with that, but couldn’t quite get it. will refocus there again. thanks!
I was doing experiments with reducers and somethink caught my attention, the return of reducer functions doesn’t return a IPersistentCollection, so someone knows why? Example:
user=> (let [result (clojure.core.reducers/flatten [1 2 [3 4]])]
(println "is collection: " (coll? result))
(println "type: " (type result)))
is collection: false
type: clojure.core.reducers$folder$reify__5949
nil
And the docs of reducers/flatten states that it returns a foldable collection:
user=> (doc clojure.core.reducers/flatten)
-------------------------
clojure.core.reducers/flatten
([] [coll])
Takes any nested combination of sequential things (lists, vectors,
etc.) and returns their contents as a single, flat foldable
collection.
nil
a foldable collection, not a collection. i.e. folding/reducing it will produce a collection
you might want to peruse https://clojure.org/news/2012/05/08/reducers https://clojure.org/news/2012/05/15/anatomy-of-reducer
> a foldable collection, not a collection. i.e. folding/reducing it will produce a collection (edited) Yes, it’s clear right now, paying attention to foldable qualifier 😄
> you might want to peruse https://clojure.org/news/2012/05/08/reducers https://clojure.org/news/2012/05/15/anatomy-of-reducer Thank you @alexmiller, I’ll dig deep into this
hi, I'm trying to get started with some deps.edn stuff, I have a problem finding standard dependencies. In my ~/.m2/settings.xml I have just one repository set up which is authenticated for some work stuff. When I try to get a dep in my deps.edn it falls over with a timeout because the configured repo doesn't have the dependency. I've been using lein until now and it finds the dependency fine, I assume that's some hidden defaults so seems a reasonable reaction from deps. Question is, can I add some other repositories to look at into deps.edn, I tried with :mvn/repos which I was hopeful for but still seems to timeout looking in the wrong place.
{:paths ["src"]
:deps {org.clojure/clojure {:mvn/version "1.10.1"}}
:aliases {:test {:extra-paths ["test"]
:extra-deps {eftest {:mvn/version "0.5.9"}} ;tried with eftest/eftest as well
}}
;still no luck after adding these
;:mvn/repos {"central" {:url " "}
; "clojars" {:url " "}}
}
> clojure -M:test
Error building classpath. Failed to read artifact descriptor for eftest:eftest:jar:0.5.9
at ...
Caused by: org.eclipse.aether.resolution.ArtifactResolutionException: Could not transfer artifact eftest:eftest:pom:0.5.9 from/to central (): connect timed out
the "looking in the wrong place" is probably just a misleading error message - it searches all of the repos in order and will typically just report one of those errors (so that can look confusing, but it should be checking all of them)
where is https://my.private.repo/repository/maven-group coming from?
the central and clojars repos are included by default
clj -Sdeps '{:deps {eftest/eftest {:mvn/version "0.5.9"}}}'
worked for me - downloaded eftest from clojars
I think you've got something funky in your ~/.m2/settings.xml that is causing the problems
ahh interesting thanks, in ~/.m2/settings.xml I have something like:
<settings xmlns=""
xmlns:xsi=""
xsi:schemaLocation=" ">
<servers>
<server>
<id>x</id>
<username>y</username>
<password>z</password>
</server>
</servers>
<mirrors>
<mirror>
<id>x</id>
<url></url>
<mirrorOf>*</mirrorOf>
</mirror>
</mirrors>
</settings>
sorry I can't share it more fullyyeah, I think it's timing out accessing that mirror
I'll try and look into the xml side more @alexmiller though this was just requested by my work to be used
that makes sense, I was hoping I could override that in the deps.edn without changing my xml but I guess not
I suppose lein is just ignoring that setup
if that's a company nexus repo or something like that, you may need to do some other process to get it retrieved and loaded in your nexus
not uncommon to proxy all maven traffic through things like that
yeah, this was a little personal project I was doing on the side to try out deps, but might not work out
well thanks for the help, sounds like nothing wrong with deps at least!
mv ~/.m2/settings.xml ~/.m2/definitely-not-settings.xml
working great now 😂
Thanks again Alex
Hi there! Can someone explain to me why this is not working?
((resolve (symbol (str "Math" "/sqrt"))) 25)
The big reason is Math/sqrt is a java static method, which the compiler statically figures out
The / is also not part of the symbol name, it just distinguishes the namespace from the name when printing a symbol
The reason I am trying to do it is to create a macro to dynamically define routes the following way –
(ns arborist.handler
(:require [compojure.core :refer :all]
[compojure.route :as route]
[arborist.users :as users]
[ring.middleware.defaults :refer [wrap-defaults site-defaults]]))
;; TODO: map over collection of http verbs to generate routes and actions
;; with something like ((resolve (symbol "+")) 5)
(defmacro rest-resource [resource]
(context (str "/" resource) []
(GET "/" [] (users/index))
(POST "/" [] (users/create))
(GET "/:user-id" [user-id] (users/show user-id))
(PATCH "/:user-id" [user-id] (users/update user-id))
(DELETE "/:user-id" [user-id] (users/update user-id))))
(defn greet [name] (str "Hello, " name "!"))
(greet "Yury")
(defroutes app-routes
(GET "/" [] "Welcome to Arborist")
(GET "/request" request (str request))
(rest-resource "users")
(rest-resource "notes")
(route/not-found "Not Found"))
(def app
(wrap-defaults app-routes site-defaults))
Like, you aren't getting any errors trying to use it, but you have sort of fallen into a crevasse
You don't entirely understand how macros work and mixing up your compile time and runtime
I am coming from ruby and in rails it is very convenient to generate routes and the rest just from the resource name
I’ve tried to write it the following way –
(defmacro rest-resource [resource]
`(context (str "/" ~resource) []
(GET "/" [] (users/index))
(POST "/" [] (users/create))
(GET "/:user-id" [user-id] (users/show user-id))
(PATCH "/:user-id" [user-id] (users/update user-id))
(DELETE "/:user-id" [user-id] (users/update user-id))))
But it give me clojure.lang.Compiler$CompilerException Syntax error macroexpanding clojure.core/let at (arborist/handler.clj:24:3).
So, is there a way to resolve resource name in a place like this?
(GET "/" [] (users/index))
If I may suggest (and if you're not fixed to use only compojure) here's an example of using dynamic routes with reitit - another (also popular) routing library. I haven't used this myself (the dynamic routing), but the example seems quite straight-forward. There's also a comparison with compojure:
I started clojure just a few days ago, trying to learn by doing a something simple like todomvc
Sure! It's lots of fun. You'll learn lots! 🙂 I put together a simple example of reitit, some db tech and a few other bits and bobs here: https://git.sr.ht/~dharrigan/startrek/tree. It's a very small project. There's also a startrek-ui which is a nice javascripy frontend that also uses reitit and cljs.
I’ve tried to use resolve, but I am getting null ptr exception
(GET "/" [] ((resolve (symbol (str resource "/index")))))
I would really recommend spending some time with some clojure tutorial (not sure what would be best)
So, is there a way to make it work?
(GET "/" [] ((resolve (symbol (str resource "/index")))))
Returns a Symbol with the given namespace and name. Arity-1 works on strings, keywords, and vars.
Because now I see the following
;; Works
(GET "/" [] (users/index))
;; Not works
(GET "/" [] ((resolve (symbol (str resource "/index")))))
e.g. for resolving to actually look something up the definition has to have been loaded
It is strange a bit, because I am passing it to a method as a string
(rest-resource "users")
it could get screwed up in a lot of different wants, hard to say without more information
my guess would be you some how ended up in a mishmash state of the world after I suggested switching from a macro to a function
(str (str resource) "/index")
is, by the definition of the str
function identical to (str resource "/index")
but in changing one for the other you had to re-load the code which is likely what fixed things
it is very possible to end up in a state where things are broken in a clean known state but work after reloading
a very common way people get themselves in a very broken place is by forgetting that the repl accumulates state. each definition you send, you have to assume it depends on the state of the repl. which is a very different kind of dev cycle if you are used to running things from scratch everytime. there are some tools that try and do things to reset the repl to a known state, but it limited what they can do
so you have some other code somewhere (maybe a plugin or something) that is screwing with you
are you sure the server is calling your code at all? visiting '/' on the server gets what you'd expect?