Kadena Cannot define a keyset outside of a namespace error - pact-lang

I'm learning Kadena pact-lang and following the tutorial at
https://docs.kadena.io/learn-pact/beginner/hello-world
I copy pasted the code
(define-keyset 'hello-admin (read-keyset 'hello-keyset))
(module hello 'hello-admin
"Pact hello-world with database example"
(defschema hello-schema
"VALUE stores greeting recipient"
value:string)
(deftable hellos:{hello-schema})
(defun hello (value)
"Store VALUE to say hello with."
(write hellos "hello" { 'value: value }))
(defun greet ()
"Say hello to stored value."
(with-read hellos "hello" { "value" := value }
(format "Hello, {}!" [value])))
)
(create-table hellos)
(hello "world") ;; store "hello"
(greet) ;; say hello!
When I load it into REPL it errors with
<interactive>:2:0: Cannot define a keyset outside of a namespace

I got it working w/ adding to top
(define-namespace 'mynamespace (read-keyset 'user-ks) (read-keyset 'admin-ks))
(namespace "mynamespace")

Related

Return the key from database query in Clojure

I'm very new to Clojure and would like to know how to simply return the value when I query the database in clojure
I've defined a function foo like below:
(defn get-foo []
(log/info "Getting foo from the database")
(let [query "select FOO from BAR where FOO = 'test'"
results (jdbc/query (db-connection) [query])]
(log/info "Results: " results)
(log/info "Foo: " (get :foo results)
(log/info "String: " (apply str results))))
What I see in the logs:
Results: ({:foo test})
Foo: nil
String: {:foo "test"}
I would like to be able to somehow return only test, without the value attached to it like in a clob, ideally, sort of like:
(log/info "Foo: " results) would return:
Foo: test
(log/info "Foo: " (:foo (first results)))
returns:
Foo: test

Map "syntax error before " (first element) while URI.encode_query(form)

I've been doing this for a couple of days, and I'm having this problem:
Whenever I try to encode a map into query string, I get the error "syntax error before: chat_id"
form = %{
"chat_id" => 237799109,
"text" => "OMG a message"
}
{status, body} = URI.encode_query(form)
#=> (SyntaxError) lib/elixir.ex:20: syntax error before: chat_id
But as far as I know this is the map syntax, isn't it? As seen here, where this example is presented:
iex> hd = %{"foo" => 1, "bar" => 2}
iex> URI.encode_query(hd)
"bar=2&foo=1
What is happening here?
Full error message:
== Compilation error on file lib/elixir.ex ==
** (SyntaxError) lib/elixir.ex:20: syntax error before: chat_id
(elixir) lib/kernel/parallel_compiler.ex:117: anonymous fn/4 in Kernel.Paral
lelCompiler.spawn_compilers/1
I don't know why you would get the error you listed, but URI.encode_query/1 only returns a single binary argument. You are trying to pattern match it against a tuple.
Can you paste more of the code instead of just those 2 lines?
iex(2)> URI.encode_query(form)
"chat_id=237&text=OMG+a+message"

How do I read (and parse) a file and then append to the same file without getting an exception?

I am trying to read from a file correctly in Haskell but I seem to get this error.
*** Exception: neo.txt: openFile: resource busy (file is locked)
This is my code.
import Data.Char
import Prelude
import Data.List
import Text.Printf
import Data.Tuple
import Data.Ord
import Control.Monad
import Control.Applicative((<*))
import Text.Parsec
( Parsec, ParseError, parse -- Types and parser
, between, noneOf, sepBy, many1 -- Combinators
, char, spaces, digit, newline -- Simple parsers
)
These are the movie fields.
type Title = String
type Director = String
type Year = Int
type UserRatings = (String,Int)
type Film = (Title, Director, Year , [UserRatings])
type Period = (Year, Year)
type Database = [Film]
This is the Parsing of all the types in order to read correctly from the file
-- Parse a string to a string
stringLit :: Parsec String u String
stringLit = between (char '"') (char '"') $ many1 $ noneOf "\"\n"
-- Parse a string to a list of strings
listOfStrings :: Parsec String u [String]
listOfStrings = stringLit `sepBy` (char ',' >> spaces)
-- Parse a string to an int
intLit :: Parsec String u Int
intLit = fmap read $ many1 digit
-- Or `read <$> many1 digit` with Control.Applicative
stringIntTuple :: Parsec String u (String , Int)
stringIntTuple = liftM2 (,) stringLit intLit
film :: Parsec String u Film
film = do
-- alternatively `title <- stringLit <* newline` with Control.Applicative
title <- stringLit
newline
director <- stringLit
newline
year <- intLit
newline
userRatings <- stringIntTuple
newline
return (title, director, year, [userRatings])
films :: Parsec String u [Film]
films = film `sepBy` newline
This is the main program (write "main" in winghci to start the program)
-- The Main
main :: IO ()
main = do
putStr "Enter your Username: "
name <- getLine
filmsDatabase <- loadFile "neo.txt"
appendFile "neo.txt" (show filmsDatabase)
putStrLn "Your changes to the database have been successfully saved."
This is the loadFile function
loadFile :: FilePath -> IO (Either ParseError [Film])
loadFile filename = do
database <- readFile filename
return $ parse films "Films" database
the other txt file name is neo and includes some movies like this
"Blade Runner"
"Ridley Scott"
1982
("Amy",5), ("Bill",8), ("Ian",7), ("Kevin",9), ("Emma",4), ("Sam",7), ("Megan",4)
"The Fly"
"David Cronenberg"
1986
("Megan",4), ("Fred",7), ("Chris",5), ("Ian",0), ("Amy",6)
Just copy paste everything include a txt file in the same directory and test it to see the error i described.
Whoopsy daisy, being lazy
tends to make file changes crazy.
File's not closed, as supposed
thus the error gets imposed.
This small guile, by loadFile
is what you must reconcile.
But don't fret, least not yet,
I will show you, let's get set.
As many other functions that work with IO in System.IO, readFile doesn't actually consume any input. It's lazy. Therefore, the file doesn't get closed, unless all its content has been consumed (it's then half-closed):
The file is read lazily, on demand, as with getContents.
We can demonstrate this on a shorter example:
main = do
let filename = "/tmp/example"
writeFile filename "Hello "
contents <- readFile filename
appendFile filename "world!" -- error here
This will fail, since we never actually checked contents (entirely). If you get all the content (for example with printing, length or similar), it won't fail anymore:
main = do
let filename = "/tmp/example2"
writeFile filename "Hello "
content <- readFile filename
putStrLn content
appendFile filename "world!" -- no error
Therefore, we need either something that really closes the file, or we need to make sure that we've read all the contents before we try to append to the file.
For example, you can use withFile together with some "magic" function force that makes sure that the content really gets evaluated:
readFile' filename = withFile filename ReadMode $ \handle -> do
theContent <- hGetContents handle
force theContent
However, force is tricky to achieve. You could use bang patterns, but this will evaluate the list only to WHNF (basically just the first character). You could use the functions by deepseq, but that adds another dependency and is probably not allowed in your assignment/exercise.
Or you could use any function that will somehow make sure that all elements are evaluated or sequenced. In this case, we can use a small trick and mapM return:
readFile' filename = withFile filename ReadMode $ \handle -> do
theContent <- hGetContents handle
mapM return theContent
It's good enough, but you would use something like pipes or conduit instead in production.
The other method is to make sure that we've really used all the contents. This can be done by using another parsec parser method instead, namely runParserT. We can combine this with our withFile approach from above:
parseFile :: ParsecT String () IO a -> FilePath -> IO (Either ParseError a)
parseFile p filename = withFile filename ReadMode $ \handle ->
hGetContents handle >>= runParserT p () filename
Again, withFile makes sure that we close the file. We can use this now in your loadFilm:
loadFile :: FilePath -> IO (Either ParseError [Film])
loadFile filename = parseFile films filename
This version of loadFile won't keep the file locked anymore.
The problem is that readFile doesn't actually read the entire file into memory immediately; it opens the file and instantly returns a string. As you "look at" the string, behind the scenes the file is being read. So when readFile returns, the file it still open for reading, and you can't do anything else with it. This is called "lazy I/O", and many people consider it to be "evil" precisely because it tends to cause problems like the one you currently have.
There are several ways you can go about fixing this. Probably the simplest is to just force the whole string into memory before continuing. Calculating the length of the string will do that — but only if you "use" the length for something, because the length itself is lazy. (See how this rapidly becomes messy? This is why people avoid lazy I/O.)
The simplest thing you could try is printing the number of films loaded right before you try to append to the database.
main = do
putStr "Enter your Username: "
name <- getLine
filmsDatabase <- loadFile "neo.txt"
putStrLn $ "Loaded " ++ show (length filmsDatabase) ++ " films."
appendFile "neo.txt" (show filmsDatabase)
putStrLn "Your changes to the database have been successfully saved."
It's kind of evil that what looks like a simple print message is actually fundamental to making the code work though!
The other alternative is to save the new database under a different name, and then delete the old file and rename the new one over the top of the old one. This does have the advantage that if the program were to crash half way through saving, you haven't just lost all your stuff.

ref to a hash -> its member array -> this array's member's value. How to elegantly access and test?

I want to use an expression like
#{ %$hashref{'key_name'}[1]
or
%$hashref{'key_name}->[1]
to get - and then test - the second (index = 1) member of an array (reference) held by my hash as its "key_name" 's value. But, I can not.
This code here is correct (it works), but I would have liked to combine the two lines that I have marked into one single, efficient, perl-elegant line.
foreach my $tag ('doit', 'source', 'dest' ) {
my $exists = exists( $$thisSectionConfig{$tag});
my #tempA = %$thisSectionConfig{$tag} ; #this line
my $non0len = (#tempA[1] =~ /\w+/ ); # and this line
if ( !$exists || !$non0len) {
print STDERR "No complete \"$tag\" ... etc ... \n";
# program exit ...
}
I know you (the general 'you') can elegantly combine these two lines. Could someone tell me how I could do this?
This code it testing a section of a config file that has been read into a $thisSectionConfig reference-to-a-hash by Config::Simple. Each config file key=value pair then is (I looked with datadumper) held as a two-member array: [0] is the key, [1] is the value. The $tag 's are configuration settings that must be present in the config file sections being processed by this code snippet.
Thank you for any help.
You should read about Arrow operator(->). I guess you want something like this:
foreach my $tag ('doit', 'source', 'dest') {
if(exists $thisSectionConfig -> {$tag}){
my $non0len = ($thisSectionConfig -> {$tag} -> [1] =~ /(\w+)/) ;
}
else {
print STDERR "No complete \"$tag\" ... etc ... \n";
# program exit ...
}

Running join on Maybe Relation

I have a model
Assignment
blah Text
....
and a model
File
assignmentId AssignmentId Maybe
...
and I want to get all the files associated with an assignment in a join query. I have tried Esqueleto and runJoin with selectOneMany but haven't had any luck, so I am considering not using a join, or using rawSql. That really doesn't seem like a good idea, but I can't figure this out. Is there any support for that feature?
Update, working example:
{-# LANGUAGE PackageImports, OverloadedStrings, ConstraintKinds #-}
module Handler.HTest where
import Import
import "esqueleto" Database.Esqueleto as Esql
import "monad-logger" Control.Monad.Logger (MonadLogger)
import "resourcet" Control.Monad.Trans.Resource (MonadResourceBase)
import qualified Data.List as L
getFilesByAssignment :: (PersistQuery (SqlPersist m), MonadLogger m
, MonadResourceBase m) =>
Text -> SqlPersist m [Entity File]
getFilesByAssignment myAssign = do
result <- select $
from $ \(assign `InnerJoin` file) -> do
on (just (assign ^. AssignmentId)
Esql.==. file ^. FileAssignmentId)
where_ (assign ^. AssignmentBlah Esql.==. val myAssign)
return (assign, file)
return $ map snd (result :: [(Entity Assignment, Entity File)])
(.$) = flip ($)
getTestR :: Handler RepHtml
getTestR = do
entFiles <- runDB $ getFilesByAssignment "test"
defaultLayout $ do
setTitle "Test page"
entFiles .$ map (show . unKey . entityKey)
.$ L.intercalate ", "
.$ toHtml
.$ toWidget

Resources