What is the best way to insert a snippet of code in spacemacs - elisp

I have a function which basically inserts function () {}; but properly indented and the cursor positioned appropriately:
(defun insert-function-js ()
(insert "function () {
};"))
(define-key evil-normal-state-map (kbd "SPC dg")
(lambda ()
(interactive)
(call-interactively 'evil-insert)
(insert-function-js)
(evil-force-normal-state)
(call-interactively 'evil-visual-char)
(call-interactively 'evil-previous-line)
(call-interactively 'indent-region)
(call-interactively 'evil-open-below)))
This seems very cumbersome. I would guess there is a better way to write this functionality! One that better leverages elisp's capabilities.
Thanks for the help!

As an answer to your first question, you could use yasnippet and a snippet based on the function-snippet provided with Spacemacs [1] to do this for you:
# -*- mode: snippet; require-final-newline: nil -*-
# name: my-function
# key: fn
# --
function () {
$0
};
If you put this snippet in a new file in ~/.emacs.d/private/snippets/, you can expand it by typing fn and then pressing M-/ [2]. If yas-indent-line is set to 'auto (which it is by default in Spacemacs), then the function should be indented correctly, and the $0 in the snippet puts your cursor in that position after insertion.
The yasnippet-expansion forms a single undo-action.
[1] The default function-snippet can be found in ~/.emacs.d/elpa/yasnippet-<VERSION>/snippets/js-mode
[2] using the default Spacemacs bindings, this calls hippie-expand, which in turn calls yas-expand.

Related

Caching api calls in clojure

I want to implement caching of api in clojure, In my application I have api's which are called for some of the functionalities. I want to reduce that api calls. I want to use clojure.core.cache.wrapped which is implemented upon clojure.core.cache. I want to cache my api call response base on the url.
The url is GET and has query inside the url that differentiates the response
for eg
http://localhost:3000/:clientid/get_data
Sample code
(:require [clojure-mauth-client.request :refer [get!]]
[clojure.core.cache.wrapped :as cw])
(def my-cache (cw/ttl-cache-factory {} :ttl 60000))
(defn get-data-caller [cid]
(cw/lookup-or-miss my-cache cid get-data))
(defn get-data [cid]
(let [req-url (str "/api/get-data?id=" cid)
response (retry-request (sign-credentials #(get! base-url req-url)) 3)]
(println response))))
I want to implement in a way that it caches depending on the cid.
In above code 3 is max-retries
With current implementation I am getting below error.
In my current code it is calling the api again and again
I got the solution, The main mistake I made here is that I implemented this in
get-data-caller
lookup-or-miss actually accepts 3 params
lookup-or-miss [cache key fn]
Here
1. cache is the one that we create.
2. key that we want to use as 'key' in our caching
3. The third has to be the function, that takes 'key' as an arg and gets data for us.
So lookup-or-miss will first check if the we have cached data for the 'key' passed, if not then, that will be passed as an arg to the third arg (i.e the fn) and get the fresh data.
If the cache data is not present for the key, then the fn in the third arg will be called with key as arg to get the data.
With above understanding I did rewrite my code as below
(:require [clojure-mauth-client.request :refer [get!]]
[clojure.core.cache.wrapped :as cw])
(def my-cache (cw/ttl-cache-factory {} :ttl 60000))
(defn http
[url]
(retry-request (sign-credentials #(get! url)) 3))
(defn get-data-caller [cid]
(get-data cid))
(defn get-data [cid]
(let [req-url (str "/api/get-data?id=" cid)
response (cw/lookup-or-miss my-cache req-url http-request)]
(println response))))
So here lookup-or-miss will search req-url key in my-cache, if present it will directly return the value stored, if not then it will call http-request with req-url as an arg
So lookup-or-miss will be executed something like this;
pseudo code for understanding
(if (contains? my-cache req-url)
(:req-url my-cache)
(http-request req-url))

Rebol2/View question: How does the layout function in Rebol2 work?

Some functions that are used in the 'layout function do apparently not exist, yet 'layout works fine. But when you try to replace the 'layout function by an adapted version containing some debugging statements, the functions and undeclared variables will immediately cause an error.
The functions BIND? and BOUND? don't show results for, for example, the used TRACK function, so there is no extra information by using those.
Special interest in the do-facets and grow-facets functions.
Here are two ways to create anonymous contexts in Rebol 2:
context [
semi-hidden-function: does [print "ok"]
set 'non-hidden-function does [semi-hidden-function]
]
use [semi-hidden-function] [
semi-hidden-function: does [print "ok"]
set 'non-hidden-function does [semi-hidden-function]
]
In the first form you may reach the context of the word semi-hidden-function:
>> probe bound? first body-of :non-hidden-function
make object! [
semi-hidden-function: func [][print "ok"]
]
But in second form you may not:
>> probe bound? first body-of :non-hidden-function
make object! [
]
I see many Rebolers use one of above forms, not only to hide but to keep the main function clean and separate.
Here I also add the functions you like to see, it is a bit long so I compressed & enbased:
You can simply paste below line to the console, copy the below text and execute the line to decompress it:
write clipboard:// decompress debase trim/lines read clip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AiQfNEi6z8eG6g1JwNF9qresf8To
yPZPkN4oKf8lhtZ7qNTP3pj/K7I47f5SmWRys/xrluJsoj7WiosH8Fqsci9zc/04t/UR8IWs3jhci
kegXdHppS/99cQO1HZ/7Efvs8aA7MPb81XdHpr/TBQCSuLNflcXiFIn35JTGO2mJYuIfgr2vmTZZ+
OXhiCQMpjojZ3hWJQ3aJCu5drDzZJRq0d4nsiCsL0N4niii+rI17X/4mYl/WxLr7C5ZY7idACQAA
You can find the definitions in the source files of the sdk
e.g
track: func [blk] [if verbose [print blk]]
in view-vid.r
Here a helper function to get the definition/source of a word/function in an unknown context and e.g. without access to the sdk
find-anon: func [ words fn /local ] [
foreach word words [
if word = fn [set :fn probe get word halt]
if block? word [
find-anon word fn
]
]
]
find-anon second :layout 'grow-facets
help grow-facets

dump command is showing empty brackets in pig

When I used the following command in the grunt shell:
B = FOREACH A GENERATE(category);
dump B;
The output was:
()
()
()
()
()
()
()
and so on.
Category is the string(char array) which I want to display using dump.
Add a "DESCRIBE B" to the end of the script.
The output appears to be 7 nulls, instead of an expected chararray or string. The DESCRIBE command will either verify that category is actually a string equal to "() () () () () () ()" or is using an unexpected schema.

Ajax GET with Reagent

I am doing an Ajax GET from my Reagent application, to load some stuff from the database.
I am not entirely sure what is the best way of getting the result of such ajax call to my page, considering that if I put it in an atom, then Reagent automatically re-renders a component when an atom is dereferenced, which means I get an infinite sequence of ajax calls.
For some code,
(def matches (atom nil))
(defn render-matches [ms]
(reset! matches (into [:ul] (map (fn [m] ^{:key m}[:li m])
(walk/keywordize-keys (t/read (t/reader :json) ms)))))
This function basically creates a [:ul [:li "Stuff here"] [:li "And here"]]
Which i would like displayed on my page, which now has the following code.
(defn standings-page []
(GET "/list-matches"
{:handler render-matches})
#matches)
I think it's better to save only data in an atom and to generate the HTML as part of the component logic.
Also it's better to trigger the AJAX call outside the render phase, for example, before the component will mount, or as the result of an event (on-click on a button for example).
Like this:
(def matches (atom nil))
(defn component []
(let [get-stuff (fn [] (GET "/..." :handler (fn [response]
(reset! matches (:body response))))]
(get-stuff) <-- called before component mount
(fn []
[:ul
(for [m match]
^{:key ...}
[:li ...])])))
This is called form-2 in this post.

Access the querystring in a Spiffy app

One shouldn't have to ask this here, but thanks to the bad documentation, how do I access the querystring in a Spiffy (egg) app? Thanks!
(use intarweb spiffy sxml-serializer)
(tcp-buffer-size 2048)
(server-port 80)
(handle-not-found (lambda (path)
; (print (request-uri (current-request)))
; (print (request-method (current-request)))
; (print (current-pathinfo (current-request)))
; (print (current-file))
; (print (remote-address))
(send-response
body: (serialize-sxml
`(div (# (class "page"))
(h1 ,path))
method: 'html))))
(start-server)
I'm not exactly sure why you want to access the query string, but the
URI objects in Spiffy come from the request object, as you've correctly
identified. The request object is from intarweb, which sticks an
uri-common object in the request-uri attribute.
You can access the constituent component parts using uri-common's
accessors, as documented in the URI-common egg reference
The query string is parsed into an alist for your convenience, and
accessible through (uri-query (request-uri (current-request))).
The "original" query string can be accessed a little more differently:
the uri-common egg is a convenience wrapper around the lower-level egg
uri-generic, which you can access by calling (uri->uri-generic URI),
where URI is (request-uri (current-request)), as before.
Then, you can access the query string through the uri-query procedure
from that egg. Here's a simple example you can use on the REPL:
#;1> (use uri-common (prefix uri-generic generic:))
#;2> (uri-reference "http://foo?x=y")
#<URI-common: scheme=http port=#f host="foo" path=() query=((x . "y")) fragment=#f>
#;3> (uri-query #2)
((x . "y"))
#;4> (uri->uri-generic #2)
#<<URI>>
#;5> (generic:uri-query #4)
"x=y"
What I did here is prefix all the procedures from uri-generic with
"generic:". This is necessary because uri-common "shadows" all the
procedures defined by uri-generic.

Resources