Meteor. Did not check() all arguments during call - exception

My meteor logs are full of these kind of errors:
Exception while invoking method 'updateShotTitle' Error: Did not check() all arguments during call to 'updateShotTitle'
at _.extend.throwUnlessAllArgumentsHaveBeenChecked (packages/check/match.js:352)
at Object.Match._failIfArgumentsAreNotAllChecked (packages/check/match.js:108)
at maybeAuditArgumentChecks (packages/ddp/livedata_server.js:1596)
at packages/ddp/livedata_server.js:648
at _.extend.withValue (packages/meteor/dynamics_nodejs.js:56)
at packages/ddp/livedata_server.js:647
at _.extend.withValue (packages/meteor/dynamics_nodejs.js:56)
at _.extend.protocol_handlers.method (packages/ddp/livedata_server.js:646)
at packages/ddp/livedata_server.js:546
This is client code:
keypress .info-title-input': (e) ->
if e.keyCode == 13
name = $(e.currentTarget).val()
file_name = #.file_name
shot_id = #.shot_parent
check(shot_id, String)
check(file_name, String)
check(name, Match.Any)
Meteor.call("updateShotTitle", shot_id, file_name, name)
And also in methods the are checks, but nothing helps me of understanding why this is happening
updateShotTitle: (shot_id, file_name, title) ->
check(shot_id, Match.Any)
check(file_name, Match.Any)
check(title, Match.Any)
Shots.update(
{ shot_id: shot_id, "images.file_name": file_name },
{ $set: { "images.$.title": title } }
)
And this is not the only method that gives me such errors, almost all of them throw this kind of exceptions. What I am doing wrong ?

Related

String passed to JSON library turns into a table

When I execute this code (Windows 10) i get an error from within the library.
local json = loadfile("json.lua")()
local handle = io.popen("curl \"https://someurl.com\"")
local result = handle:read("*all")
handle:close()
local output = json:decode(result)
The error in the console:
lua: json.lua:377: expected argument of type string, got table
stack traceback:
[C]: in function 'error'
json.lua:377: in method 'decode'
monitor.lua:10: in main chunk
[C]: in ?
I'm running the code on Windows 10 with a console and using this library: https://github.com/rxi/json.lua
This function always returns the same error, even if I try different types of arguments, i.e. numbers or strings.
function json.decode(str)
if type(str) ~= "string" then
error("expected argument of type string, got " .. type(str))
end
local res, idx = parse(str, next_char(str, 1, space_chars, true))
idx = next_char(str, idx, space_chars, true)
if idx <= #str then
decode_error(str, idx, "trailing garbage")
end
return res
end
local output = json:decode(result)
is syntactic sugar for
local output = json.decode(json, result)
json is a table.
Hence inside function json.decode the following if statement is entered:
if type(str) ~= "string" then
error("expected argument of type string, got " .. type(str))
end
which produces the observed error.
To fix this you can either change the function definiton to
function json:decode(str)
-- code
end
Or you call
local output = json.decode(result)
You should pick the second one as changing the json library will affect code that already uses json.decode as intended by the author.

Lua variable as a function call

I need to define some variables in lua which when accessed result in a call of C++ function:
Lua:
var rootname = root.name; // 'root' acts as a call to c++ function defined below
C++:
class Node
{
std::string name;
}
Node * root()
{
return MyNodeGraph->GetRoot();
}
Is that possible in Lua?
Yes you can do something like that. That's acutally one of the most common use cases of Lua. Although the proper Lua syntax would be local a = prop() if you want a to be 5.
Read https://www.lua.org/manual/5.3/
and https://www.lua.org/pil/24.html
https://www.lua.org/pil/25.html
https://www.lua.org/pil/26.html
Setting metatable of _G might not be part of the "Lua best practices" but here you go:
setmetatable(_G, {
__index = function(t, k)
if k == "root" then
return root_function() -- Call your C function here.
end
return rawget(t, k)
end
})
-- This function is just for a quick test. Call C function instead of this.
function root_function()
print("in root_function")
return { name = "hello" }
end
--
-- Test
rootname = root.name
print(rootname) -- Prints "hello"

