w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
  Home » CLOJURE » Page 1
Reading key with greatest number from set
The built in sorted-set-by function should do the trick: user> (apply sorted-set-by #(- (:uid %1) (:uid %2)) #{{:uid 2, :name "book2", :qty "2", :price "2"} {:uid 3, :name "book3", :price "1", :qty "1"} {:uid 1, :name "book4", :qty "2", :price "2"}}) #{{:uid 1, :name "book4", :qty "2", :price "2"} {:uid 2, :name "book2", :qty "2", :price "2"} {:uid 3, :name

Categories : Clojure

Mapping a list of datomic ids to entity maps
I used to take this approach to save queries to the DB, the code is probably less reusable but it depends on what is more critical in your current scenario. I haven't a Datomic instance configured as I am not working with it right now so it may contain syntax error but I hope you get the idea. (def query-result '[:find ?cat-name ?id :where [?cat-name :category/

Categories : Clojure

Why does (name ) return nil?
Silly mistake. In case others run into it: What I omitted above is that the function is part of a protocol extended on that particular record. That means that the symbol name inside the protocol method is shadowed by the name field of the record. Calling clojure.core/name instead of name solved the problem.

Categories : Clojure

Take-while and take-nth in clojure
not-nil? is the same as the built in function some? in clojure 1.6 The idiom is to use - in preference to _ in Clojure binding names. (partial get_message "my_queue") is better as #(get-message "my_queue") since you clearly have no intention of adding args (if (some? payload) (String. payload "UTF-8")) could be expressed as (some-> payload (String. "UTF-8")), though you may want to reserv

Categories : Clojure

How to build hash map of sets
(defn pairs-to-hash [pairs] (into {} (map (fn [kv] [(key kv) (->> kv val (map second) set)]) (group-by first pairs)))) (pairs-to-hash '([:a 2] [:b 3] [:a 1] [:b 3])) This was a quick attempt that I think could be neatened up a bit.

Categories : Clojure

Why this code does not throw StackOverflow exception
Because 1 is a long. The code starts computing extremely long rationals, and slows to a crawl after a few iterations. If you run it with 1.0 and 4 it blows the stack very quickly after a few thousand calls (may vary depending on your jvm parameters).

Categories : Clojure

/var/cache/debconf/config.dat-new: Permission denied
Answer provided by hugod, author of pallet. As of pallet 0.8.0-RC.11 when running on localhost the default script prefix is :no-sudo when the default would otherwise be :sudo. This is for historical reasons I don't know the details about. To change the script prefix back to sudo, wrap your action with (pallet.action/with-action-options {:script-prefix :sudo} YOUR-ACTION-HERE). So in my case it

Categories : Clojure

How to keep the map order in Clojure?
If your data won't change, you can use array-map: (def templates (array-map :list1 {} :list2 {} :list3 {})) (seq templates) ;; => ([:list1 {}] [:list2 {}] [:list3 {}]) (keys templates) ;; => (:list1 :list2 :list3) Why the constraint with constant data, you ask? Well, an array-map might turn into a hash-map after basically any modification operation (if its contents grow to

Categories : Clojure

Check if not nil in Clojure
identity https://clojuredocs.org/clojure.core/identity (identity x) Returns its argument.

Categories : Clojure

Leiningen, repl, uberjar: Unable to resolve symbol, No such var
Using def inside of a function is not idiomatic, especially if there is no reason to have it as a global variable. Just pass it as a function parameter: (let [parsed-args (parse-opts ...)] ... (build-album parsed-args)) If you really need global state, you can use e.g. a promise (alternatively, an atom): (defonce parsed-args (promise)) ... (deliver parsed-args (parse-opts ...)) However,

Categories : Clojure

Printing vector as a tree
You have to take care of when to start a new level of indentation, otherwise you'll start to map over leaves (and those are not something that can be mapped over): (defn print-tree ([tree] (apply str (map #(print-tree % "") tree))) ([tree prefix] (if (vector? tree) (->> (map #(print-tree % (str prefix "-")) tree) (apply str)) (str prefix tree " ")))) Example: (

Categories : Clojure

Using a Java class in the clojure repl
With the standard clojure repl, the class file needs to be available on the classpath used to start the repl. Here's an example java -cp pathToClojureclojure.jar;.src;.lib;.lib* clojure.main %1 I have the src included for clojure source, the lib folder included for class files, and lib* included for classes included in jar files. In this example, the Speak class can be included and used with:

Categories : Clojure

Very slow resource loading time with compojure route/resources and ring
I found the culprit of this huge performance loss. After a ton of debugging I found out that the only difference between project 1 and project 2 is the resources folder. Project 1 includes a entire frontend project. A lot of files through bower, scss, compiled css, compiled cljs and so on. Everything you need for good frontend development. In total 10506 files. Project 2 was a test project inc

Categories : Clojure

Clojure idiom for dynamic map creation
This uses cond-> to simplify things a little. (defn make-map [foo bar baz] (cond-> {} foo (assoc :foo foo) bar (assoc :bar bar) baz (assoc :baz baz))) It's hard to tell with the toy example whether there's a better option for you.

Categories : Clojure

Faking friend credential function using Midje
I'm still not sure why this is happening but I have a work around. If I replace my credential-fn with: (defn another-fn [] (println (str "hey look I got called")) (throw (Exception.))) (defn cred-fn [creds] (another-fn)) And then create a fake for the new function in the test, like this: (fact "login with incorrect username and password returns unauthenticated" (:status (post "/lo

Categories : Clojure

What is the idiomatic way of waiting for a Clojure async channel?
This is a very common approach, so to answer your first question I'd say yes. There are a few conveniences offered by core.async that could make it a bit more idomatic (though it's really fine the way it is): use go-loop in preference to (go (while true ...)) or (go (loop ...)) use alt! in preference to (let [[result channel]] (alts! ...))

Categories : Clojure

Filter elements not matching on a key between two lists in clojure
(defn mismatch? "Returns true if there is any mismatch between corresponding items." [a b] (= (count (clojure.set/union (set a) (set b))) (max (count a) (count b)))) If you want a specific name, you could use list comprehension: (defn get-mismatched-emails "Returns the name of any superheroes with inconsistent contact records." [a b] (for [i a j b :when (and (= (:name i

Categories : Clojure

Difference between keep-indexed and map-indexed?
Keep-indexed will keep the result of fn if result is not nil (keep-indexed #(if (odd? %1) %2) [:a :b :c :d :e]) ;;(:b :d) map-index will keep all result of applying fn to coll regardless return value is nil or not (map-indexed #(if (odd? %1) %2) [:a :b :c :d :e]) ;; (nil :b nil :d nil)

Categories : Clojure

How to make sure the input is a number?
Are you sure that it isn't working? (defn numbers-only [n] {:pre [(number? n)]} (println "Yay!")) (numbers-only "clojure") AssertionError Assert failed: (number? n) (numbers-only 27) Yay! Maybe you are mistyping the name of the param in the pre condition?

Categories : Clojure

Clojure commute and alter performance
I used VisualVM to monitor the clojure.core functions involved when running the example using both alter and commute. alter commute If my interpretation of the results are correct, the accumulated time spent on each function shows that commute is actually faster than alter. It seems the overhead of all the other operations that need to be done to run the code in parallel are the ones that m

Categories : Clojure

clojure / lisp dialect etc function result expression
This is valid Clojure. Of a sequence of expressions/forms , the function returns the value of the last. Any others only have side-effects, such as (println ...) above. A function body has an implicit do to bring this about.

Categories : Clojure

Performance counter for Clojure (using core.async)
Have you considered ztellman's Narrator. It's a package for "analyzing and aggregating streams of data" There's plenty of examples, including one for the rate of messages over a period. I haven't actually used it, just remembered reading its docs and it having this kind of aggregation build in.

Categories : Clojure

How to create a map from a list of key-value pairs using values as a predicate in Clojure?
Into tends to be most useful when you just need to take a seq of values and with no additional transformation construct a result from it using only conj. Anything else where you are performing construction tends to be better suited by preprocessing such as sorting, or by a reduction which allows you to perform accumulator introspection such as you want here. First of all we have to be able to com

Categories : Clojure

Conditional threading through expressions
Okay. Well you have a data dependency between the function results and your predicates, so the "nicest" thing I came up using only clojure.core is to compose as-> and cond-> (as-> initValue data (cond-> data (test1 data) (f1 data)) (cond-> data (test2 data) (f2 data))) Another approach would be my own update-when helper... (defn ->when-update "Function of a valu

Categories : Clojure

Compojure Not Serving CSS When I Use Multiple Parameters
Finally I solved this issue after replacing <link rel="stylesheet" href="css/main.css"> to <link rel="stylesheet" href="/css/main.css">. What a trivial problem and I didn't notice it for a day. Lol so embarrasing.

Categories : Clojure

Handling websocket client messages with aleph
in This example the author uses recieve-all and siphon from aleph to accomplish a very similar task which I'll roughly paraphrase as: (let [chat (named-channel room (receive-all ch #(println "message: " %)))] (siphon chat ch)

Categories : Clojure

How to create a map dynamic in clojure?
Here is one way to go about it: (fn [cond1 cond2] (into {:a 1} (map (fn [[c e]] (when c e)) [[cond1 [:b 2]] [cond2 [:c 3]]]))) You would probably want to pass in a table of conditions tied to entry pairs.

Categories : Clojure

Clojure core.async and Lamina
core.async and Lamina are two different projects and they aren't intended to replace each other. Actually, they could play nicely together -if you want to-. Lamina is a stream oriented approach, while core.async is message oriented. Which one to use is up to you. In Lamina, the important thing is the callbacks you define for the channel, while in core.async, channels and go blocks are decouple

Categories : Clojure

How to access tables in other schema in korma?
You should be able to do this by defining another db. I can create a db like this: CREATE database my_db; USE my_db; CREATE TABLE stuff ( things VARCHAR(255) ); INSERT INTO stuff (things) VALUES ("some things"); Now I define two Korma databases and entities, and query them: (defdb my-db (mysql {:host "localhost" :port 3306 :db "my_db"

Categories : Clojure

Clojure, file to byte array?
The most succinct method is just to use the byte-streams library, in which you'd simply call (byte-streams/to-byte-array (java.io.File. "path")). If you want to do it without an external library, it would be something like: (let [f (java.io.File. "path") ary (byte-array (.length f)) is (java.io.FileInputStream. f)] (.read is ary) (.close is) ary)

Categories : Clojure

Run script as specified user
Not sure, what your example shows and what the question is ... Why do you try to create an user from your pallet-user (I talk about "(actions/user (:username user-pallet))" )? Pls. remove to make your Question more clear. Does the pallet-user exist on your localhost? Is it sudo able? What show's the console output? With console output I mean sth. like 20:57:56.305 [operate-57] DEBUG pallet.ss

Categories : Clojure

Clojure: (:refer-clojure :exclude [read]) apparently not working
It doesn't seem like the ns'es you are using match your file names. I'm not sure if that's just sloppy examples or if that's actually the issue. Usually when you split a namespace across files, the loaded files should start with (in-ns 'foo.core), not (ns foo.core). clojure.pprint is a good example in core (it loads a bunch of sub files). A fuller example: foo/core.clj: (ns foo.core (:refer-

Categories : Clojure

How do I get the longest continuous sequence in a matrix which fulfills a criterion?
(def m "ABBAAAC") (->> m (map-indexed vector) (partition-by #(-> % second identity)) (sort-by count >) (first)) Gives: ([3 A] [4 A] [5 A])

Categories : Clojure

Composing a small list with elements among some candidate elements, where the inclusion of each element depends on an independent predicate?
This would do what you want: (defn f [conds vs] (when (seq vs) (let [[c1 & cr] conds [v1 & vr] vs] (if c1 (cons v1 (f cr vr)) (f cr vr))))) Example: (f [false true true false] [1 2 3 4]) => (2 3) (f [true true false true false true] [1 2 3 nil 4 5]) => (1 2 nil 5)

Categories : Clojure

in clojure why isn't x identified if defined as [x] argument and then referenced as x? in code block?
I am not sure what is your problem (you didn't ever defined x?) but you could implement it in Clojure like this (defn boolean [x] (not (or (nil? x) (false? x)))) (boolean 1) #=> true (boolean nil) #=> false (boolean false) #=> false (boolean []) #=> true Or more implicit solution (defn boolean [x] (if x true false)) Or your approach: (defn boolean

Categories : Clojure

clojure when-let alternative for an empty array?
seq returns nil on an empty input sequence so you could do: (when-let [batches (seq (map #(array-map :id %) generated-uuids))] {:generatedBatches batches}))}}})

Categories : Clojure

ClassCastException java.lang.Long cannot be cast to clojure.lang.IFn
You need to remove the brackets from around salary in your if condition: (if (= years 0) salary (calculate-salary (- years 1) (* salary 2)) the form (f arg1 arg2 ..) attempts to call f as a function with arg1, arg2 ... as arguments. Therefore (salary) attempts to invoke salary (a long) as a function with no arguments, hence the error.

Categories : Clojure

defrecord Class Not Found Exception
:import references a Java class - and when creating package/class names for those the Clojure compiler converts dashes to underscores. This might thus work: (:import [discrete_optimization.knapsack Item])

Categories : Clojure

Leiningen checkouts when library has a slash in its name
The only thing lein expects in the directory directly underneath checkouts is a project.clj file. The organization namespace is inferred from that project file, and has nothing to do with the directory structure above the symlink. In your flambo project file, make sure you have (defproject yieldbot/flambo "version" ... correctly. Then in your checkouts of your spark-streaming project, create a sy

Categories : Clojure




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.