Access the if statement via base::if() in R - r

I am coding in R and due to stability purposes when I have to deploy something, I call every function with the syntax package::function(arguments) just to avoid conflicts that as you know may happen when using a lot of packages. It helped me a lot over the years.
I know that if is a reserved word so technically speaking it is impossible (or at least it should be in my knowledge) for someone to define an object and name it if.
I am also aware that it belongs to control flow statement (which I think are a different "thing") and due to the previous consideration I am also aware that the following questions might be useless. My pure technical doubts are:
Why if I embrace it in back-ticks the function class returns "function" as a result?
Why without back-ticks I get an error? and last but most important
Why I am unable to access it via the usual base::if() syntax?
As I said, most likely useless questions but at this point I am curious about the details underneath it.
> class(if)
Error: unexpected ')' in "class(if)"
> class(`if`)
[1] "function"
> base::if(T) T
Error: unexpected 'if' in "base::if"
> if(T) T
[1] TRUE
> base::if(`T`) T
Error: unexpected 'if' in "base::if"

if-with-backticks actually returns .Primitive("if")
The R language definition section on "Internal vs Primitive" specifies that .Primitive objects include
“Special functions” which really are language elements, but implemented as primitive functions:
{ ( if for while repeat break next
return function quote switch
The reason that a naked "if" without backticks or base::if don't work is that the "language elements" above are treated as special cases by R's parser. Once you have typed base::, R's parser expects the next symbol to be a regular symbol that can be looked up in the base namespace. base::if, base::for, and base::( all return errors because R does not expect these special elements to occur at this position in the input stream; they are syntactically incorrect.

Related

How and why is a GNAT.Strings.String_List use clause disallowed? How can you use System.Strings.String_List."&" with infix notation?

Posting for two reasons: (1) I was stuck on unhelpful compiler errors for far too long for such a simple issue and I want the next person to google those messages to come upon my (or other) answers, and (2) I still don't understand disallowing a use clause, so my own answer is really incomplete.
In order to call a program in two places with mostly the same arguments, I want to use the '&' to append to a default list inline:
declare
Exit_Code : constant Integer := GNAT.OS_Lib.Spawn (Program_Name => "gprbuild", Args => (Default_GPR_Arguments & new String'(File_Name_Parameter)));
begin
if Exit_Code /= 0 then
raise Program_Error with "Exit code:" & Exit_Code'Image;
end if;
end;
However, the compiler complains that System.Strings.String_List needs a use clause:
operator for type "System.Strings.String_List" is not directly visible
use clause would make operation legal
But inserting use System.Strings.String_List yields:
"System.Strings.String_List" is not allowed in a use clause
I also got this warning:
warning: "System.Strings" is an internal GNAT unit
warning: use "GNAT.Strings" instead
So I substituted GNAT for System in the with and the use clause and got an extra error in addition to the original 'you need a use clause for System.Strings.String_List' one:
"GNAT.Strings.String_List" is not allowed in a use clause
Why is GNAT.Strings.String_List not allowed in a use clause? Section 8.5 on use clauses doesn't seem to state anything on disallowed packages, so is this a compiler bug? Is it possible to define a new package that cannot have a use clause?
In a use clause of the form
use Name;
Name must be a package name. GNAT.Strings.String_List is a subtype name, not a package name.
There are a number of ways to invoke "&" for String_List. The simplest is to use the full name:
GNAT.Strings."&" (Left, Right)
but presumably you want to be able to use it as an operator in infix notation, Left & Right. Ways to achieve this, in decreasing specificity:
function "&" (Left : GNAT.Strings.String_List; Right : GNAT.Strings.String_List) return GNAT.Strings.String_List renames GNAT.Strings."&"; This makes this specific function directly visible.
use type GNAT.Strings.String_List; This makes all primitive operators of the type directly visible.
use all type GNAT.Strings.String_List; This makes all primitive operations of the type (including non-operator operations) directly visible.
use GNAT.Strings; This makes everything in the package directly visible.
Looks like it is a design decision. And many other packages in System follows this rule. From the s-string.ads (package specification for System.String):
-- Note: this package is in the System hierarchy so that it can be directly
-- be used by other predefined packages. User access to this package is via
-- a renaming of this package in GNAT.String (file g-string.ads).
My guess why this is done in that way: because it isn't in the Ada specification, but extension from GNAT.

What is the difference between ?matrix and ?matrix()

I was going through swirl() again as a refresher, and I've noticed that the author of swirl says the command ?matrix is the correct form to calling for a help screen. But, when I run ?matrix(), it still works? Is there a difference between having and not having a pair of parenthesis?
It's not specific to the swirl environment (about which I was entirely unaware until 5 minutes ago) That is standard for R. The help page for the ? shortcut says:
Arguments
topic
Usually, a name or character string specifying the topic for which help is sought.
Alternatively, a function call to ask for documentation on a corresponding S4 method: see the section on S4 method documentation. The calls pkg::topic and pkg:::topic are treated specially, and look for help on topic in package pkg.
It something like the second option that is being invoked with the command:
?matrix()
Since ?? is actually a different shortcut one needs to use this code to bring up that page, just as one needs to use quoted strings for help with for, if, next or any of the other reserved words in R:
?'?' # See ?Reserved
This is not based on a "fuzzy logic" search in hte help system. Using help instead of ? gets a different response:
> help("str()")
No documentation for ‘str()’ in specified packages and libraries:
you could try ‘??str()’
You can see the full code for the ? function by typing ? at the command line, but I am just showing how it starts the language level processing of the expressions given to it:
`?`
function (e1, e2)
{
if (missing(e2)) {
type <- NULL
topicExpr <- substitute(e1)
}
#further output omitted
By running matrix and in general any_function you get the source code of it.

What language is used by bosun?

From their quickstart guide I got this following sample
alert cpu.is.too.high {
template = test
$metric = q("sum:rate{counter,,1}:os.cpu{host=your-system-here}", "1h", "")
$avgcpu = avg($metric)
crit = $avgcpu > 80
warn = $avgcpu > 60
}
I would guess it's a perlish DSL. What is the name of this language?
We just call it "Bosun's expression language" and is documented at http://bosun.org/expressions.html. As you said it is a custom DSL. It currently has the following qualities
It is not imperative. The language itself actually lacks true variables, the "$foo" are just text replacement
It is functional
It is well typed (functions accept and return specific types. Since the DSL is for alerting, we believe it is important to catch as many errors at possible at parse time.)
The guts implementation of the parser and lexer is based on that guts of text/template. A map function that takes an expression to operator on every X item in a series for an entire seriesSet is in the works, so the language is still a bit in the works. But I don't think we will be change the underlying design choices mentioned above (except maybe actually use real variables instead of text replacement at some point.)

how to remove warnings regarding use of scanf in Qt?

I used scanf() in my program,when I compile it I'm getting a lot of warnings regarding use of scanf as follows:
D:\myspace\projects\nnf\NNFAdaptor\NNFAdaptor\main.cpp
C4996: 'scanf': This function or variable may be unsafe. Consider using scanf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS.
I also tried using _CRT_SECURE_NO_WARNINGS but it is not present in my Qt (headers),it is shown as error.
Put #define _CRT_SECURE_NO_WARNINGS at the top of your main.cpp (before any #includes).
That class of warnings is mostly wrong (particularly about what to use instead) but it really is true that you should not use scanf, because:
It is very easy to write a format specification that is dangerous in the same way that gets is dangerous, i.e. it will write past the end of a buffer without noticing. It is possible to write format specifications that don't have this problem but it is much harder.
It is almost impossible to write a scanf-based input parser that can handle ill-formed input reliably.
Overflow in any numeric conversion is technically undefined behavior, which means the C library is allowed to crash your program just because someone typed too many digits. (Good C libraries will not do anything worse than produce garbage in your result variable, but that can itself be a headache.)
You should not use scanf_s instead; it attempts to paper over problem 1 but doesn't entirely succeed, and it doesn't address problems 2 and 3 at all. Since you are using Qt, I recommend:
Read entire lines into std::strings using std::getline.
Parse them with QRegExp.
Convert numeric strings to numbers with e.g. QString::toDouble.
If your input syntax is more complicated than regexes can handle, investigate QLALR.

Pass unevaluated commands to a function in R

I am a bit of an R novice, and I am stuck with what seems like a simple problem, yet touches pretty deep questions about how and when things get evaluated in R.
I am using Rserve quite a bit; the typical syntax to get things evaluated remotely is a bit of a pain to type repeatedly:
RSeval(connection, quote(try(command)))
So I would like a function r which does the same thing with just the call:
r(command)
My first, naive, bound to fail attempt involved:
r <- function(command) {
RSeval(c, quote(try(command)))
}
You've guessed it: this sends, literally, try(command) to my confused Rserve daemon. I want command to be partially evaluated, if that makes any sense -- i.e. replaced by what I typed as an argument, but without evaluating it locally.
I looked for solutions to this, browsed throught the documentation for quote, substitute, eval, call, etc.. but I was not able to find something that worked. Either command gets evaluated locally, or not at all.
This is not a big problem, I can type the whole damn quote(try()) thing all the time; but at this point I am mostly curious as to how to get this to work!
EDIT:
More explanations as to what I want to do.
In the text above, command is meant to be a call do a function, ideally -- i.e., not a character string. Something like a <- 3 or assign("a", 3) rather than "a<-3" or quote(a<-3).
I believe that this is part of what makes this tricky. It seems really hard to tell R not to evaluate this locally, but only send it literally. Basically I would like my function to be a bit like quote(), which does not evaluate its argument.
Some explanation about my intentions. I wish to use Rserve frequently to pass commands to a remote R daemon. The commands would be my own (or my colleagues) and the daemon protected by firewall and authentication (and would not be run as root) -- so there is no worry of malicious commands being passed.
To be perfectly honest, this is not a big issue, and I would be pretty happy to always use the RSeval(c, quote(try())). At this point I see this more like an interesting inquiry into the subleties of R :-)
You probably want to use the substitute command, it can give you the argument unevaluated that you can build into the call.
I'm not sure if I understood you correctly - would eval(parse(text = command)) do the trick? Notice that command is a character, so you can easily pass it as a function argument. If I'm getting the point...
Anyway, evaluating user-specified commands is potentially malicious, therefore not recommended. You should either install AppArmor and tweak it (which is not an easy one), or drop the whole evaluation thing...

Resources