How to mount the drive for use in R Colab - r

I'm trying to use the driver for R colab but it gives the following error
if (file.exists("/usr/local/lib/python3.6/dist-packages/google/colab/_ipython.py")) {
install.packages(" R.utils")
library("R.utils")
library("httr")
my_check <- function() {return(TRUE)}
reassignInPackage("is_interactive", pkgName = "httr", my_check)
options(rlang_interactive=TRUE )
}
drive_auth(
email = gargle:: gargle_oauth_email (),
path = NULL,
scopes = "https://www.googleapis.com/auth/drive",
cache = gargle:: gargle_oauth_cache (),
use_oob = gargle:: gargle_oob_default () ,
token = NULL
)
Error in drive_auth():
! Can't get Google credentials
ℹ Are you running googledrive in a non-interactive session? Consider:
• drive_deauth() to prevent the attempt to get credentials
• Call drive_auth() directly with all necessary specifics
ℹ See gargle's "Non-interactive auth" vignette for more details:
ℹ https://gargle.r-lib.org/articles/non-interactive-auth.html
Traceback:
drive_auth(use_oob = TRUE, cache = TRUE)
drive_abort(c("Can't get Google credentials", i = "Are you running googledrive in a non-interactive session? \\n Consider:",
. * = "{.fun drive_deauth} to prevent the attempt to get credentials",
. * = "Call {.fun drive_auth} directly with all necessary specifics",
. i = "See gargle's "Non-interactive auth" vignette for more details:",
. i = "{.url https://gargle.r-lib.org/articles/non-interactive-auth.html}"))
cli::cli_abort(message = message, ..., .envir = .envir)
rlang::abort(message, ..., call = call, use_cli_format = TRUE,
. .frame = .frame)
signal_abort(cnd, .file)

Related

R - mocking API requests with `gh` package

I am trying to mock the output of a gh API request:
httptest2::with_mock_dir("gh", {
test_that("api works", {
gh::gh("GET /repos/r-lib/gh")
})
})
I am trying to set up testing for custom functions that routinely make API calls to GitHub and I am using gh to make these requests. I am following this tutorial as guidance: https://books.ropensci.org/http-testing/
However, no directory is created when this function is run. Is there anyway to capture the output of gh::gh and store it as a mock API return so that I can run my tests without needing GitHub authentication or even an internet connection?
httptest2 is specifically designed to test httr2 requests:
This package helps with writing tests for packages that use httr2
Unfortunately, gh uses httr:
Imports:
cli (>= 3.0.1),
gitcreds,
httr (>= 1.2),
ini,
jsonlite
This means that you can't directly use httptest2 with gh.
However, using gh source code, you can extract the parameters of the GET request sent to httr by gh:
gh_get <- function(endpoint, ..., per_page = NULL, .token = NULL, .destfile = NULL,
.overwrite = FALSE, .api_url = NULL, .method = "GET",
.limit = NULL, .accept = "application/vnd.github.v3+json",
.send_headers = NULL, .progress = TRUE, .params = list()) {
params <- c(list(...), .params)
params <- gh:::drop_named_nulls(params)
if (is.null(per_page)) {
if (!is.null(.limit)) {
per_page <- max(min(.limit, 100), 1)
}
}
if (!is.null(per_page)) {
params <- c(params, list(per_page = per_page))
}
req <- gh:::gh_build_request(
endpoint = endpoint, params = params,
token = .token, destfile = .destfile,
overwrite = .overwrite, accept = .accept,
send_headers = .send_headers,
api_url = .api_url, method = .method
)
req
}
req <- gh_get("GET /repos/r-lib/gh")
req
#$method
#[1] "GET"
#$url
#[1] "https://api.github.com/repos/r-lib/gh"
#$headers
# User-Agent Accept
# "https://github.com/r-lib/gh" "application/vnd.github.v3+json"
#$query
#NULL
#$body
#NULL
#$dest
#<request>
#Output: write_memory
This allows with the example you provided to use httr2 to send the same request :
library(httr2)
resp_httr2 <- request(base_url=req$url) %>%
req_perform() %>%
resp_body_json()
If you are mainly interested in json content, the results are the same, only the attributes differ :
resp_gh <- gh::gh("GET /repos/r-lib/gh")
all.equal(resp_gh,resp_httr2,check.attributes=FALSE)
#[1] TRUE
If you want to use httptest2, switching to httr2 would work:
with_mock_dir("gh", {
test_that("api works", {
resp <- request(base_url=req$url) %>%
req_perform() %>%
resp_body_json()
expect_equal(resp$full_name,"r-lib/gh")})
})
#Test passed 🎉
#[1] TRUE
Offline testing now works because gh\api.github.com directory was created by httptest2.
Maybe you can take inspiration from tests/testthat/test-mock-repos.R
res <- gh(
TMPL("/repos/{owner}/{repo}"),
owner = "gh-testing",
repo = test_repo,
.token = tt()
)
expect_equal(res$name, test_repo)
expect_equal(res$description, "Test repo for gh")
expect_equal(res$homepage, "https://github.com/r-lib/gh")
expect_false(res$private)
expect_false(res$has_issues)
expect_false(res$has_wiki)
A GET method would not create any directory.

