This page is not created by, affiliated with, or supported by Slack Technologies, Inc.
2017-02-23
Channels
- # aws-lambda (1)
- # beginners (11)
- # boot (456)
- # cider (3)
- # cljsrn (7)
- # clojure (340)
- # clojure-berlin (6)
- # clojure-dev (207)
- # clojure-germany (12)
- # clojure-greece (3)
- # clojure-italy (3)
- # clojure-russia (12)
- # clojure-spec (42)
- # clojure-uk (29)
- # clojured (7)
- # clojurescript (125)
- # datascript (1)
- # datomic (47)
- # defnpodcast (4)
- # emacs (30)
- # events (7)
- # hoplon (13)
- # instaparse (64)
- # jobs (13)
- # jobs-discuss (1)
- # lein-figwheel (1)
- # leiningen (10)
- # luminus (1)
- # lumo (14)
- # off-topic (10)
- # om (16)
- # om-next (3)
- # onyx (1)
- # pedestal (3)
- # protorepl (5)
- # re-frame (17)
- # reagent (66)
- # ring (1)
- # ring-swagger (13)
- # spacemacs (12)
- # specter (4)
- # untangled (272)
- # vim (4)
- # yada (24)
@shader you won't be able to just do to-date/from-date, as that will mean when it deserializes a util.Date it wouldn't know whether it's a util.Date or joda date. but anyway I think you just need to extend Freezable2 https://github.com/ptaoussanis/nippy/blob/master/src/taoensso/nippy.clj#L316
and add something to custom-readers https://github.com/ptaoussanis/nippy/blob/master/src/taoensso/nippy.clj#L253 🙂
the macros extend-freeze
and extend-thaw
(https://github.com/ptaoussanis/nippy/blob/master/src/taoensso/nippy.clj#L1413) would be better than directly extending Freezable2
I understand
(let [{:keys [a b]} ...])
however, what does
(let [{:keys [foo/a foo/b]} ...]}
mean ?It binds the name a
to the value at the key :foo/a
, and likewise for b
.
So, like, the map you'd be destructuring should look something like this: {:foo/a 1, :foo/b 2}
.
Right.
Little more explanations https://clojure.org/guides/destructuring#_namespaced_keywords
can someone explain please what does wrong during this back and forth number conversion?
(let [n 9007199254740995
converted-back-and-forth (long (bigdec n))]
(- converted-back-and-forth n))
=> 1
it's nowhere near Long/MAX_VALUE
and BigDecimal is supposed to be arbitrary precision... 😕
static public long longCast(Object x){
if(x instanceof Integer || x instanceof Long)
return ((Number) x).longValue();
else if (x instanceof BigInt)
{
BigInt bi = (BigInt) x;
if(bi.bipart == null)
return bi.lpart;
else
throw new IllegalArgumentException("Value out of range for long: " + x);
}
else if (x instanceof BigInteger)
{
BigInteger bi = (BigInteger) x;
if(bi.bitLength() < 64)
return bi.longValue();
else
throw new IllegalArgumentException("Value out of range for long: " + x);
}
else if (x instanceof Byte || x instanceof Short)
return ((Number) x).longValue();
else if (x instanceof Ratio)
return longCast(((Ratio)x).bigIntegerValue());
else if (x instanceof Character)
return longCast(((Character) x).charValue());
else
return longCast(((Number)x).doubleValue());
}
ah, good point, i should have just looked up the definition of long
sorry for the noise
(let [n 9007199254740995
converted-back-and-forth (.longValue (bigdec n))]
(- converted-back-and-forth n))
=> 0
if you need it, .longValue
@onetomactually my problem arose because i was just using clojure.core//
on a BigDecimal,
but i should just drop down BigDecimal methods and use .divideToIntegralValue
...
onetom: would +'
work for you?
And friends?
im still mapping out the possibilities, and i just saw it yesterday that there are these *'
variants.
but for now this worked:
(let [units-to-buy (-> (.divideToIntegralValue wallet price) (.longValueExact))] ...)
btw, this whole issue was surface by generative testing, so im very happy that i invested into learning clojure.spec
How could I read a file and exit with true when a defined string is found?
(defn file-includes?
[filename substring]
(with-open [buf (BufferedReader. (FileReader. filename))]
(if (some #(clojure.string/includes? % substring) (line-seq buf))
true
false)))
there are other ways like slurp
but this will buffer, so you can use on larger files if desired. also, this is one line at a time and does not let you look for multi-line substrings, but this can be done too of course, just not with line-seq
@joshjones thank you
I have to access java objects, but want to write a macro to make it more convenient. But now I struggle with the quoting of the object name. How could I rewrite a JavaClass.object
to (JavaClass/Object)
so the object name could be passed as variable?
@danielgrosse As a variable, then your only chance is reflection which is super slow. But a macro, yes then you could write (inv-java System.currenttimeMilis)
.
(defmacro inv-java! [x]
(let [[c m] (str/split (str x) #"[.]")]
(list (symbol (str c '/ (symbol m))))))
(inv-java! System.currentTimeMillis)
Btw, I read the question a bit differently, so for interests sake, this is what I did (btw it supports class names with dot notation)..
`(alias 'str 'clojure.string) (defmacro java[obj] (let [t (str/split (str obj) #"[.]")] (read-string (str (str/join "." (butlast t)) "/" (last t))))) (macroexpand '(java Java.lang.Math.abs)) (java Java.lang.Math.abs)`
Just to make it clear: I think all this is actually a terrible idea. 🙂 Good editors will understand (Xyz/zyx)
and provide proper help/hints/arity-checks.
Thank you both. Maybe I wrote the question in a wrong way. I try to achieve something like literal notation in javascript. So I could do something like
(defmacro get-object
[objectname]
(Javaclass/~objectname)
)
Currently I made a map where I associate the Object to a keyname.
because the impedance of the document structure matches the forms in clojure very well
' (mc/insert-batch db "documents" [{ :first_name "John" :last_name "Lennon" } { :first_name "Paul" :last_name "McCartney" }])'
As with everything, it depends on your use case but I also think mongo is very good, specially for prototyping or smaller projects. You rarely need to think about performance and since every clojure datastructure can be serialized you can really just focus on building features.
;; returns documents with year field value of 1998, as Clojure maps (mc/find-maps db "documents" { :year 1998 })
@scknkkrer I prefer for Datomic
(with-collection db "movies" (find { :year { $lt 2010 $gte 2000 } :revenue { $gt 20000000 } }) (fields [ :year :title :producer :cast :budget :revenue ]) ;; note the use of sorted maps with sort (sort (sorted-map :revenue -1)) (skip 10) (limit 20) (hint "year-by-year-revenue-idx") (snapshot))
@scknkkrer I would not depend on the programming language when deciding for a database. These are two different things. When looking for a DB you might want to consider other stuff, like read / write performance, scalability, costs, support, do you need a key / value store, etc..
and mongo is fairly good in most languages anyway, because most languages are not set based constructs
With all these criterias, I am looking for idiomatic technology for clojure. Any cassandra user ?
With datomic made by Rich Hickey I would also say that datomic is a natural choice. However, its not an open source license, except the free version.
@scknkkrer there are quite a few c* users, and we have quite decent bindings for c* as well: shameless plug > https://github.com/mpenet/alia
Super easy. Normally not a fan of clojure-DSL to represent SQL queries, but in case of C* it makes a lot of sense since the SQL dialect is so minimalistic. So I'm using hayt DSL with it.
then again if you hesitate between mongo, datomic and c*, maybe you need to have a clear idea of what are you requirements, these are all quite different in many ways
Or at a minimum have a hook to capture time of the first byte received and last byte received.
@mpenet, so, Is cassandra good choice for long-time ? I heard a bit of cassandra. And I looked a little bit.
Yes, nothing is a silver bullet. That said, another team in our company is quite entrenched in cassandra, and it's a big system.
if you don't need clustering, dealing with large volumes of data (or writes), maybe something else would fit better
and mongo is a bit hybrid , so if you don't need the extra expressiveness of the queries, and hte sharding (which C* is better at anyway), then it's also not the best
Yea, but early in project, I need implementation simplicity. Late in project, we will have really large datas...
c* is cassandra
I’m getting the following error: Caused by java.lang.UnsupportedOperationException Can't type hint a primitive local when I try to use the try+ and throw+ macros provided by the library
Anybody familiar with JDBC for MS SQL? Can't seem to get windows authentication working - copied ntlmauth.dll to my java library path as requested, and it still complains with "SSO Failed: Native SSPI library not loaded. Check the java.library.path"
they mention writing out the java.library.path
and just confirm it is what you think it is
still nothing. one thing is that the first answer says I should place 32 bit version in program files (x86) and the 64 bit in program files. but I dont have a 64 bit java folder under Program Files
and I checked hte library path, found that C:\Program files (x86)\ is in there.. tried that, nothing
dll might not load if the dlls that it depends upon cannot load. Its sometimes helpful to run depends.exe to analyse dll dependencies, and tell you what’s missing
I made the above macro that wraps defmethod, it works fine in the repl during development but when running my program with lein run or running the jar I get"No method in multimethod 'execute'" for the tasks I defined
I should mention that the deftask calls are made in different namespaces, and they are required in the core namespace
it seems like it is not related to the macro but rather the fact that the defmethods are not in the same namespace since it doesn't work either when I use the result of the macro-expension directly
i want to subclass a java class to customize one of its methods, whats the easiest way to do this from clojure?
hi I'm using clj-http.client
and cljs-http.client
and getting 403 (Forbidden) error in server when using the methods PUT and POST
@chrisblom have you tried reify
? https://clojuredocs.org/clojure.core/reify
@tomaas Hm, in general? I think that is very good to be found by google. In case you use luminus here are the docs about it: http://www.luminusweb.net/docs/security.md#cross_site_request_forgery_protection
Its just a guess that this might be the problem as GET requests dont expect a CSRF token, but POST / PUT / ... do
@dpsutton that not really what i'm looking for, i need a subclass of ReentrantLock, as other parts of my code expect a ReentrantLock or a subclass
@chrisblom I think you don't need to write this
in the parameter vector for lock and unlock
id like to do the following:
(s/defschema Benefit
{:cpf s/Str
:nomeSegurado s/Str
:emailSegurado s/Str
:atendimentoId s/Str
:referenciaId s/Int
:clausula s/Str
:dataInicioBeneficio s/Str
:dataFimBeneficio s/Str
:motivo s/Str})
(defn my-function [^String bla ^Benefit foo] ...)
since you don't have an actual underlying type you won't prevent this, so you get nothing out of the annotation
id like to anotate with something, and the compiler complains of this code .. maybe i should try to integrate compojure with spec instead of prismatic
if you want programmatic guarantees, use spec and if you want hints to the programmer use the doc string
apparently using the :require [ns1 [subns1 [a] [b] [c]]] for in the ns declaration was my problem for the multimethods not being present at runtime
but i doubt an end consumer would ever look in the meta of your function for usage hints
speaking of type hints, does anyone know how to generate an anonymous fn
form with a type-hinted return value?
I've figured out from the docs that you can add type hints to params by putting {:tag type}
metadata on the param symbols, but not sure what to do about return types
docs (https://clojure.org/reference/java_interop#typehints) say to put a ^type
tag before the arg vector...
Hi all, is there a way to do deep clone of hash ?
the functions that will take this are java methods, so I guess they're "type-hinting" by default
my understanding is that type hinting does less than you think, so check if you are getting reflection warnings in the first place
then my understanding (and i could be wrong) is that type hinting will gain you nothing
sorry, not very familiar with java's type system or strongly typed languages in general
alex miller corrects a lot of misunderstandings of type hinting a lot so i've picked up a few things from him
@dpsutton a type hint on the return value makes it so that consumers of your function don't have to type hint it every time
also if it's a primitive type hint, it will optimize the emitted code to potentially avoid extra boxing
this is the context, in case anyone's curious:
(defn- method->fn
"Takes a method and returns a type hinted anonymous `fn` form that
calls the method."
[{:keys [parameter-types declaring-class name]
:as method}]
(let [params (-> parameter-types
count
(repeatedly gensym))
params-with-types (map (fn [param type]
(with-meta param {:tag type}))
params
parameter-types)
obj `obj#
obj-with-type (with-meta obj {:tag declaring-class})]
`(fn [~obj-with-type [email protected]]
(. ~obj ~name [email protected]))))
is type hinting the return value still useless if the anonymous function is stored as a constant?
using (def x (fn ^Foo [] (Foo.)))
rather than (defn x ^Foo [] (Foo.))
will make the return type hint useless
I lied before by saying that return type hints on anon functions are useless -- what I meant is, they don't get propagated outside the fn
so in your last example, that type hint acts as a cast for the return value of that function
So the type hint will still properly work for the function itself. Wrt, the compiler avoiding reflection for that anonymous function, right?
so, if you had
public class Foo { public void a (long x) { System.out.println("1");} public void a (Object x) {System.out.println("2")}}
I agree, type hinting with primitives took me a while to get right. I wish there was more documentation about it. Cause me nice bug.
Also, if I run:
(binding [*print-meta* true]
(pr-str
(macroexpand-1
'(defn xy ^String [x] x))))
anyone know if you can (or even should be) redefining with-refdefs
a java method like java.utils.UUID/randomUUID
?
I’m working with a web app (via luminus). I’m currently trying to apply access rules via the buddy-auth warp-access-rules
middleware. Though it seems my changes only take place when I restart my server. Is this expected?
@mruzekw if you take a look at https://github.com/funcool/buddy-auth/blob/master/src/buddy/auth/accessrules.clj#L320 you can see that it compiles your rules and then returns an anonymous function that is actually being used as the middleware, that means that any changes you make to your access rules won't take effect until they've been recompiled and your server has the new function handed in as a middleware
Thanks @tanzoniteblack I looked around but wasn’t able to make full sense of the code yet.
so yes, that's expected. You should be able to work around this though if you do something like (def my-access-rules (wrap-access-rules <rules>))
and then use the symbol my-access-rules
in your middleware
that should cause your rules to take effect whenever you redefine my-access-rules
but that might depend on which http server you're using 😄
don't actually know the subtleties of how immutant works well enough to tell you if that should or shouldn't work, but I'd be interested to hear back what you find
While (subseq sc >= s <= e) returns a lazy seq, (subseq sc >= s) does not - returns a PersistentTreeMap$Seq. Does anyone know if the latter behaves similar to lazy seq? That is, does it walk the tree step by step as asked for values or does it just make the whole thing up front?? Thanks
apologies if this is the wrong place to ask - is there a recommended clojure postgresql package?
@joshjones: I do, but I wouldn't be unbiased :) What's up?
I'm just trying to figure out how to read the :body
of a POST request. The body in the request is:
#object[io.undertow.io.UndertowInputStream 0x46598eaa "[email protected]"],
@piotr2b what do you mean by multi-tails? are you saying you cannot have more than one tail position in clojurescript? because that is not correct
Do I really need to directly use the read
methods, etc., in this UndertowInputStream
class? Or is there a more straightforward way to do it? @tcrawley -- further, I see that the stream is closed, so I don't know how to get the data
your algorithm is not tail recursive, so recur won't work, has nothing to do with clojurescript
@joshjones what type of data is the body? if it's a string, you can just (slurp (:body request))
@tcrawley thanks so much, that did it -- geez louise, I did not notice that it extends java.io.InputStream... derp! 🙂
also, is tail recursion optimization beneficial outside of strict evaluation? if this is a lazy structure, does it matter if its tail recursive or not?
@dpsutton good point -- seems that it can just be constructed with the current lazy-seq / cons pattern of constructing a lazy seq
(actually the second code doesn’t work, there is an infinite loop in it)
@catilac I'm currently working on a project that uses a postgresql database and I'm using clojure.java.jdbc and also com.layerware/hugsql
geek-draven: good to know! have you had any issues with jdbc? i'm trying to bring clojure into this company 🙂
I've not had any problems with it, I even used it to connect to a Redshift database on AWS
Good luck introducing it to your company, we've been using it for 2 years and have deployed nearly 40 back end applications in that time 🙂
no worries, our entire data pipeline is built in Clojure, and this is the first programming language I've learnt 😀
no, I've just been using plain old json files
@piotr2b would recommend to take a look at https://clojure.org/reference/lazy#_recipe_how_to_write_lazy_sequence_functions_in_new_model , see if it might fit your use case
Actually my question is whether this can be rewritten with tail recursion
Oops, I’m sorry about the mistake in docstring. Could you elaborate on this?
but i think we were thinking tail recursion and lazy are kinda at odds with one another
constructing a lazy sequence (that is really lazy) and recur are mutually exclusive things
@joshjones thanks for your links, I gonna read it
ok thanks for referencing this ticket @hiredman.
I’m starting a referral program for introducing new Clojure and other “Functional” Engineering Professionals for new gigs. Working with several customers hiring. Anyone interested in learning more, send me a message.
hi all, actually I also have a project with Clojure (Datomic+Cassandra as well) if anybody in the EU and interested msg me
#jobs is more appropriate for job announcements
i basically want to walk through a datastucture and perform an update on the first element that meets a predicate while leaving all the other elements alone
@yedi have you looked at https://github.com/nathanmarz/specter ?
ooo specter looks promising, i might try that. though ideally i wouldn't have to pull in another lib