I am using Jason language to communicate between two agents. But I am unable to use send action, it gives an error.
These are my two agents,
Agent1 :-
// Agent Agent1 in project factorial3.mas2j
/* Initial goals */
!start.
/* Plans */
+!start : true
<- .print("starting..");
!query_factorial(2).
+!query_factorial(X) : true <-
.send(agent2,tell,giveme(X)).
/*+fact(X,Y) : true <-
.print("factorial ", X, " is ", Y, " thank you expert").*/
Agent2:-
// Agent agent2 in project IdEx.mas2j
/* Initial beliefs and rules */
/* Initial goals */
!begin.
/* Plans */
+!begin : true
<- .print("expert starting.......");
!giveme(X).
+!giveme(X):true
<- !fact(X,Y);
.print("Factorial of ", X, " is ", Y).
//.send(agent1,achive,fact(X,Y)).
+!fact(X,1) : X == 0.
+!fact(X,Y) : X > 0
<- !fact(X-1,Y1);
Y = Y1 * X.
So, I am getting an error when I am trying to call send action in agent1 and agent2 gives an receive error.
UPDATED
I am getting this error,
[agent2] *** Error adding var into renamed vars. var=X, value=(_229-1).
java.lang.ClassCastException: jason.asSyntax.ArithExpr cannot be cast to jason.asSyntax.VarTerm
at jason.asSemantics.TransitionSystem.prepareBodyForEvent(TransitionSystem.java:877)
at jason.asSemantics.TransitionSystem.applyExecInt(TransitionSystem.java:728)
at jason.asSemantics.TransitionSystem.applySemanticRule(TransitionSystem.java:222)
at jason.asSemantics.TransitionSystem.reasoningCycle(TransitionSystem.java:1429)
at jason.infra.centralised.CentralisedAgArch.run(CentralisedAgArch.java:205)
at java.lang.Thread.run(Thread.java:745)
If you want to ask for an agent to perform a plan (in case of agent1 when you say "+!query_factorial(X)...") it should be an achieve message. Uncommenting the "plan" "+fact(X,Y) : true <- .print("factorial ", X, " is ", Y, " thank you expert")." you should use the operator "!" at the begining to make it a plan. So, if I undertood the general idea of your test project, it can be rewrite as follows:
Agent1 code:
!start.
+!start : true
<- .print("starting..");
!query_factorial(2).
+!query_factorial(X) : true <-
.send(agent2,achieve,giveme(X)).
Agent2 code:
+!giveme(X):true
<- !fact(X,Y);
.print("Factorial of ", X, " is ", Y).
+!fact(X,1) : X == 0.
+!fact(X,Y) : X > 0
<- !fact(X-1,Y1);
Y = Y1 * X.
You can see, I am not using the "begin plan" of your original code since the Agent1 is doing the job, making Agent2 work when asked.
Related
Iteration to datastore query result in GAE/Go is very slow.
q := datastore.NewQuery("MyStruct")
gaeLog.Infof(ctx, "run") // (1)
it := client.Run(ctx, q)
list := make([]MyStruct, 0, 10000)
gaeLog.Infof(ctx, "start mapping") // (2)
for {
var m MyStruct
_, err := it.Next(&m)
if err == iterator.Done {
break
}
if err != nil {
gaeLog.Errorf(ctx, "datastore read error : %s ", err.Error())
<some error handling>
break
}
list = append(list , m)
}
gaeLog.Infof(ctx, "end mapping. count : %d", len(list)) // (3)
The result is below.
18:02:11.283 run // (1)
18:02:11.291 start mapping // (2)
18:02:15.741 end mapping. count : 2400 // (3)
It takes about 4.5 seconds between (2) and (3), just only 2400 record. It is very slow.
How can I improve performance?
[Update]
I added the query in above code q := datastore.NewQuery("MyStruct").
I tried to retrieve all the entities in the kind MyStruct. This kind has 2400 entities.
I was using cloud.google.com/go/datastore and found it is slow. I migrated to use google.golang.org/appengine/datastore.
The result is as follows, less than 1 second.
13:57:46.216 run
13:57:46.367 start mapping
13:57:47.063 end mapping. count : 2400
I'm looking for some guidance and hope that I did the right thing posting it in here. I'm looking to input data to Quantmod with GetSymbols from SQL Server. I'm new to R but have a background working with SQL Server, not a pro but finding my way.
I have imported all my data into one table in SQL Server named Quotes with the following columns;
- Ticker Varchar(10)
- Name varchar(50)
- [Date] datetime
- [Open] Decimal(19,9)
- High Decimal(19,9)
- Low Decimal(19,9)
- [Close] Decimal(19,9)
- Volume Decimal(19,9)
- Signal Decimal(19,9)
I'm able to connect to the database using the RODBC package:
- (cn <- odbcDriverConnect(connection="Driver={SQL Server Native Client 11.0};server=localhost;database=DB;trusted_connection=yes;"))
and make various select statement in R, but I'm lost in getting the data into Quantmod without having to do other workaround like exporting to csv from SQL. Importing the data from Yahoo is a problem as I cannot find a complete Yahoo-tickerlist.
Is there a way to get data directly into R and quantmod from SQL Server?
Something like this should do the trick.
getPrices.DB <- function(Symbol, from=NA) {
cn <- "add your connection info here"
qry <- sprintf("select [Date], [Open],[High],[Low],[Close],[Volume],[Signal] from MarketPrice where Ticker = '%s'", Symbol)
if (!is.na(from)) { qry <- paste(qry, sprintf(" and [Date]>= '%s'", from)) }
DB <- odbcDriverConnect(cn)
r <- sqlQuery(DB, qry, stringsAsFactors = FALSE)
odbcClose(DB)
if (!is.null(r) && NROW(r) >= 1) {
x <- xts(r[, 2:7], order.by = as.POSIXct(r[, 1], tz = "UTC"))#can eliminate tz if you want in local timezone
indexFormat(x) <- "%Y-%b-%d %H:%M:%OS3 %z" #option. I find useful for debuggging
colnames(x) <- paste(Symbol, c("Open", "High","Low", "Close", "Volume", "Signal"), sep = ".")
return(x)
} else {
return(NULL)
}
}
Now hook into the quantmod infrastructure:
getSymbols.DB <- function(Symbols, env, ...) {
importDefaults("getSymbols.DB")
this.env <- environment()
for (var in names(list(...))) {assign(var, list(...)[[var]], this.env)}
if (!hasArg(from)) from <- NA
if (!hasArg(verbose)) verbose <- FALSE
if (!hasArg(auto.assign)) auto.assign <- FALSE
for (i in 1:length(Symbols)) {
if (verbose) cat(paste("Loading ", Symbols[[i]], paste(rep(".", 10 - nchar(Symbols[[i]])), collapse = ""), sep = ""))
x <- getPrices.DB(Symbols[[i]], from = from)
if (auto.assign) assign(Symbols[[i]], x, env)
if (verbose) cat("done\n")
}
if (auto.assign)
return(Symbols)
else
return(x)
}
example usage:
APPL <- getSymbols("AAPL", src="DB", auto.assign=F)
I have a function to update the database for a list of ID (max 1,000 elements at once, for IN in Oracle DB):
## Split the data frame into chunks of 1,000 elements max.
chunk <- split(df, ceiling(seq_along(df$id) / 1000))
res <- lapply(chunk,
function (x) sqlQuery(database,
paste0(
"UPDATE sometable
SET flag = '", batch.id, "'\n ",
"WHERE id IN (", paste0("'", x$id, "'", collapse=", "), ")")))
I'd like to test that my updates went well. But I did not find a way to get the count of updated rows via rODBC calls.
Thus, as a (satisfying!?) workaround, I'm looking at the text results of sqlQuery, and understand that when everything goes well, I get a list of character(0) results.
Now, how to assert that all the UPDATE queries were correctly done?
I tried using any or all calls, with no success:
> all(res == character(0))
[1] TRUE
> all(res != character(0))
[1] TRUE
> any(res != character(0))
[1] FALSE
> any(res == character(0))
[1] FALSE
I don't understand that, whatever my condition, the result is always TRUE (for all) or FALSE (for any).
Tried all.equal with no more success:
> all.equal(character(0), res)
[1] "Modes: character, list" "Lengths: 0, 1" "names for current but not for target" "target is character, current is list"
you have to lapply over res. as in lapply(res, identical, character(0L))
You can try:
all(vapply(res,length,1L)==0)
This evaluates the length of each component of res and returns TRUE if all the elements are of zero length (as character(0) is).
I am writing my first custom matcher in rspec. I would like to provide a failure message with a break down on why the comparison has failed. Effectively I would like to output the differences between the expected and the actual object. I effectively just need to do this with 2 arrays on the object. I have done some research and am trying to use =~ as described here. It mentions it has an informative failure message but I am struggling to access the failure message. I would effectively just like to return the combined failure message for two separate arrays to give an informative reason for the matcher returning false.
My attempt is as follows
RSpec::Matchers.define :have_same_state_as_measure_table do |expected_measure_table , max_delta = 1e-06|
match do |actual_measure_table|
actual_measure_table.equivalence(expected_measure_table, max_delta)
end
description do
"checks if measure has same state as expected measure table within a given number of precision"
end
# Optional method description
description do
"checks if measure has same state as expected measure table, within a given level of precision"
end
# Optional failure messages
failure_message do |actual_measure_table|
mismatch_string = ""
mismatch_string += (actual_measure_table.columns =~ expected_measure_table.columns || "")
mismatch_string += (actual_measure_table.names =~ expected_measure_table.names || "")
"Measure tables missmatch as follows %s" % (mismatch_string.to_s)
end
failure_message_when_negated do |actual_measure_table|
"expected friend not to be in zipcode"
end
end
My final matcher was as follows :
class CompareMeasureTables
attr_reader :expected_measure_table, :max_delta, :actual_measure_table
def initialize(expected_measure_table, max_delta=1e-06)
#expected_measure_table = expected_measure_table
#max_delta = max_delta
end
def description
"Checks if measure has same state as expected measure table, within a given level of precision"
end
def matches?(actual_measure_table)
#actual_measure_table = actual_measure_table
actual_measure_table.equivalence(expected_measure_table, max_delta, false)
end
def failure_message
#mismatch_description = ""
if actual_measure_table.columns.sort != expected_measure_table.columns.sort
#mismatch_description += "\nColumns mismatch \nExpected =" + expected_measure_table.columns.inspect
#mismatch_description += "\nActual =" + actual_measure_table.columns.inspect
end
if (#mismatch_description == "")
#mismatch_description += "\nData mismatch \nExpected =" + (expected_measure_table.records - actual_measure_table.records).inspect
#mismatch_description += "\nActual =" + (actual_measure_table.records - expected_measure_table.records).inspect
#mismatch_description += "\nTolerance set at #{#max_delta}"
end
"Measure tables mismatch as follows %s" % (#mismatch_description)
end
end
i have many data.frames() that i am trying to send to MySQL database via RMySQL().
# Sends data frame to database without a problem
dbWriteTable(con3, name="SPY", value=SPY , append=T)
# stock1 contains a character vector of stock names...
stock1 <- c("SPY.A")
But when I try to loop it:
i= 1
while(i <= length(stock1)){
# converts "SPY.A" into SPY
name <- print(paste0(str_sub(stock1, start = 1, end = -3))[i], quote=F)
# sends data.frame to database
dbWriteTable(con3,paste0(str_sub(stock1, start = 1, end = -3))[i], value=name, append=T)
i <- 1+i
}
The following warning is returned & nothing was sent to database
In addition: Warning message:
In file(fn, open = "r") :
cannot open file './SPY': No such file or directory
However, I believe that the problem is with pasting value onto dbWriteTable() since writing dbWriteTable(con3, "SPY", SPY, append=T) works but dbWriteTable(con3, "SPY", name, append=T) will not...
You are probably using a non-base package for str_sub and I'm guessing you get the same behavior with substr. Does this succeed?
dbWriteTable(con3, substr( stock1, 1,3) , get(stock1), append=T)