Skip to content

Instantly share code, notes, and snippets.

View cosi1's full-sized avatar
🐾
I ❤️ R

Paweł Piątkowski cosi1

🐾
I ❤️ R
View GitHub Profile
@cosi1
cosi1 / vterm.fish
Last active June 1, 2021 17:05
`find_file` function for Emacs' vterm and fish shell
function find_file
set -q argv[1]; or set argv[1] "."
vterm_cmd find-file (realpath "$argv")
end
function vterm_cmd --description 'Run an Emacs command among the ones been defined in vterm-eval-cmds.'
set -l vterm_elisp ()
for arg in $argv
set -a vterm_elisp (printf '"%s" ' (string replace -a -r '([\\\\"])' '\\\\\\\\$1' $arg))
end
@cosi1
cosi1 / static.R
Last active November 20, 2022 16:57
Static-type function operator
# Static-type function operator
# Usage:
# int_mult = integer %:% function(integer..x, integer..y) { x * y }
`%:%` = function(..type, ..fun) {
..arg_types = get_arg_types(fun = ..fun)
..fun = untype_args(fun = ..fun, types = ..arg_types)
function(...) {
..args = match.call(..fun)[-1]
validate_args(args = ..args, types = ..arg_types)
..res = eval(..fun(...), envir = environment(..fun))
@cosi1
cosi1 / range_if.R
Created February 20, 2019 19:22
Range matching in R
range_if = function(.., ..., default = NULL) {
for (expr in list(...)) {
s = substitute(expr)
if (length(s) < 3 || s[[1]] != as.symbol("~")) {
stop("Invalid argument. Use `condition ~ expression`")
}
if (isTRUE(eval(s[[2]]))) return(eval(s[[3]]))
}
default
}
@cosi1
cosi1 / toggle.R
Created September 8, 2018 19:17
Feature toggles in R
`%||%` = function(x, y) {
if (!identical(x, FALSE)) x else y
}
toggle = function(fun, env_var = "env", dev_env = "dev") {
if (Sys.getenv(env_var) == dev_env) fun else FALSE
}
# Imports a namespace under an alias
# (equivalent of Python's `import ... as ...`)
importAs = function(namespace, alias) {
namespace::registerNamespace(name = alias, env = asNamespace(namespace))
}
# Imports function(s) from a namespace (including unexported functions)
# to the global namespace
# (equivalent of Python's `import ... from ...`)
importFrom = function(namespace, functions) {
@cosi1
cosi1 / hex_to_rgb.R
Last active September 13, 2016 09:48
Converts a list of colors in hexadecimal format (#RRGGBB) to a list of PyMOL's `set_color` commands
library(magrittr)
hex_to_rgb = function(color_list) {
mapply(function(clr, i) {
clr %>%
substring(c(2, 4, 6), c(3, 5, 7)) %>%
paste0("0x", .) %>%
strtoi() %>%
`/`(256) %>%
paste(collapse = ",") %>%
@cosi1
cosi1 / pipe.R
Last active August 18, 2016 11:22
Minimalist pipe operator for R
`%>%` = function(par, fun) {
s = substitute(fun)
fun.name = s[[1]]
fun.args = as.list(s)
fun.args[[1]] = par
do.call(deparse(fun.name), fun.args)
}