How to attach two files when sending message to SMTP Server (emayili+Outlook)

I have been setting the emayili package to send email with two attached files from my Outlook account, but so far I have been unable to do it.
The code is as following (with emails and passwords replaced with 'aaa' and 'bbb' for privacy/security):
email <- envelope(
from = "aaa#domain.com",
to = "bbb#domain.com",
subject = subject,
html = body) %>%
attachment('filename1.xlsx') %>%
attachment('filename2.xlsx')
smtp <- server(host = "smtp.mailtrap.io",
port = 587,
username = "********",
password = "*********")
smtp(email, verbose = TRUE)
When I run the code, I get the following result:
> smtp(email, verbose = TRUE)
Sending email to smtp.office365.com:587/.
Error: Request failed after 5 attempts
Run `rlang::last_error()` to see where the error occurred.
In addition: Warning messages:
1: In smtp(email, verbose = TUE) :
​ restarting interrupted promise evaluation
2: In f(...) : restarting interrupted promise evaluation
3: In f(...) : restarting interrupted promise evaluation
4: In f(...) : restarting interrupted promise evaluation
5: In f(...) : restarting interrupted promise evaluation
Any idea what is going wrong?
Also try to use library(Microsoft365R)
outl <- get_personal_outlook()
#your code
# using emayili to create an email with attachments
ey_email <- emayili::envelope(
text="Hello from emayili",
to="user#example.com",
subject="example emayili email") %>%
emayili::attachment("mydocument.docx") %>%
emayili::attachment("mydata.xlsx")
outl$create_email(ey_email)
#your code
Full manual you can find there

unable to get sen2r function working, some arguments missing?

