IntelliJ/Cursive unexpected issue - intellij-idea

Sometimes I try to run a Clojure program in IntelliJ and I get the following error:
(.deleteOnExit (java.io.File. "/home/matan.bl/.IdeaIC15/system/tmp/form-init7886362698780123516.clj"))
(do (set! *warn-on-reflection* nil)
(set! *warn-on-reflection* nil)
nil
(clojure.core/doseq [namespace1387 (quote
(sparkling.serialization
sparkling.destructuring))]
(clojure.core/binding [clojure.core/*out* clojure.core/*err*]
(clojure.core/println "Compiling" namespace1387))
(try
(clojure.core/compile namespace1387)
(catch java.lang.Throwable
t__8048__auto__ (clojure.core/binding [clojure.core/*out*
clojure.core/*err*]
(clojure.core/println (.getMessage
t__8048__auto__)))
(throw t__8048__auto__))))
(do nil
(try
(clojure.core/require
(quote clojure.tools.nrepl.server))
(catch
java.lang.Throwable t__11819__auto__
(clojure.core/println "Error loading"
(clojure.core/str (quote clojure.tools.nrepl.server) ":")
(clojure.core/or (.getMessage t__11819__auto__)
(clojure.core/type
t__11819__auto__)))))
(try (clojure.core/require (quote complete.core))
(catch java.lang.Throwable t__11819__auto__
(clojure.core/println "Error loading"
(clojure.core/str
(quote
complete.core) ":")
(clojure.core/or (.getMessage t__11819__auto__)
(clojure.core/type t__11819__auto__)))))
nil)
(clojure.core/let
[server__11814__auto__ (clojure.tools.nrepl.server/start-server
:bind
"127.0.0.1" :port 0 :ack-port 42520 :handler
(clojure.tools.nrepl.server/default-handler))
port__11815__auto__ (:port server__11814__auto__)
repl-port-file__11816__auto__ (clojure.core/apply clojure.java.io/file
["/home/matan.bl/projects/af_sparkling-river"
".nrepl-port"])
legacy-repl-port__11817__auto__ (if (.exists (clojure.java.io/file
"/home/matan.bl/projects/af_sparkling- river/target"))
(clojure.java.io/file
"/home/matan.bl/projects/af_sparkling-river/target" "repl-port"))]
(clojure.core/when true
(clojure.core/println
"nREPL server started on port"
port__11815__auto__
"on host"
"127.0.0.1"
(clojure.core/str "- nrepl://" "127.0.0.1" ":" port__11815__auto__)))
(clojure.core/spit
(clojure.core/doto repl-port-file__11816__auto__ .deleteOnExit)
port__11815__auto__)
(clojure.core/when
legacy-repl-port__11817__auto__
(clojure.core/spit (clojure.core/doto
legacy-repl-port__11817__auto__
.deleteOnExit)
port__11815__auto__))
(clojure.core/deref (clojure.core/promise))))
Do you have any idea what this error means and how it can be solved?

I have seen errors like this when typing
(-main ....)
into the REPL in Cursive-clojure without first clicking
on the switch repl to namespace button. Also make sure you have clocked "load file" in the same menu.

Related

How does read-line work in Lisp when reaching eof?

Context:
I have a text file called fr.txt with 3 columns of text in it:
65 A #\A
97 a #\a
192 À #\latin_capital_letter_a_with_grave
224 à #\latin_small_letter_a_with_grave
etc...
I want to create a function to read the first (and eventually the third one too) column and write it into another text file called alphabet_code.txt.
So far I have this function:
(defun alphabets()
(setq source (open "fr.txt" :direction :input :if-does-not-exist :error))
(setq code (open "alphabet_code.txt" :direction :output :if-does-not-exist :create :if-exists :supersede))
(loop
(setq ligne (read-line source nil nil))
(cond
((equal ligne nil) (return))
(t (print (read-from-string ligne) code))
)
)
(close code)
(close source)
)
My problems:
I don't really understand how the parameters of read-line function. I have read this doc, but it's still very obscure to me. If someone would have very simple examples, that would help.
With the current code, I get this error: *** - read: input stream #<input string-input-stream> has reached its end even if I change the nil nil in (read-line source nil nil) to other values.
Thanks for your time!
Your questions
read-line optional arguments
read-line accepts 3 optional arguments:
eof-error-p: what to do on EOF (default: error)
eof-value: what to return instead of the error when you see EOF
recursive-p: are you calling it from your print-object method (forget about this for now)
E.g., when the stream is at EOF,
(read-line stream) will signal the end-of-file error
(read-line stream nil) will return nil
(read-line stream nil 42) will return 42.
Note that (read-line stream nil) is the same as (read-line stream nil nil) but people usually still pass the second optional argument explicitly.
eof-value of nil is fine for read-line because nil is not a string and read-line only returns strings.
Note also that in case of read the second optional argument is, traditionally, the stream itself: (read stream nil stream). It's quite convenient.
Error
You are getting the error from read-from-string, not read-line, because, apparently, you have an empty line in your file.
I know that because the error mentions string-input-stream, not file-stream.
Your code
Your code is correct functionally, but very wrong stylistically.
You should use with-open-file whenever possible.
You should not use print in code, it's a weird legacy function mostly for interactive use.
You can't create local variables with setq - use let or other equivalent forms (in this case, you never need let! :-)
Here is how I would re-write your function:
(defun alphabets (input-file output-file)
(with-open-stream (source input-file)
(with-open-stream (code output-file :direction :output :if-exists :supersede)
(loop for line = (read-line source nil nil)
as num = (parse-integer line :junk-allowed t)
while line do
(when num
(write num :stream code)
(write-char #\Newline code))))))
(alphabets "fr.txt" "alphabet_code.txt")
See the docs:
loop: for/as, while, do
write, write-char
parse-integer
Alternatively, instead of (when num ...) I could have use the corresponding loop conditional.
Also, instead of write+write-char I could have written (format code "~D~%" num).
Note that I do not pass those of your with-open-stream arguments that are identical to the defaults.
The defaults are set in stone, and the less code you have to write and your user has to read, the less is the chance of an error.

emacs sql mode could not save history

below is my settings:
(defun my-sql-save-history-hook ()
(let ((lval 'sql-input-ring-file-name)
(rval 'sql-product))
(if (symbol-value rval)
(let ((filename
(concat "~/.emacs.d/sql/"
(symbol-name (symbol-value rval))
"-history.sql")))
(set (make-local-variable lval) filename)
(set-default 'sql-input-ring-file-name filename))
(error
(format "SQL history will not be saved because %s is nil"
(symbol-name rval))))))
and i describe the variable values:
sql-input-ring-file-name's value is
"~/.emacs.d/sql/mysql-history.sql"
Original value was nil
Local in buffer *SQL*; global value is the same.
and i have directory ~/.emacs.d/sql but do not have any file
my emacs version is 24.4.1
I had trouble getting the answers above to work, but this works for me. The main change is lval and kill-buffer-hook
(defun my-sql-save-history-hook ()
(let ((lval 'comint-input-ring-file-name)
(rval 'sql-product))
(if (symbol-value rval)
(let ((filename
(concat "~/.emacs.d/sql/"
(symbol-name (symbol-value rval))
"-history.sql")))
(set (make-local-variable lval) filename))
(error
(format "SQL history will not be saved because %s is nil"
(symbol-name rval))))))
(add-hook 'sql-interactive-mode-hook 'my-sql-save-history-hook)
(add-hook 'kill-buffer-hook 'comint-write-input-ring)

Pop3 Over SSL/TLS in Common Lisp

Can anyone point me to a Common Lisp library (specifically for SBCL on Linux) for pulling pop3 email over SSL/TLS? Cl-pop seems fine, but it doesn't seem to support SSL and I'm not sure how to wrap it into CL+SSL (assuming it's possible). Does anyone have any suggestions short of rolling your own?
You can redefine the usocket-connect function to yield the stream type returned by the SSL library. Then you can define methods to send and receive data over this stream using regular strings (the SSL library only supports binary by default, but CL-POP assumes that strings can be sent). You'll need to depend on the FLEXI-STREAMS library to convert between text and binary. (ql:quickload :flexi-streams)
The following is code to make the change and define the needed methods. Since usocket-connect is replaced, I provide the :unencrypted keyword to create a regular socket.
The code could probably be made more efficient.
The string-to-octets and octets-to-string functions support an :external-format argument which allows them to encode/decode many character encoding schemes, including UTF-8, ISO-8859-*, and others. The full list of supported encodings is documented here. I didn't use :external-format in this answer, so it defaults to :latin-1.
The code is written against an old version of CL+SSL that seems to have been installed on my system by the Debian package manager. The current versions of make-ssl-client-stream and make-ssl-server-stream support several more keyword arguments than are supported by the version on my machine. It doesn't matter, however, because CL-POP will use none of these keyword arguments.
(defpackage :ssl-pop
(:use :common-lisp :cl+ssl :usocket :flexi-streams))
(in-package :ssl-pop)
(let ((old-connect (symbol-function 'socket-connect)))
(defun socket-connect (host port &key (protocol :stream)
external-format certificate key crypto-password
(clientp t) close-callback unencrypted
(unwrap-streams-p t) crypto-hostname
(element-type '(unsigned-byte 8)) timeout deadline
(nodelay t nodelay-specified) local-host
local-port)
(let* ((old-connect-args
`(,host ,port :protocol ,protocol
:element-type ,element-type
:timeout ,timeout :deadline ,deadline
,#(if nodelay-specified
`(:nodelay ,nodelay))
:local-host ,local-host
:local-port ,local-port))
(plain-socket (apply old-connect old-connect-args)))
(if unencrypted
plain-socket
(let ((socket-stream (socket-stream plain-socket)))
(assert (streamp socket-stream))
(if clientp
(make-ssl-client-stream socket-stream
:external-format external-format
:certificate certificate
:key key
:close-callback close-callback)
(make-ssl-server-stream socket-stream
:external-format external-format
:certificate certificate
:key key)))))))
(defmethod socket-stream ((object cl+ssl::ssl-stream))
object)
(defmethod socket-receive ((socket cl+ssl::ssl-stream) buffer length
&key (element-type '(unsigned-byte 8)))
(let ((buffer (or buffer (make-array length
:element-type element-type))))
(loop for ix from 0 below length
do
(restart-case
(setf (aref buffer ix) (read-byte socket))
(thats-ok () :report "Return the bytes that were successfully read"
(return-from socket-receive (subseq buffer 0 ix)))))
buffer))
(defmethod socket-send ((socket cl+ssl::ssl-stream) buffer length
&key host port)
(declare (ignore host port)) ;; They're for UDP
(loop for byte across buffer
do (write-byte byte socket)))
(defmethod sb-gray:stream-read-line ((socket cl+ssl::ssl-stream))
(let ((result (make-array 0 :adjustable t :fill-pointer t
:element-type '(unsigned-byte 8))))
(loop for next-byte = (read-byte socket)
until (and (>= (length result) 1)
(= next-byte 10)
(= (aref result (- (length result) 1)) 13))
do
(vector-push-extend next-byte result))
(octets-to-string
(concatenate 'vector
(subseq result 0 (- (length result) 1))))))
(defmethod trivial-gray-streams:stream-write-sequence
((stream cl+ssl::ssl-stream) (sequence string) start end
&key &allow-other-keys)
(trivial-gray-streams:stream-write-sequence stream
(string-to-octets sequence)
start end))
(defmethod sb-gray:stream-write-char ((stream cl+ssl::ssl-stream)
(char character))
(let ((string (make-string 1 :initial-element char)))
(write-sequence (string-to-octets string) stream)))
(defmethod socket-close ((socket cl+ssl::ssl-stream))
(close socket))

How to catch any Javascript exception in Clojurescript?

In my communication layer I have a need to be able to catch ANY javascript exception, log it down and proceed as I normally would do.
Current syntax for catching exceptions in Clojurescript dictates that I need to specify the type of the exception being caught.
I tried to use nil, js/Error, js/object in the catch form and it doesn't catch ANY javascript exception (which can have string as the type of the object).
I would appreciate any hints how this can be done natively in Clojurescript.
I found another possible answer in David Nolen "Light Table ClojureScript Tutorial"
;; Error Handling
;; ============================================================================
;; Error handling in ClojureScript is relatively straightforward and more or
;; less similar to what is offered in JavaScript.
;; You can construct an error like this.
(js/Error. "Oops")
;; You can throw an error like this.
(throw (js/Error. "Oops"))
;; You can catch an error like this.
(try
(throw (js/Error. "Oops"))
(catch js/Error e
e))
;; JavaScript unfortunately allows you to throw anything. You can handle
;; this in ClojureScript with the following.
(try
(throw (js/Error. "Oops"))
(catch :default e
e))
It looks like js/Object catches them all (tested on https://himera.herokuapp.com):
cljs.user> (try (throw (js/Error. "some error")) (catch js/Object e (str "Caught: " e)))
"Caught: Error: some error"
cljs.user> (try (throw "string error") (catch js/Object e (str "Caught: " e)))
"Caught: string error"
cljs.user> (try (js/eval "throw 'js error';") (catch js/Object e (str "Caught: " e)))
"Caught: js error"
One thing to watch out for is lazy sequences. If an error is thrown in a lazy sequence that part of the code might not be executed until after you've exited the try function. For example:
cljs.user> (try (map #(if (zero? %) (throw "some error")) [1]))
(nil)
cljs.user> (try (map #(if (zero? %) (throw "some error")) [0]))
; script fails with "Uncaught some error"
In that last case, map creates a lazy sequence and the try function returns it. Then, when the repl tries to print the sequence to the console, it's evaluated and the error gets thrown outside of the try expression.
I think I've just found the solution in this link
https://groups.google.com/forum/#!topic/clojure/QHaTwjD4zzU
I copy the contents here:
This solution was published by Herwig Hochleitner
try in clojurescript is actually a macro that uses the builtin try*
and adds type dispatch. So to catch everything, just use (try* ...
(catch e ...)). This maps directly to javascript's try.
And here is my implementation working now:
(defn is-dir? [the_dir]
(try*
(if-let [stat (.statSync fs the_dir )]
(.isDirectory stat)
false)
(catch e
(println "catching all exceptions, include js/exeptions")
false
)
)
)
I hope it helps you
Juan

How do I use \*print-dup\* to print records in clojure? A simple case

I'm trying to use *print-dup* to allow writing clojure data to a file
and then read it back, however, I'm getting problems even with this
simple case. Is there something I am doing wrong? What do I need to do
to get this to work?
Clojure 1.3.0-alpha3-SNAPSHOT
user=> (defrecord TreeNode [val left right]) ;;create the record
user.TreeNode
user=> (TreeNode. 5 nil nil)
#:user.TreeNode{:val 5, :left nil, :right nil} ;; it works just fine
user=> (binding [*print-dup* true] (prn (TreeNode. 5 nil nil))) ;; use *print-dup* to support reading in and preserving type
#=(user.TreeNode/create {:val #=(java.lang.Long. "5"), :left nil, :right nil}) ;; this is the form we need to copy paste
nil
user=> #=(user.TreeNode/create {:val #=(java.lang.Long. "5"), :left nil, :right nil}) ;;trying to copy and paste
IllegalArgumentException No matching method found: create
clojure.lang.Reflector.invokeMatchingMethod (Reflector.java:50) ;;we have an error
user=>
Records don't print in an eval-able form. We added our own defrecord2 that includes support for creating constructor functions and print/pprint support to print them using the constructor function (which can be eval'ed back into the original record). This is doc'ed more here and here and the code is here.
I asked Rich Hickey about this issue at the Clojure Conj conference in Oct. 2010 and he said constructor functions and reader support for records are planned for the future.
As an update, as of alpha8, in the simple case, *print-dup* with records now works.
user=> (defrecord TreeNode [val left right])
user.TreeNode
user=> (TreeNode. 5 nil nil)
#user.TreeNode{:val 5, :left nil, :right nil}
user=> (binding [*print-dup* true] (prn (TreeNode. 5 nil nil)))
#user.TreeNode[5, nil, nil]
nil
user=> #user.TreeNode[5, nil, nil]
#user.TreeNode{:val 5, :left nil, :right nil}
user=>
Work around in 1.2:
(defn- extend-print-dup [record-class]
(defmethod print-dup record-class [o w]
(.write w "#=(")
(.write w (.getName ^Class (class o)))
(.write w ". ")
(dorun (map (fn [a] (print-dup a w) (.write w " ")) (vals o)))
(.write w ")")))
(defrecord Hl7Field [protospec segname fname pos hl7type values])
(extend-print-dup Hl7Field)
=> (def a (Hl7Field. "p" "PV1" "toto" 0 "ST" ["c" "d"]))
=> (binding [*print-dup* true] (prn a))
#=(higiebus.bus.protocol.hl7.Hl7Field. "p" "PV1" "toto" 0 "ST" ["c" "d"] )
=> #=(higiebus.bus.protocol.hl7.Hl7Field. "p" "PV1" "toto" 0 "ST" ["c" "d"] )
{:protospec "p", :segname "PV1", :fname "toto", :pos 0, :hl7type "ST", :values ["c" "d"]}
You could wrap the call to extend-print-dup in a custom defrecord macro.