Catch mysql error in R

I'am working with r and mysql database and I don't know how catch an insert data into table error in mysql.
I have this:
status <- tryCatch({ AnalyzerDb.insert_data_frame(dataset) })
But when I run the code I have an error:
Error en mysqlExecStatement(conn, statement, ...) :
RS-DBI driver: (could not run statement: Duplicate entry '00001002-2014-01-17 00:00:00' for key 'PRIMARY')
But when I view the value in status var, the variable has NULL value.
Thanks
tryCatch works by you defining functions that handle errors and warnings. If you don't supply tryCatch with any such handles, nothing will be done.
The documentation has several examples illustrating this, as well as a long description outlining how it works.
Something like this:
tryCatch(log("a"),error = function(e) cat("I found an error"))
I have defined this function:
myDivideTryCatchInformation <- function(StatusVector, status ) {
if (class(status) == "try-warning") {
StatusVector[4] = StatusVector[4] + 1
} else if (class(status) =="try-error") {
StatusVector[5] = StatusVector[5] + 1
} else {
StatusVector[3] = StatusVector[3] + 1
}
return(StatusVector)
}
params: StatusVector: this is a vector with 6 positions: XXX, rows, ok, warnings, errors, XXX
and status is the result of try function.

Scala: How to write a generic check function that evaluates any function that returns boolean?

I'm struggling a bit with this: I need a function that takes any function
of type fun(Any*) : Boolean as parameter, evaluates the function and returns true or
false, depending on the success of the function evaluation.
Essentially, what I need is a function type that allows any number and any type of parameter but the function must return Boolean.
Which would allow me to write functions like:
def checkLenght(str : String, length : Int) : Boolean ={
if (str.lenght == length)}
or
def ceckAB(a : Int, b : Int) : Boolean = {
if(a < b && a >= 23 && b < 42) }
so that, for example
eval(checkLenght(abc, 3)) //returns true
eval(ceckAB(4,1)) // returns false
I thought, a function type of:
type CheckFunction = (Any*) => Boolean
may does the trick but I struggle with writing the generic eval function.
Any advise?
Thank you
Solution:
The function requires
1) Another function of return type Boolean: "(func : => Boolean)"
2) Return type Boolean ": Boolean"
3) Returns the value of the passed function-parameter: " = func"
Altogether the function is:
def eval(func : => Boolean) : Boolean = func
It amazes me over again how simple simple things are in Scala.
As pointed out by the comments, this is a rather unusual function with no obvious
sense. Just a word about the underlying reasons.
Motivation:
There were a lot of question about the underlying motivation, so here a short
summary why such a function is needed.
Essentially, there are two reasons.
First one is about moving the failure handling away from the function itself
into a handler function. This preserves the purity of the check function and even allows
re-usage of generic checks.
Second, it's all about "pluggable failure handling". This means, the eval function only
tells if a failure happened (or not). In case of a failure, a handler is called through an interface. The implementation of the handler can be swapped using profiles as required.
Why?
Swapping profiles means, I code my checks and functions as usual but by switching the
profile, I switch the handler which means I can chose between full-stop, console print out, email alert, SNMP notification, push message... you name it. To do so, I need to decouple the check function from its evaluation and from its handling. That's the motivation for such a rather strange looking eval function.
And for the sake of completeness, I've already implemented all that stuff but was I facing the limitation of only handling trivial checks i.e. check(Boolean*) which is neat but often I would prefer to write a function to do more sophisticated checks.
Solved
The function is defined by returning the value of the passed function:
def eval(func : => Boolean) : Boolean = {func}
I can't say that I really understand your motivations for wanting to do what you want to do, but I guess that's beside the point. Maybe the eval function will check something before invoking the supplied function and not invoke that other function (like a fast fail) given some certain condition. Maybe you do some post checking after invoking the function and change the result based on something else. Either way, I suppose you could accomplish something similar to what you want with code looking like this:
def main(args: Array[String]) {
val str = "hello world"
println(eval(checkLength(str, 3)))
println(eval(intsEqual(1,1)))
}
def eval(func: => Boolean):Boolean = {
//Do whetever you want before invoking func, maybe
//not even invoke it if some other condition is present
val fres = func
//Maybe change something here before returning based on post conditions
fres
}
def checkLength(s:String, len:Int) = s.length() == len
def intsEqual(a:Int, b:Int) = a == b
If you really want the eval function to be able to support any function that takes any types of args and returns a Boolean, then using a by-name function like this, and then leveraging closure inside the by-name function to pass any params along to whatever actual function you want to invoke. A better way to demonstrate this is as follows:
def checkMyString(str:String, len:Int) = {
eval(str.length == len)
}
It's probably hard to see that the check str.length == len is not invoked unless eval decides to invoke it until you expand it to it's true form:
def checkMyString(str:String, len:Int) = {
def check = {
str.length == len
}
eval(check)
}
Here, the nested function check has access to str and len due to closure, and this will allow you to get around the requirement that eval must be able to invoke a function with any params that returns a Boolean.
This is just one way to solve your problem, and it might not even be suitable given your needs, but I just wanted to throw it out there.
If your input functions only have 2 arguments, like your two examples, you can write a semi generic function take takes all functions with two arguments of any type:
def eval[A,B](func: (A,B) => Boolean, arg1: A, arg2: B) = {
func(arg1, arg2)
}
def checkLength(str: String, length: Int) : Boolean = {
str.length == length
}
eval(checkLength, "ham", 4)
res0: Boolean = false
But if you want to support functions with more arguments, you would have to write one eval function for three arguments, four arguments, etc
Maybe there is a better way that can handle all cases?

