Racket : How do i print the mysql result in a HTML page - html

I am trying print the values from the DB on the HTML page generated in APPLICATION.rkt
but this is what i see when i execute the code below
&createstring;&db-conn;SELECT * from students
Here is what I am trying to execute:
#lang racket
(require db)
(require web-server/servlet)
(provide/contract (start (request? . -> . response?)))
(define db-conn
(virtual-connection
(lambda () (mysql-connect #:server "localhost"
#:port 8889
#:database "SOB"
#:user "root"
#:password "root"))))
(define (start request)
(define (createstring id name sid)
(string-append "id is " id "and name is " name "and sid is " sid))
(response/xexpr
'(html
(head (title "SOB"))
(body
,#(map (h1) (map createstring (in-query db-conn "SELECT * from students"))))
)))
(require web-server/servlet-env)
(serve/servlet start
#:launch-browser? #f
#:quit? #f
#:listen-ip #f
#:port 8080
#:extra-files-paths
(list (build-path "/Users/lalith/Documents/LALITH FILES/MDX/SOB/" "htmlfiles"))
#:servlet-path
"/servlets/APPLICATION.rkt")
Any suggestions as to what I'm doing wrnog?

There are a couple problems.
First, use quasiquote (or "backquote") instead of quote; otherwise you can't escape from it with ,# (ie, unquote-splicing). In other words, change
'(html ___)
to
`(html ___)
Then, inside the ,# escape, your maps are wrong, and map doesn't work with in-query anyway. You probably want something like this instead:
,#(for/list ([(id name sid)
(in-query db-conn "SELECT id, name, sid from students")])
`(h1 ,(createstring id name sid)))
Or something like that. (The code above would make a level-1 header for each row in the table, if that's what you want.)
Edited in response to comment: It looks like id is a numeric column in the database. If you have a recent version of Racket, I recommend using ~a, which is like string-append but automatically converts non-string values to strings first. Change the definition of createstring to this:
(define (createstring id name sid)
(~a "id is " id "and name is " name "and sid is " sid))
In older versions of Racket (before ~a), use format instead (see the docs for how).

Related

Creating a variable by passing alrd made variables into a function (R language)

I am a little bit confuse on running my code I already write the code for the first and second prompts on the screenshot. But, it won't run when I hit resources. I ask my friend, it's correct. I'm so lost.
Prompt:
Create a variable my_intro by passing your variables my_name and my_age
into your make_introduction() function
Using the str_count function, create a variable occurrences that stores
the # of times the letter "e" appears in my_intro
my code:
make_introduction <- function(name, age){
cat("Hello, my name is", name, ",", " ", "and I'm", age,"years old.")
}
make_introduction("Stephanie",20)
make_introduction <- function(my_name, my_age){
cat(" ", "Hello, my name is", my_name, ",", " ", "and I'm", my_age,"years old.")
}
my_intro <- make_introduction(my_name, my_age)
occurences <- str_count(my_intro, "e")

LISP: how to properly encode a slash ("/") with cl-json?

I have code that uses the cl-json library to add a line, {"main" : "build/electron.js"} to a package.json file:
(let ((package-json-pathname (merge-pathnames *app-pathname* "package.json")))
(let
((new-json (with-open-file (package-json package-json-pathname :direction :input :if-does-not-exist :error)
(let ((decoded-package (json:decode-json package-json)))
(let ((main-entry (assoc :main decoded-package)))
(if (null main-entry)
(push '(:main . "build/electron.js") decoded-package)
(setf (cdr main-entry) "build/electron.js"))
decoded-package)))))
(with-open-file (package-json package-json-pathname :direction :output :if-exists :supersede)
(json:encode-json new-json package-json))
)
)
The code works, but the result has an escaped slash:
"main":"build\/electron.js"
I'm sure this is a simple thing, but no matter which inputs I try -- "//", "/", "#//" -- I still get the escaped slash.
How do I just get a normal slash in my output?
Also, I'm not sure if there's a trivial way for me to get pretty-printed output, or if I need to write a function that does this; right now the output prints the entire package.json file to a single line.
Special characters
The JSON Spec indicates that "Any character may be escaped.", but some of them MUST be escaped: "quotation mark, reverse solidus, and the control characters". The linked section is followed by a grammar that show "solidus" (/) in the list of escaped characters. I don't think it is really important in practice (typically it needs not be escaped), but that may explain why the library escapes this character.
How to avoid escaping
cl-json relies on an internal list of escaped characters named +json-lisp-escaped-chars+, namely:
(defparameter +json-lisp-escaped-chars+
'((#\" . #\")
(#\\ . #\\)
(#\/ . #\/)
(#\b . #\Backspace)
(#\f . #\)
(#\n . #\Newline)
(#\r . #\Return)
(#\t . #\Tab)
(#\u . (4 . 16)))
"Mapping between JSON String escape sequences and Lisp chars.")
The symbol is not exported, but you can still refer to it externally with ::. You can dynamically rebind the parameter around the code that needs to use a different list of escaped characters; for example, you can do as follows:
(let ((cl-json::+json-lisp-escaped-chars+
(remove #\/ cl-json::+json-lisp-escaped-chars+ :key #'car)))
(cl-json:encode-json-plist '("x" "1/5")))
This prints:
{"x":"1/5"}

Why am I getting lifted/5.1 undefined error while using formlets?

I am having trouble with an error I keep getting while trying to use formlets in racket. It says:
; lifted/5.1: undefined;
; cannot reference an identifier before its definition
; in module: top-level
; internal name: lifted/5.1
Nothing in my code is named "lifted" or "5.1" or any combination of the two. I am thinking that this is something inside the black box of formlets that I'm running up against, but I don't know what.
; set up
(require web-server/servlet web-server/servlet-env)
(require web-server/formlets)
; body of program
(define simpleformlet
(formlet
(#%#
"Name: " ,{input-string . => . name}
"Number: " ,{input-int . => . number})
(name number)))
(define (start request)
(showpage request))
(define (showpage request)
(define (responsegen embed/url)
(response/xexpr
`(html
(head (title "App3"))
(body (h1 "Let's try this...")
(form
([action ,(embed/url actionhandler)]
[method "POST"])
,#(formlet-display simpleformlet)
(input ([type "submit"])))))))
(define (actionhandler request)
(define-values (name number)
(formlet-process simpleformlet request))
(response/xexpr
`(html
(head (title "Alright!"))
(body (h2 "name")
(p ,name)
(h2 "number")
(p ,number)))))
(send/suspend/dispatch responsegen))
; run it!
(serve/servlet start
#:servlet-regexp #rx""
#:servlet-path "/form")
I added the line
#lang racket
at the top of your program. Used "Determine language from source" in the lower, left corner of DrRacket. And ran your program. A browser window opened and I was able to enter a name and a number, before I got a sensible error.
I am using Racket version 6.12, so if you are using an older version of Racket, then upgrade and try again.

Clojure write 2d array to csv

I understand how to write to CSV using [clojure.data.csv] But I am at a loss as to write the CSV in this specific format.
The data I want to write to CSV is the result of a DB query using [clojure.java.jdbc] with the as-arrays? true modifier which returns a 2D array where [0][1] is the column names which need to become the headers in the CSV and then [x][y] will become the data to write to these headers so [1][0] will write the first returned row and column 0 to the CSV under the first heading.
(with-open [out-file (io/writer "out-file.csv")]
(csv/write-csv out-file
[["abc" "def"]
["ghi" "jkl"]]))
The above is an example of writing to CSV file, but I am unsure how to use the result of my query and write the values to CSV.
The data will look like this:
[[header1, header2, header3]
[val1, val2, val3]
[val1, val2, val3]]
The query looks like this:
(j/query db ["$SOME_QUERY"] as-arrays? true))
Can somebody help with this?
Edit: update this is what i have so far:
(defn write-query-to-csv [query db output-filename]
(log/info (str "Executing " query " on " db))
(let [results (j/query db ["$QUERY"]
:as-arrays? true)
header (->> results
first)
data (->> results)]
(with-open [out-file (io/writer output-filename)]
(csv/write-csv out-file
(reduce conj (conj [] header) data)))
(io/file output-filename)))
The header data is correct but I'm unsure how to populate the data variabale :/
It looks to me like results is a sequence of sequences, and in the let you pull the header sequence out, but don't strip it off of the data. Then header contains a sequence of header labels, and data contains the header sequence plus the data sequences (one sequence for each row). The reduce line adds the header sequence back on to the sequence of sequences--which now contains two header sequences. Most of that isn't necessary. Since results is in the correct format for passing to write-csv, the let only needs to bind results, and then you can pass results with no modification as the second argument to write-csv, like this:
(defn write-query-to-csv [query db output-filename]
(log/info (str "Executing " query " on " db))
(let [results (j/query db ["$QUERY"]
:as-arrays? true)]
(with-open [out-file (io/writer output-filename)]
(csv/write-csv out-file result)
(io/file output-filename)))
So you don't need the reduce line here, but for future reference, it would probably clearer to replace (conj [] header) with (vector header). Also, another way to write the entire reduce expression would be (cons header data). That will return a different kind of sequence than your reduce line, but write-csv won't care, and I think performance should be similar. You could also use (into (vector header) data).

How to control indentation after an open parenthesis in Emacs

When I use emacs python-mode, if the last character of a line is an open parenthesis it indents the next line just one step in from the indentation of the previous line.
call_some_function(
some_very_long_argument_that_I_want_to_put_on_its_own_line)
I like that. Now in ecmascript-mode (which I am using for actionscript 3), it always indents to the level of the previous parenthesis.
call_some_function(
this_is_not_really_saving_me_any_horizontal_space);
How can I make ecmascript-mode indent like python-mode in this respect?
Since ecmascript-mode is based on cc-mode, you can use c-set-offset which allows you to customize any syntactic symbol's offset with the preferred value.
In your case, go to the point which is indented in the wrong level, hit C-c C-o (or type M-x c-set-offset), accept the suggested symbol (arglist-intro), and set it a new value (e.g. +, the default offset).
You can also do it programmatically in your dotemacs, for instance, with:
(add-hook 'ecmascript-mode-hook
(lambda ()
(c-set-offset 'arglist-intro '+)
(c-set-offset 'arglist-close 0)))
ecmascript-mode seems to be based on cc-mode. If you set the indentation style for cc-mode,
it will also work for ecmascript-mode. I have the following code in my .emacs. When I use
ecmascript-mode it indents as desired:
;;{{{ c/c++ indent style variables
(require 'cc-mode)
(defconst my-c-style
'(
(c-electric-pound-behavior . 'alignleft)
(c-tab-always-indent . t)
(c-hanging-braces-alist . ((block-open)
(brace-list-open)
(substatement-open)
(defun-open before after)
(defun-close before after)
))
(c-hanging-colons-alist . ((member-init-intro before)
(inher-intro)
(case-label)
(access-label after)
(label after)
(access-key after)))
(c-cleanup-list . (scope-operator
empty-defun-braces
defun-close-semi))
(c-offsets-alist . ((arglist-close . c-lineup-arglist)
(case-label . 4)
(statement-case-intro . 4)
(access-label . -4)
(label . -)
(substatement-open . 0)
(block-open . 0)
(knr-argdecl-intro . -)))
)
"My C++/C Programming Style")
; Customizations for both c-mode and c++-mode
(defun my-c-mode-common-hook ()
; set up for my perferred indentation style, but only do it once
(c-add-style "My" my-c-style 'set-this-style)
; we like auto-newline and hungry-delete
(c-toggle-auto-hungry-state 1)
; keybindings for both C and C++. We can put these in c-mode-map
; because c++-mode-map inherits it
(define-key c-mode-map "\C-m" 'newline-and-indent)
; insert 8 tabs
(setq tab-width 8)
)
;;}}}
Thank you Török Gábor, in my case I prefered to set
(add-hook 'XXX-mode-hook
(lambda ()
(c-set-offset 'arglist-cont-nonempty '+)))
I was looking for something like this :
veryLongFunctionName (bar,
bar,
bar)
For a more exhaustive list of variables : read emacs documentation