I tried to query data from database with jdbc. The problem is some column is array type.
;get that particular column
(def jdbc-array (with-connection *db*
(with-query-results rs ["select * from refgene limit 5"]
(:exonstarts (first rs)))))
;Check if it has a value
(print jdbc-array)
;#<Jdbc4Array {67075873,67078739,67085754,67100417,67109640,67113051,67129424,67131499,67143471,67162932}>nil
;check class
(class jdbc-array)
;org.postgresql.jdbc4.Jdbc4Array
How to convert this array to seq/vector in clojure ? I tried (seq jdbc-array) and (seq (.getArray jdbc-array) but both doesn't work...
If the with-connection option seems clunky to you (it does to me), you can extend the IResultSetReadColumn protocol to convert Jdbc4Array objects into regular or vectors:
Here's one way to do that:
(extend-protocol clojure.java.jdbc/IResultSetReadColumn
org.postgresql.jdbc4.Jdbc4Array
(result-set-read-column [pgobj metadata i]
(vec (.getArray pgobj))))
this will convert all array types into vectors when reading
this approach can also help with the JSON datatype as in this example
Ok, I got it. I need to called getArray before clojure close the connection, or it'll give a nil.
Not sure why... My guess is clojure's laziness.
;work
(with-connection *db*
(with-query-results rs ["select * from refgene limit ?" 5]
(seq (.getArray (:exonends (first rs))))))
Related
can someone point me to how I can write this in syntax-parse/case?
[(list e ...) #`(list #,(f #'e) ...)]
basically I'd like each element in the list to be processed individually by f in unsyntax. I don't think the above is the right syntax?
You can use unsyntax-splicing (which can be abbreviated as #,#) to embed result of list returning expression as individual elements of outer list. Then you can use map procedure to apply f over all elements of list returned by (syntax->list #'(e ...)) expression. In the end it will look like this:
#`(list #,#(map f (syntax->list #'(e ...))))
I have c-string style array if_name defined:
(define-cstruct _ifreq ([ifr_name (_array _byte IFNAMSIZE)]
;; ommited ...
))
I can access individual elements by (array->ref) and through recursion create list from it. Then use (list->bytes) to get lisp data structure. I am curious if there is a simpler way without need for list creation.
Racket comes with mutable byte strings for just such an occasion!
(require ffi/unsafe)
(define (byte-array->bytes array)
(let* ([len (array-length array)]
[byte* (make-bytes len)])
(for ([i (in-range len)])
(bytes-set! byte* i (array-ref array i)))
byte*))
I'm trying to schedule a Clojure function using Executors.newSingleThreadScheduledExecutor(). The annoyance is that calling .get() on the resulting ScheduledFutureTask returns nil instead of the function's result.
I'm taking Mr Hickey's implementation of futures as the model.
(ns my.ns
(:import (java.util.concurrent Executors ThreadFactory TimeUnit)))
(def ^:private thread-pool-scheduler (atom nil))
(def ^:private thread-pool-counter (agent 0))
(defn- get-and-increment-thread-id []
(-> thread-pool-counter (send inc) deref))
(def ^:private thread-factory
(reify ThreadFactory
(newThread [this f]
(let [thread (Thread. f)]
(.setName thread (format "clojure-scheduled-future-thread-pool-%d"
(get-and-increment-thread-id)))
thread))))
(defn scheduled-future-call [^Callable f ^long delay ^TimeUnit unit]
(.schedule (scheduled-futures-executor) (bound-fn* f) delay unit))
(defn start-scheduled-futures-executor! []
(reset! thread-pool-scheduler
(Executors/newSingleThreadScheduledExecutor thread-factory)))
(defn scheduled-futures-executor []
(or #thread-pool-scheduler
(start-scheduled-futures-executor!)))
Everything works, and side-effects fire when appropriate (e.g. scheduling #(println "ok")).
However, calling the get() method of the resulting ScheduledFutureTask always gives me nil
(e.g. scheduling #(+ 5 5)).
I tried extending Callable explicitly, tried omitting bound-fn*, but the result is the same:
(defprotocol ISchedule
(schedule [this delay time-unit]))
(extend Callable
ISchedule
{:schedule (fn [this delay time-unit]
(.schedule (scheduled-futures-executor) this delay time-unit))})
My intuition is that the ScheduledExecutorService is choosing schedule(Runnable, long, TimeUnit) over schedule(Callable, long, TimeUnit), but shouldn't type hints fix that?
Many, many thanks for any help or tips!
My intuition is that the ScheduledExecutorService is choosing schedule(Runnable, long, TimeUnit) over schedule(Callable, long, TimeUnit),
I think you're right, only I reified Callable and it worked properly. (I also added Callable to the list of classes in the import statement).
EDIT: I also removed the call to bound-fn*
Check it out:
(defn make-callable [f] (reify Callable (call [this] (f))))
(def cat (make-callable (fn [] (println "meeow") "i am a cat")))
(def who-are-you? (scheduled-future-call cat 2 TimeUnit/SECONDS))
(println "Tell me who you are!\n\t" (.get who-are-you?))
outputs:
meeow
Tell me who you are!
i am a cat
The ^Callable hint on f does you no good, because you just call bound-fn anyway, whose result is not type-hinted. You need to hint the thing you actually pass to .schedule. More importantly, you need to hint the target object itself (the executor), as the compiler will (quite reasonably) ignore any hints on arguments if the target object is not hinted: it has to do reflection anyway if it doesn't know the type of the target!
So, hint both of those things in a let-binding1 and you should be fine. You might need to hint all the rest of the arguments as well for disambiguation, but I don't think so.
1 Note: do not hint the expressions generating them, eg ^Callable (bound-fn f). That usually works, but sometimes doesn't, in scenarios that are complicated to explain. Best to just avoid that scenario.
The macro, transform!, as defined below seems to work for => (transform! ["foo" 1 2 3]). The purpose is to take in a list, with the first element being a string that represents a function in the namespace. Then wrapping everything into swap!.
The problem is that transform! doesn't work for => (transform! coll), where (def coll ["foo" 1 2 3]). I am getting this mystery exception:
#<UnsupportedOperationException java.lang.UnsupportedOperationException: nth not supported on this type: Symbol>
The function:
(defmacro transform!
" Takes string input and update data with corresponding command function.
"
[[f & args]] ;; note double brackets
`(swap! *image* ~(ns-resolve *ns* (symbol f)) ~#args))
I find it strange that it works for one case and not the other.
Macros work at compile-time and operate on code, not on runtime data. In the case of (transform! coll), the macro is being passed a single, unevaluated argument: the symbol coll.
You don't actually need a macro; a regular function will suffice:
(defn transform! [[f & args]]
(apply swap! *image* (resolve (symbol f)) args)))
Resolving vars at runtime could be considered a code smell, so think about whether you really need to do it.
You're passing a symbol to the macro, namely coll. It will try to pull that symbol apart according to the destructuring statement [f & args], which won't be possible of course.
You can also use (resolve symbol) instead of (ns-resolve *ns* symbol).
I'm specifically trying to generate the boilerplate for crud functions to work with the Google App Engine datastore using appengine-magic in Clojure. I'm having difficulty working out how to generate values from a model that I've reproduced below.
(def *model* {:users [{:name "Adam"
:email "adam#gmail.com"
:registered-on "07-05-2011"}
{:name "Greg"
:email "gregory#gmail.com"
:registered-on "11-05-2011"}]
:post [{:title "A"
:authour "Adam"}
{:title "B"
:author "Greg"}]})
I'm fairly new to appengine-magic, but it provides a defentity which allows you to define entities that you can put into the datastore and save! which allows you to save predefined entities into the datastore.
These take the form of:
(ds/defentity Post [title author])
(ds/save! (Post. title author))
Now just to start with I've defined:
(defn list-entities [model]
"Takes a representation of the model and lists the entities in preparation for generating defentities"
(interleave (vec (map first (partition 1 (map (comp symbol capitalize #(str % ".") name) (keys model)))))
(map vec (map keys (map first (vals model))))))
Calling it with:
(list-entities *model*)
Outputs:
(Users. [:name :email :registered-on] Post. [:title :author])
Now I am having difficulty defining gen-entities which will take the output above and repeatedly call ds/defentities defining as many entities as my model requires.
(defmacro gen-entities [entity fields]
`(ds/defentity 'entity 'fields))
Additionally I am in no way certain that this is a reasonable way to go about solving this problem. I'm still very new to macros and probably making several mistakes. Any help/clarity would be appreciated.
NOTE:
That model I've realised is badly designed, the one below is a lot better:
(def *model* {:users [:name :email :registered-on]
:post [:title :author]})
However it is more complex in terms of writing a macro so I will leave it as is.
I think a macro is required, because defentity seems to define a type.
(defmacro gen-entities
[model]
`(do
~#(for [[entity-kw values] model]
(let [entity-sym (-> entity-kw name capitalize symbol)
fields (map (comp symbol name) (keys (first values)))]
`(ds/defentity ~entity-sym [~#fields])))))
You don't have to fiddle the keys and values from each other, just to put them together again with interleave. Mapping over a map will give you the key and the corresponding value in one go.
user=> (macroexpand-1 `(gen-entities ~model))
(do
(ds/defentity Users [name registered-on email])
(ds/defentity Post [title authour]))
Note: this won't work with the model stored in a Var. You'll have to specify the model in the call to gen-entities.
user=> (macroexpand-1 '(gen-entities model))
(
#<IllegalArgumentException java.lang.IllegalArgumentException: Don't know how to create ISeq from: clojure.lang.Symbol>