How to avoid "source !=null" when using Code Contracts and Linq To Sql?

I have the following code using a normal data context which works great:
var dc = new myDataContext();
Contract.Assume(dc.Cars!= null);
var cars = (from c in dc.Cars
where c.Owner == 'Jim'
select c).ToList();
However when I convert the filter to an extension method like this:
var dc = new myDataContext();
Contract.Assume(dc.Cars!= null);
var cars = dc.Cars.WithOwner('Jim');
public static IQueryable<Car> WithOwner(this IQueryable<Car> cars, string owner)
{
Contract.Requires(cars != null);
return cars.Where(c => c.Owner == owner);
}
I get the following warning:
warning : CodeContracts: requires unproven: source != null
My guess is that your warning is caused by the owner parameter, rather than the cars. Add a precondition in the WithOwner method to check if owner is not null.
public static IQueryable<Car> WithOwner(IQueryable<Car> cars, string owner)
{
Contract.Requires(cars != null);
Contract.Requires(!string.isNullOrEmpty(owner));
return cars.Where(c => c.Owner = owner);
}
In your first code sample, you have 'Jim' hard-coded, so no problems there because there is not something which can be null.
In your second example you created a method for which the static compiler cannot prove that the source ( being owner ) 'will never be null', as other code might call it with an invalid values.
I wonder how you get the code compiled with the Extension method since you are missing this keyword in your method signature.
public static IQueryable<Car> WithOwner(this IQueryable<Car> cars, string owner)
{
...
}
/KP
Its possible that your code snippet does not completely describe the code you are using.
Consider this snippet instead:
var dc = new myDataContext();
Contract.Assume(dc.Cars!= null);
var models = dc.Cars.WithOwner('Jim').Select(c => c.Model);
public static IQueryable<Car> WithOwner(this IQueryable<Car> cars, string owner)
{
Contract.Requires(cars != null);
return cars.Where(c => c.Owner == owner);
}
In this snipped its likely the runtime will complain with the warning you mentioned, but it is not complaining about Cars possibly being null, it is complaining about the result from WithOwner (passed into Select) possibly being null.
You can satisfy the runtime by ensuring that the result from your extension method will not be null:
Contract.Ensures(Contract.Result<IQueryable<Car>>() != null);
This contract should be ok because Where will not return null, but instead returns an Enumerable.Empty<T>() when there are no matches.
We fixed this a few releases back. The warning was due to some missing contracts around Linq expression construction etc. Linq expression methods have contracts and the C# compiler generates code that calls these methods. If we don't have enough post conditions on the called methods, then you can get these cryptic warnings about code that you don't even know is there (unless you look with ILdasm).