I am trying to use to sen2r() function (Package sen2r_1.3.2) with default parameters but getting the following error:
Error in paste(c(...), collapse = sep) : argument is missing, with no default.
I know the error wants me to fill in some parameters, but the source manual clearly says that the default should work, and the parameters can be set subsequently upon launching the GUI.
Using the s2_gui() launches the shiny app, but keeps hanging when I try to "Save and Close"
R version 3.6.3 (2020-02-29)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 18.04.4 LTS
Also, can someone with a 'higher reputation' please create a sen2r tag, for easier subsequent communications?
Here is the traceback...
sen2r()
Error in paste(c(...), collapse = sep) :
argument is missing, with no default
> traceback()
7: paste(c(...), collapse = sep)
6: strsplit(paste(c(...), collapse = sep), "\n")
5: unlist(strsplit(paste(c(...), collapse = sep), "\n"))
4: strwrap(unlist(strsplit(paste(c(...), collapse = sep), "\n")),
width = width, indent = indent, exdent = exdent, prefix = prefix,
initial = initial)
3: print_message(type = "waiting", "It seems you are running this package for the first time. ",
"Do you want to verify/install the required dependencies using a GUI (otherwise, an\n automatic check will be performed)? (y/n) ",
)
2: .sen2r(param_list = param_list, pm_arg_passed = pm_arg_passed,
gui = gui, preprocess = preprocess, s2_levels = s2_levels,
sel_sensor = sel_sensor, online = online, order_lta = order_lta,
apihub = apihub, downloader = downloader, overwrite_safe = overwrite_safe,
rm_safe = rm_safe, step_atmcorr = step_atmcorr, sen2cor_use_dem = sen2cor_use_dem,
sen2cor_gipp = sen2cor_gipp, max_cloud_safe = max_cloud_safe,
timewindow = timewindow, timeperiod = timeperiod, extent = extent,
extent_name = extent_name, s2tiles_selected = s2tiles_selected,
s2orbits_selected = s2orbits_selected, list_prods = list_prods,
list_rgb = list_rgb, list_indices = list_indices, index_source = index_source,
rgb_ranges = rgb_ranges, mask_type = mask_type, max_mask = max_mask,
mask_smooth = mask_smooth, mask_buffer = mask_buffer, clip_on_extent = clip_on_extent,
extent_as_mask = extent_as_mask, reference_path = reference_path,
res = res, res_s2 = res_s2, unit = unit, proj = proj, resampling = resampling,
resampling_scl = resampling_scl, outformat = outformat, rgb_outformat = rgb_outformat,
index_datatype = index_datatype, compression = compression,
rgb_compression = rgb_compression, overwrite = overwrite,
path_l1c = path_l1c, path_l2a = path_l2a, path_tiles = path_tiles,
path_merged = path_merged, path_out = path_out, path_rgb = path_rgb,
path_indices = path_indices, path_subdirs = path_subdirs,
thumbnails = thumbnails, parallel = parallel, processing_order = processing_order,
use_python = use_python, tmpdir = tmpdir, rmtmp = rmtmp,
log = log, globenv = sen2r_env, .only_list_names = FALSE)
1: sen2r()
I ran s2_gui() as is...no parameters specified. But i am running the dependency check now, I suspect that should clear things up even for the GUI.
This error was due to a code bug, which was fixed (see the GitHub issue 292).
Until the sen2r CRAN version will be updated, the bug can be:
solved installling the sen2r GitHub version (remotes::install_github("ranghetti/sen2r")), or
bypassed launching check_gdal() before running sen2r().
This is a bug in the original code.
In the traceback that you provided, it included:
3: print_message(type = "waiting", "It seems you are running this package for the first time. ",
"Do you want to verify/install the required dependencies using a GUI (otherwise, an\n automatic check will be performed)? (y/n) ",
)
Notably, I'll truncate most of the strings:
3: print_message(type = "waiting", "It seems ... time. ",
"Do you ... performed)? (y/n) ",
) # ^-- extra comma, invalid R syntax
Notice how it ends with a comma and then a right-paren? Yup, that's a syntax error in R. (This has been submitted as issue 292 on the original repo.)

Trouble using the r package (random)

I want to generate random string and have installed the random package.
However, I couldn't run my code and received this error:
Error in url(urltxt, ..., method = "libcurl") : cannot open connection
In addition: Warning message: In url(urltxt, ..., method = "libcurl")
: URL 'https://www.random.org/strings/?num=7&len=6&digits=on&upperalpha=on&loweralpha=off&unique=on&format=plain&rnd=new'
: status was 'SSL connect error'
Here's my code:
library("random")
String<-randomStrings(n=7, len = 6, digits = TRUE, upperalpha = TRUE, loweralpha = FALSE, unique = TRUE, check = FALSE)
Anybody knows what's the source of this error?

WriteWebGL in R

I am trying to export a 3D plot that was made using the plot3d function from the rgl package using the WrtieWebGL function for web viewing. I don't really understand the example in the WriteWebGL documentation because it saves to a temp directory. Could someone please provide an example on how to use this function and/or point out my error(s) with usage? Thank you for your time and help.
attach(dataset1)
plot3d(Days_Prep_Time,ACT_Score,Coffee,size=5,col="blue", type="s")
writeWebGL(dir = "webGL", filename = file.path(dir, "index.html"),
template = system.file(file.path("WebGL", "template.html"), package = "rgl",
snapshot = TRUE, font = "Arial")
I get the following error:
Error in writeWebGL(dir = "webGL", filename = file.path(dir, "index.html"), :
template ‘’ does not contain %WebGL%
In addition: Warning message:
In file(con, "r") :
file("") only supports open = "w+" and open = "w+b": using the former
You are adding the snapshot and font parameters to the system.file function, not the writeWebGL function:
writeWebGL(dir = "webGL", filename = file.path(dir, "index.html"),
template = system.file(file.path("WebGL", "template.html"), package = "rgl"),
snapshot = TRUE, font = "Arial")
In particular, note that
system.file(file.path("WebGL", "template.html"), package = "rgl")
returns the correct path from console, whereas
system.file(file.path("WebGL", "template.html"), package = "rgl", snapshot = TRUE, font = "Arial")
returns "".

Resources