-
Notifications
You must be signed in to change notification settings - Fork 1
/
util.R
65 lines (52 loc) · 1.4 KB
/
util.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
ptr_is_valid <- function(ptr) {
stopifnot(methods::is(ptr, "externalptr"))
!.Call(ptr_is_null, ptr)
}
validate_parsed_content <- function(env) {
if (ptr_is_valid(env$parsed_html$node)) return(env)
parsed_html <- xml2::read_html(env$raw_html, encoding = env$encoding)
env$parsed_html <- parsed_html
tags_in_doc <- sort(unique(xml2::xml_name(xml2::xml_find_all(parsed_html, "//*"))))
set_names(
lapply(tags_in_doc, function(tag) {
tag <- (if (tag == "html") "//html" else sprintf(".//%s", tag))
xml2::xml_find_all(parsed_html, tag)
}),
tags_in_doc
) -> env[["tag"]]
lapply(env[["tag"]], function(.x) {
class(.x) <- c("reapr_taglist", class(.x))
.x
}) -> env[["tag"]]
env
}
lock_environment <- function(env, exclude="") {
for (nm in ls(env)) {
if (!(nm %in% exclude)) lockBinding(as.name(nm), env)
}
lockEnvironment(env)
invisible(env)
}
set_names <- function(x, nms) {
names(x) <- nms
x
}
`%na%` <- function(a, b) {
if (is.na(a)) b else a
}
`%||%` <- function(a, b) {
if (is.null(a)) b else a
}
bytes <- function (x, digits = 3, ...) {
power <- min(floor(log(abs(x), 1000)), 4)
if (power < 1) {
unit <- "B"
}
else {
unit <- c("kB", "MB", "GB", "TB")[[power]]
x <- x/(1000^power)
}
formatted <- format(signif(x, digits = digits), big.mark = ",",
scientific = FALSE)
paste0(formatted, " ", unit)
}