4 Week 4
Topics: Functions and sampling
This week's topics are functions and sampling, the latter including a cursory treatment of loops and bootstrapping.
4.1 Environments
Functions exist in environments
, which are "frames" or collections containing objects including variables, functions, etc.). There is a global environment (.GlobalEnv
) that contains all of the data, functions, in the current R session. Those objects can be enumerated with the ls()
function.
The reason environments are mentioned at this time is because functions instantiate environments that exist while the function is running. More on this in a bit....
4.2 Functions
Functions are sets of statements in R that are grouped together to perform a specific task or set of tasks. Functions are either built in, included in packages, or user-defined. Functions are used mainly to simplify running a series of individual commands or functions, for situations where the same process will need to be run multiple times on different inputs, or when control structures are needed (e.g., looping, logical branching).
4.2.1 Function Components
The different parts of a function are:
- (Usually) Name: This is the actual name of the function. It is stored in an R environment as an object with this name.
- (Optional) Arguments: Arguments specify the inputs or options to the function. When a function is invoked, you pass a value to the argument. Arguments are optional; that is, a function may contain no arguments. Also arguments can have default values.
- Body: The function body contains a collection of statements that defines what the function does.
- Return value: The return value of a function is the last expression in the function body to be evaluated.
Another important concept for functions is environments.
<IP_ADDRESS> Name
Most functions are created with code of the form
function_name <- function(argument(s)){
statement(s)
}
For example, to square a vector of numerical values:
f_square <- function(x){
x^2
}
the function name is f_square
.
Some functions are not named, and are referred to as "anonymous" functions. For example, functions can be used within the apply
family of functions. Here is an oprationalized example.
# create a list of three vectors of random numbers of different random lengths
# set.seed() makes the random process reproducible.
set.seed(10)
# vector lengths
v.len <- rnorm(n = 3, mean = 30, sd = 10) %>% round(0)
# make the random vectors
set.seed(5)
v1 <- rnorm(n = v.len[1])
set.seed(3)
v2 <- rnorm(n = v.len[2])
set.seed(6)
v3 <- rnorm(n = v.len[3])
# create the list
L <- list(v1, v2, v3)
# get the first value from each vector in the list
lapply(X = L, FUN = function(x) {x[1]})
## [[1]]
## [1] -0.8408555
##
## [[2]]
## [1] -0.9619334
##
## [[3]]
## [1] 0.269606
The last line of the code chunk is:
lapply(X = L, FUN = function(x) {x[1]})
in which the body of the function is x[1]
, i.e., obtain the first element of a vector. But the function itself is not named, and hence "anonymous."
<IP_ADDRESS> Arguments
Most functions require arguments. Arguments are used to instantiate variables within the function's environment that can be used later in the body of the function. Each argument is named, and the name is used within the function as a local variable within the function's environment.
Following our example from above, f_square
takes an argument named "x" that is a numeric vector.
Here, let's modify the function to demonstrate that within the environment of the function, x
is a variable:
f_square_2 <- function(x){
message("input:")
print(x)
message("output:")
x^2
}
f_square_2(c(1,2,3))
## input:
## [1] 1 2 3
## output:
## [1] 1 4 9
We can try running the function using different (or no) arguments:
Here, using a vector of a single NA numeric
f_square(as.numeric(NA))
## [1] NA
... or a vector that contains a numeric NA:
f_square(c(1, 2, NA))
## [1] 1 4 NA
... or a null:
f_square(NULL)
## numeric(0)
... or a vector containing a null:
f_square(c(1, 2, NULL))
## [1] 1 4
... or with no argument at all:
f_square()
## Error in f_square() : argument "x" is missing, with no default
Some functions do not require arguments, e.g., to get the current date or time:
Sys.Date()
## [1] "2021-03-06"
Sys.time()
## [1] "2021-03-06 12:23:29 PST"
... and if we try to use an argument we get an error:
Sys.Date(1)
## Error in Sys.Date(1) : unused argument (1)
<IP_ADDRESS>.1 Default values for arguments
If you want an argument to have a default value, it is specified in the listed arguments in the form argument = value
. Following our previous f_square_2()
function, we can modify to print the input based on the logical argument verbose
:
f_square_3 <- function(x, verbose = FALSE){
# only run the next lines if verbose is true
if(verbose){
message("input:")
print(x)
message("output:")
}
x^2
}
Here we run with the default verbose
option (FALSE
):
f_square_3(x = c(1, 2, 3))
## [1] 1 4 9
... and with verbose = TRUE
:
f_square_3(x = c(1, 2, 3), verbose = TRUE)
## input:
## [1] 1 2 3
## output:
## [1] 1 4 9
A more meaningful example demonstrates stratification of counts into intensity bins using accelerometry data. We will be using accelerometry from one day's data from one subject in a study.
The cut points for accelerometry were identified at 0, 2690, 6167, and 9642 counts per minute, from Sasaki et al. (2011).
__Sasaki JE, John D, Freedson PS. Validation and comparison of ActiGraph activity monitors. J Sci Med Sport. 2011;14(5):411-416. doi:10.1016/j.jsams.2011.04.003__
The variable vm3
is the vector magnitude measured with the accelerometer for each minute. Data: accelerometry.csv.
acc <- read.csv("files/accelerometry.csv")
head(acc)
## time_acc vm3
## 1 2018-09-13 02:59:00-07 0
## 2 2018-09-13 02:58:00-07 0
## 3 2018-09-13 02:57:00-07 0
## 4 2018-09-13 02:56:00-07 0
## 5 2018-09-13 02:55:00-07 0
## 6 2018-09-13 02:54:00-07 0
The following function codes intensity by the aforementioned cut points by default and using default labels:
f_acc_intensity <- function(x,
cuts = c(-Inf, 2690, 6167, 9642, Inf),
labels = c("sedentary/low", "moderate", "vigorous", "very vigorous")){
cut(x = acc$vm3, breaks = cuts, labels = labels)
}
... and when run with the defaults to tabulate the minutes spent in different PA levels
acc$intens_default <- f_acc_intensity(acc$vm3)
table(acc$intens_default)
##
## sedentary/low moderate vigorous very vigorous
## 1435 4 1 0
But we could run this with different thresholds and levels, where SPLA = "sedentary/low physical activity" and MVPA = "moderate-to-very vigorous physical activity):
acc$intens_2lev <- f_acc_intensity(x = acc$vm3,
cuts = c(-Inf, 2690, Inf),
labels = c("SLPA", "MVVPA"))
table(acc$intens_2lev)
##
## SLPA MVVPA
## 1435 5
<IP_ADDRESS>.2 The ...
argument
When functions do not have a known a priori number or set of arguments, or when a large number of arguments is to be passed to another function the ...
argument is used. We will not cover this but you are encouraged to read more: How to Use the Dots Argument in R; The three-dots construct in R.
<IP_ADDRESS> Body
The function's body contains all of the code to perform the purpose of the function. Following our initial example, the body of the function is simply
x^2
The body can be as simple or complicated as it needs to be in order to achieve the desired result.
<IP_ADDRESS> Return value
The return value is either the last evaluated expression in the function or an object specified using the return()
function.
In our original f_square()
function, the return value is x^2
since no other return()
value was specified, e.g., for a vector of one element:
f_square <- function(x){
x^2
}
f_square(3)
## [1] 9
or a vector with multiple elements:
f_square(c(1,2,3))
## [1] 1 4 9
An simple example of explicitly specifying return values is shown in this numerical comparison function:
f_compare <- function(x, y){
# either missing?
if(nargs() != 2)
return("invalid number of arguments")
# numeric?
if(!is.numeric(x) | !is.numeric(y)){
return(sprintf("%s or %s is not numeric.", x, y))
}
# comparisons follow
if(x > y){
return(sprintf("%s is greater than %s", x, y))
}
if(x < y) {
return(sprintf("%s is less than %s", x, y))
}
if(x == y){
return(sprintf("%s equals %s", x, y))
}
}
If you want to handle an expected error, you can print an informative message and use return(invisible())
, which returns nothing at all (whereas return()
results in a NULL
) e.g., here without invisible()
:
f_readfile <- function(fname){
if(!file.exists(fname)){
warning(paste(fname, "does not exist!"))
return()
} else {
read.csv(fname)
}
}
f_readfile("foobar.txt")
## Warning in f_readfile("foobar.txt"): foobar.txt does not exist!
## NULL
... and with invisible()
:
f_readfile <- function(fname){
if(!file.exists(fname)){
warning(paste(fname, "does not exist!"))
return(invisible())
} else {
read.csv(fname)
}
}
f_readfile("foobar.txt")
## Warning in f_readfile("foobar.txt"): foobar.txt does not exist!
<IP_ADDRESS> Function environments
As mentioned before, functions instantiate environments that exist only while the function is being evaluated. This means that functions can include named variables that have the same name as a variable in a different environment. For example here is a function that only lists what objects are in the local and global environments:
# declare a few variables
x <- 1
y <- "hello"
# a simple function
f <- function(x){
# create a local variable
y <- x + 2
# another function inside this function
g <- function(x){
x * 3
}
# what variables are in this environment?
print("----------")
print("objects in this function's environment:")
print(ls())
# what is in the global env?
print("----------")
print("objects in the global environment:")
print(ls(envir = .GlobalEnv))
# return the output of the function
print("----------")
y
}
f(1)
## [1] "----------"
## [1] "objects in this function's environment:"
## [1] "g" "x" "y"
## [1] "----------"
## [1] "objects in the global environment:"
## [1] "a" "acc" "age_jane" "age_john"
## [5] "ages" "bins" "bins2" "BMI"
## [9] "boston_zip" "census_vars" "ci_95" "cmd"
## [13] "csvfname" "csvsize" "ctdat" "d"
## [17] "dat" "dat_1" "dat_sub" "dat_sub_sel"
## [21] "dtafname" "excel_fname" "f" "F"
## [25] "f_acc_intensity" "f_compare" "f_readfile" "f_square"
## [29] "f_square_2" "f_square_3" "figure_nums" "fname"
## [33] "fnames" "foo" "fstfname" "fstsize"
## [37] "g" "i" "inc" "income"
## [41] "income_factor" "iris_summary" "ja" "jo"
## [45] "l" "L" "labels" "m"
## [49] "m1" "m2" "m3" "my_zip"
## [53] "mystr" "mytext" "myUrl" "n"
## [57] "n_fnames" "normvec1000" "p" "pal"
## [61] "pal2" "pb" "pop" "s"
## [65] "sqlc" "states_5" "subjects" "sum_health_white_afram"
## [69] "t" "tabhealth_afram" "tabhealth_white" "table_nums"
## [73] "tbs" "tempdirfiles" "tmp" "tmpdir"
## [77] "txt" "urls" "v" "v.len"
## [81] "v1" "v2" "v3" "vals"
## [85] "x" "X" "xlsclip" "y"
## [89] "zip_bad" "zip_good" "zipfile"
## [1] "----------"
## [1] 3
Once the function completes, all objects in its local environment are purged. If you are running a complicated function that creates intermediate values that you want to examine for troubleshooting, this kind of thing can be done, to assign a variable with a specific value to a different environment created specifically for examining the intermediate products of the function:
# create an environment for holding intermediate objects created in the function run
foo <- new.env()
g <- function(x){
# code for a bunch of complicated operations
# ...
# generates an intermediate data frame named "bar"
bar <- head(iris)
# save to the other env
assign(x = "bar", value = bar, envir = foo)
# more code to do more complicated stuff
# ...
foobar <- head(cars)
# assign this too
assign(x = "foobar", value = foobar, envir = foo)
# yet more complicated stuff here
# ...
}
When the function runs, the objects bar
and foobar
are placed in the foo
environment. We can examine those:
# run the function
g()
# what is in envornment "foo"?
ls(envir = foo)
## [1] "bar" "foobar"
And we can view their values:
print(foo$bar)
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1 5.1 3.5 1.4 0.2 setosa
## 2 4.9 3.0 1.4 0.2 setosa
## 3 4.7 3.2 1.3 0.2 setosa
## 4 4.6 3.1 1.5 0.2 setosa
## 5 5.0 3.6 1.4 0.2 setosa
## 6 5.4 3.9 1.7 0.4 setosa
print(foo$foobar)
## speed dist
## 1 4 2
## 2 4 10
## 3 7 4
## 4 7 22
## 5 8 16
## 6 9 10
4.3 Sampling
The general topic of sampling is far greater than what we can cover in this course. However, a few examples may be helpful for students who have little experience in sampling.
The main R function for sampling is sample()
, which draws a random sample from a vector or data frame. Options for sample()
include the size of the sample, whether or not to replace sampled individuals to the pool, and a probability weight of the same length (or number of rows) as the population from which the sample is drawn.
4.3.1 Sampling with replacement
Sampling with replacement is similar to rolling a die. Each roll of the die has a 1/6 probability of coming up with each value. For example:
# create a vector to represent the faces of a die
d <- 1:6
# now make a sample of 100,000 rolls of the die
s <- sample(x = d, size = 100000, replace = TRUE)
# tabulate the result
(tbs <- table(s))
## s
## 1 2 3 4 5 6
## 16391 16931 16557 16728 16609 16784
# proportions
(prop.table(tbs))
## s
## 1 2 3 4 5 6
## 0.16391 0.16931 0.16557 0.16728 0.16609 0.16784
The probability of rolling two of the same number in a row is 1/6 \(\times\) 1/6, or \(\approx\) 0.028
4.3.2 Sampling without replacement
Sampling without replacement removes from the population the individual that was sampled. For example, the probability of selecting an ace from a whole deck of cards is 4/52, or \(\approx\) 0.077. If we drew once from the deck and returned the card back to the deck to draw again, both samples would be independent. The probability of drawing two aces would be 4/52 \(\times\) 4/52, or \(\approx\) 0.0059. That is an example of sampling with replacement.
Performing the same sample without replacement, i.e., finding an ace, removing it, and then sampling again would have a probability of drawing two aces being 4/52 \(\times\) 3/51, or \(\approx\) 0.0045.
For a population of sufficient size relative to the sample, sampling with or without replacement will lead to nearly identical results.
Let's use an example of a population of 50,000 persons, where 30,000 are female and 20,000 are male. If we were to sample two persons with replacement, the probability that they would both be female would be 30000/50000 \(\times\) 30000/50000, or 0.36.
If we sample without replacement, the probability of selecting a female in the first sample of one would be 30000/50000, and the second sample of 1 would have a probability of selecting a female 29999/49999, with a joint probability of \(\approx\) 0.359995.
4.3.3 Bootstrapping
Bootstrapping is used to estimate the characteristics of a population by repeating a large number of random samples (with replacement) and then calculating summary statistics on the set of samples. The reason replacement is used is that each sample represents a "snapshot" of the population. As the number of samples increases, the summary continues to approach the true population characteristics.
We will use a simple example from our previously created hypothetical population. If we had no idea what the male/female split was, we could generate a large number of small-is samples and the take the mean.
Here we will use an R loop. A loop is constructed using the form
for (element in set){
do something
}
A few simple examples follow.
Print each letter in the first 5 letters of the alphabet. In this example, the iterated element is a letter. The built in vector letters
is used:
for (i in head(letters, 5)){
print(i)
}
## [1] "a"
## [1] "b"
## [1] "c"
## [1] "d"
## [1] "e"
A similar approach, but using a numerical index:
states_5 <- head(state.name, 5)
for (i in 1:length(states_5)){
s <- states_5[i]
print(s)
}
## [1] "Alabama"
## [1] "Alaska"
## [1] "Arizona"
## [1] "Arkansas"
## [1] "California"
The bootstrap will use 5,000 samples of size 100 from our hypothetical population to estimate the proportion of females.
# create the population
# 1 indicates female and 0 indicates male
pop <- c(rep(1, 5e4 * 3 / 5), rep(0, 5e4 * 2 / 5))
# initialize a vector
F <- NULL
# run the bootstrap
for (i in seq(from = 1, to = 5000, by = 1)){
# sample once
s <- sample(x = pop, size = 100, replace = TRUE)
# calculate percent female
p <- sum(s) / length(s)
# concatenate the result with the running result
F <- c(F, p)
}
# mean and standard deviation of the bootstrap
mean(F)
## [1] 0.600582
sd(F)
## [1] 0.04883276
Using the bootstrap results, we can estimate the 95% confidence interval around the mean using the Rmisc::CI()
function, and make a density plot showing the mean and the confidence interval.
# 95% CI
ci_95 <- Rmisc::CI(x = F, ci = 0.95)
# plot with 95 % CI
plot(density(F), main = "density plot of bootstrap")
abline(v = ci_95, col=c(2,1,2))
If we already had an enumeration of the population, this method would be unnecessary. However, most survey-derived data are generated from samples. If the sample is representative of the underlying population, the sample can be considered an acceptable proxy.
Source code for this document
# Week 4 {#week4}
```{r, echo=FALSE, warning=FALSE, message=FALSE}
library(tidyverse)
library(magrittr)
library(knitr)
library(kableExtra)
library(readstata13)
```

Topics: Functions and sampling

This week's topics are functions and sampling, the latter including a cursory treatment of loops and bootstrapping.
## Environments
Functions exist in `environments`, which are "frames" or collections containing objects including variables, functions, etc.). There is a global environment (`.GlobalEnv`) that contains all of the data, functions, in the current R session. Those objects can be enumerated with the `ls()` function.
The reason environments are mentioned at this time is because functions instantiate environments that exist while the function is running. More on this in a bit....
## Functions
Functions are sets of statements in R that are grouped together to perform a specific task or set of tasks. Functions are either built in, included in packages, or user-defined. Functions are used mainly to simplify running a series of individual commands or functions, for situations where the same process will need to be run multiple times on different inputs, or when control structures are needed (e.g., looping, logical branching).
### Function Components
The different parts of a function are:
1. (Usually) Name: This is the actual name of the function. It is stored in an R environment as an object with this name.
1. (Optional) Arguments: Arguments specify the inputs or options to the function. When a function is invoked, you pass a value to the argument. Arguments are optional; that is, a function may contain no arguments. Also arguments can have default values.
1. Body: The function body contains a collection of statements that defines what the function does.
1. Return value: The return value of a function is the last expression in the function body to be evaluated.
Another important concept for functions is environments.
#### Name
Most functions are created with code of the form
```
function_name <- function(argument(s)){
statement(s)
}
```
For example, to square a vector of numerical values:
```{r}
f_square <- function(x){
x^2
}
```
the function name is `f_square`.
Some functions are not named, and are referred to as "anonymous" functions. For example, functions can be used within the `apply` family of functions. Here is an oprationalized example.
```{r}
# create a list of three vectors of random numbers of different random lengths
# set.seed() makes the random process reproducible.
set.seed(10)
# vector lengths
v.len <- rnorm(n = 3, mean = 30, sd = 10) %>% round(0)
# make the random vectors
set.seed(5)
v1 <- rnorm(n = v.len[1])
set.seed(3)
v2 <- rnorm(n = v.len[2])
set.seed(6)
v3 <- rnorm(n = v.len[3])
# create the list
L <- list(v1, v2, v3)
# get the first value from each vector in the list
lapply(X = L, FUN = function(x) {x[1]})
```
The last line of the code chunk is:
```
lapply(X = L, FUN = function(x) {x[1]})
```
in which the body of the function is `x[1]`, i.e., obtain the first element of a vector. But the function itself is not named, and hence "anonymous."
#### Arguments
Most functions require arguments. Arguments are used to instantiate variables within the function's environment that can be used later in the body of the function. Each argument is named, and the name is used within the function as a local variable within the function's environment.
Following our example from above, `f_square` takes an argument named "x" that is a numeric vector.
Here, let's modify the function to demonstrate that within the environment of the function, `x` is a variable:
```{r}
f_square_2 <- function(x){
message("input:")
print(x)
message("output:")
x^2
}
f_square_2(c(1,2,3))
```
We can try running the function using different (or no) arguments:
Here, using a vector of a single NA numeric
```{r}
f_square(as.numeric(NA))
```
... or a vector that contains a numeric NA:
```{r}
f_square(c(1, 2, NA))
```
... or a null:
```{r}
f_square(NULL)
```
... or a vector containing a null:
```{r}
f_square(c(1, 2, NULL))
```
... or with no argument at all:
```
f_square()
```

```
## Error in f_square() : argument "x" is missing, with no default
```

Some functions do not require arguments, e.g., to get the current date or time:
```{r}
Sys.Date()
Sys.time()
```
... and if we try to use an argument we get an error:
```
Sys.Date(1)
```

```
## Error in Sys.Date(1) : unused argument (1)
```

##### Default values for arguments
If you want an argument to have a default value, it is specified in the listed arguments in the form `argument = value`. Following our previous `f_square_2()` function, we can modify to print the input based on the logical argument `verbose`:
```{r, collapse=TRUE}
f_square_3 <- function(x, verbose = FALSE){
# only run the next lines if verbose is true
if(verbose){
message("input:")
print(x)
message("output:")
}
x^2
}
```
Here we run with the default `verbose` option (`FALSE`):
```{r}
f_square_3(x = c(1, 2, 3))
```
... and with `verbose = TRUE`:
```{r}
f_square_3(x = c(1, 2, 3), verbose = TRUE)
```
A more meaningful example demonstrates stratification of counts into intensity bins using accelerometry data. We will be using accelerometry from one day's data from one subject in a study.
The cut points for accelerometry were identified at 0, 2690, 6167, and 9642 counts per minute, from Sasaki et al. (2011).
__Sasaki JE, John D, Freedson PS. Validation and comparison of ActiGraph activity monitors. J Sci Med Sport. 2011;14(5):411-416. doi:10.1016/j.jsams.2011.04.003__
The variable `vm3` is the vector magnitude measured with the accelerometer for each minute. Data: [accelerometry.csv](files/accelerometry.csv).
```{r}
acc <- read.csv("files/accelerometry.csv")
head(acc)
```
The following function codes intensity by the aforementioned cut points by default and using default labels:
```{r}
f_acc_intensity <- function(x,
cuts = c(-Inf, 2690, 6167, 9642, Inf),
labels = c("sedentary/low", "moderate", "vigorous", "very vigorous")){
cut(x = acc$vm3, breaks = cuts, labels = labels)
}
```
... and when run with the defaults to tabulate the minutes spent in different PA levels
```{r}
acc$intens_default <- f_acc_intensity(acc$vm3)
table(acc$intens_default)
```
But we could run this with different thresholds and levels, where SPLA = "sedentary/low physical activity" and MVPA = "moderate-to-very vigorous physical activity):
```{r}
acc$intens_2lev <- f_acc_intensity(x = acc$vm3,
cuts = c(-Inf, 2690, Inf),
labels = c("SLPA", "MVVPA"))
table(acc$intens_2lev)
```
##### The `...` argument
When functions do not have a known _a priori_ number or set of arguments, or when a large number of arguments is to be passed to another function the `...` argument is used. We will not cover this but you are encouraged to read more: [How to Use the Dots Argument in R](https://www.dummies.com/programming/r/how-to-use-the-dots-argument-in-r/); [The three-dots construct in R](https://www.r-bloggers.com/2013/01/the-three-dots-construct-in-r/).
#### Body
The function's body contains all of the code to perform the purpose of the function. Following our initial example, the body of the function is simply
```
x^2
```
The body can be as simple or complicated as it needs to be in order to achieve the desired result.
#### Return value
The return value is either the last evaluated expression in the function or an object specified using the `return()` function.
In our original `f_square()` function, the return value is `x^2` since no other `return()` value was specified, e.g., for a vector of one element:
```{r}
f_square <- function(x){
x^2
}
f_square(3)
```
or a vector with multiple elements:
```{r}
f_square(c(1,2,3))
```
An simple example of explicitly specifying return values is shown in this numerical comparison function:
```{r}
f_compare <- function(x, y){
# either missing?
if(nargs() != 2)
return("invalid number of arguments")
# numeric?
if(!is.numeric(x) | !is.numeric(y)){
return(sprintf("%s or %s is not numeric.", x, y))
}
# comparisons follow
if(x > y){
return(sprintf("%s is greater than %s", x, y))
}
if(x < y) {
return(sprintf("%s is less than %s", x, y))
}
if(x == y){
return(sprintf("%s equals %s", x, y))
}
}
```
If you want to handle an expected error, you can print an informative message and use `return(invisible())`, which returns nothing at all (whereas `return()` results in a `NULL`) e.g., here without `invisible()`:
```{r}
f_readfile <- function(fname){
if(!file.exists(fname)){
warning(paste(fname, "does not exist!"))
return()
} else {
read.csv(fname)
}
}
f_readfile("foobar.txt")
```
... and with `invisible()`:
```{r}
f_readfile <- function(fname){
if(!file.exists(fname)){
warning(paste(fname, "does not exist!"))
return(invisible())
} else {
read.csv(fname)
}
}
f_readfile("foobar.txt")
```
#### Function environments
As mentioned before, functions instantiate environments that exist only while the function is being evaluated. This means that functions can include named variables that have the same name as a variable in a different environment. For example here is a function that only lists what objects are in the local and global environments:
```{r}
# declare a few variables
x <- 1
y <- "hello"
# a simple function
f <- function(x){
# create a local variable
y <- x + 2
# another function inside this function
g <- function(x){
x * 3
}
# what variables are in this environment?
print("----------")
print("objects in this function's environment:")
print(ls())
# what is in the global env?
print("----------")
print("objects in the global environment:")
print(ls(envir = .GlobalEnv))
# return the output of the function
print("----------")
y
}
f(1)
```
Once the function completes, all objects in its local environment are purged. If you are running a complicated function that creates intermediate values that you want to examine for troubleshooting, this kind of thing can be done, to assign a variable with a specific value to a different environment created specifically for examining the intermediate products of the function:
```{r}
# create an environment for holding intermediate objects created in the function run
foo <- new.env()
g <- function(x){
# code for a bunch of complicated operations
# ...
# generates an intermediate data frame named "bar"
bar <- head(iris)
# save to the other env
assign(x = "bar", value = bar, envir = foo)
# more code to do more complicated stuff
# ...
foobar <- head(cars)
# assign this too
assign(x = "foobar", value = foobar, envir = foo)
# yet more complicated stuff here
# ...
}
```
When the function runs, the objects `bar` and `foobar` are placed in the `foo` environment. We can examine those:
```{r}
# run the function
g()
# what is in envornment "foo"?
ls(envir = foo)
```
And we can view their values:
```{r}
print(foo$bar)
```
```{r}
print(foo$foobar)
```
## Sampling
The general topic of sampling is far greater than what we can cover in this course. However, a few examples may be helpful for students who have little experience in sampling.
The main R function for sampling is `sample()`, which draws a random sample from a vector or data frame. Options for `sample()` include the size of the sample, whether or not to replace sampled individuals to the pool, and a probability weight of the same length (or number of rows) as the population from which the sample is drawn.
### Sampling with replacement
Sampling with replacement is similar to rolling a die. Each roll of the die has a 1/6 probability of coming up with each value. For example:
```{r}
# create a vector to represent the faces of a die
d <- 1:6
# now make a sample of 100,000 rolls of the die
s <- sample(x = d, size = 100000, replace = TRUE)
# tabulate the result
(tbs <- table(s))
# proportions
(prop.table(tbs))
```
The probability of rolling two of the same number in a row is 1/6 $\times$ 1/6, or $\approx$ 0.028
### Sampling without replacement
Sampling without replacement removes from the population the individual that was sampled. For example, the probability of selecting an ace from a whole deck of cards is 4/52, or $\approx$ 0.077. If we drew once from the deck and returned the card back to the deck to draw again, both samples would be independent. The probability of drawing two aces would be 4/52 $\times$ 4/52, or $\approx$ 0.0059. _That_ is an example of sampling _with_ replacement.
Performing the same sample _without_ replacement, i.e., finding an ace, removing it, and then sampling again would have a probability of drawing two aces being 4/52 $\times$ 3/51, or $\approx$ 0.0045.
For a population of sufficient size relative to the sample, sampling with or without replacement will lead to nearly identical results.
Let's use an example of a population of 50,000 persons, where 30,000 are female and 20,000 are male. If we were to sample two persons with replacement, the probability that they would both be female would be 30000/50000 $\times$ 30000/50000, or 0.36.
If we sample without replacement, the probability of selecting a female in the first sample of one would be 30000/50000, and the second sample of 1 would have a probability of selecting a female 29999/49999, with a joint probability of $\approx$ 0.359995.
### Bootstrapping
Bootstrapping is used to estimate the characteristics of a population by repeating a large number of random samples (with replacement) and then calculating summary statistics on the set of samples. The reason replacement is used is that each sample represents a "snapshot" of the population. As the number of samples increases, the summary continues to approach the true population characteristics.
We will use a simple example from our previously created hypothetical population. If we had no idea what the male/female split was, we could generate a large number of small-is samples and the take the mean.
Here we will use an R loop. A loop is constructed using the form
```
for (element in set){
do something
}
```
A few simple examples follow.
Print each letter in the first 5 letters of the alphabet. In this example, the iterated element is a letter. The built in vector `letters` is used:
```{r}
for (i in head(letters, 5)){
print(i)
}
```
A similar approach, but using a numerical index:
```{r}
states_5 <- head(state.name, 5)
for (i in 1:length(states_5)){
s <- states_5[i]
print(s)
}
```
The bootstrap will use 5,000 samples of size 100 from our hypothetical population to estimate the proportion of females.
```{r}
# create the population
# 1 indicates female and 0 indicates male
pop <- c(rep(1, 5e4 * 3 / 5), rep(0, 5e4 * 2 / 5))
# initialize a vector
F <- NULL
# run the bootstrap
for (i in seq(from = 1, to = 5000, by = 1)){
# sample once
s <- sample(x = pop, size = 100, replace = TRUE)
# calculate percent female
p <- sum(s) / length(s)
# concatenate the result with the running result
F <- c(F, p)
}
# mean and standard deviation of the bootstrap
mean(F)
sd(F)
```
Using the bootstrap results, we can estimate the 95% confidence interval around the mean using the `Rmisc::CI()` function, and make a density plot showing the mean and the confidence interval.
```{r}
# 95% CI
ci_95 <- Rmisc::CI(x = F, ci = 0.95)
# plot with 95 % CI
plot(density(F), main = "density plot of bootstrap")
abline(v = ci_95, col=c(2,1,2))
```
If we already had an enumeration of the population, this method would be unnecessary. However, most survey-derived data are generated from samples. If the sample is representative of the underlying population, the sample can be considered an acceptable proxy.

Source code for this document

[04-week04.Rmd](04-week04.Rmd)
```{r, comment='', echo=FALSE}
cat(readLines("04-week04.Rmd"), sep = '\n')
```


Checks whether the provided export directory could contain a SavedModel.
tf.compat.v1.saved_model.loader.maybe_saved_model_directory
tf.compat.v1.saved_model.maybe_saved_model_directory
tf.compat.v1.saved_model.contains_saved_model(export_dir)
Note that the method does not load any data by itself. If the method returns
false
, the export directory definitely does not contain a SavedModel. If the
method returns true
, the export directory may contain a SavedModel but
provides no guarantee that it can be loaded.
export_dir
: Absolute string path to possible export location. For example,
'/my/foo/model'.True if the export directory contains SavedModel files, False otherwise.


{% extends "mails/messages/activity_base.html" %} {% load i18n %} {% block message%}
{% blocktrans context 'email' %}Your team '{{team_name}}' is no longer participating in the activity '{{title}}'.{% endblocktrans %}


E-Tutor
Login
Login
E-Mail Address
Fill out this field and ensure that is a valid email
Password
Fill out this field
Remember Me
Login
OR
Login with Google
Forgot Your Password?


Rails <IP_ADDRESS> (July 12, 2022)
-
Change ActiveRecord::Coders::YAMLColumn default to safe_load
This adds two new configuration options The configuration options are as follows:
config.active_storage.use_yaml_unsafe_load
When set to true, this configuration option tells Rails to use the old "unsafe" YAML loading strategy, maintaining the existing behavior but leaving the possible escalation vulnerability in place. Setting this option to true is not recommended, but can aid in upgrading.
config.active_record.yaml_column_permitted_classes
The "safe YAML" loading method does not allow all classes to be deserialized by default. This option allows you to specify classes deemed "safe" in your application. For example, if your application uses Symbol and Time in serialized data, you can add Symbol and Time to the allowed list as follows:
config.active_record.yaml_column_permitted_classes = [Symbol, Date, Time]
[CVE-2022-32224]
Rails 5.2.8 (May 09, 2022)
- No changes.
Rails <IP_ADDRESS> (April 26, 2022)
- No changes.
Rails 5.2.7 (March 10, 2022)
- No changes.
Rails <IP_ADDRESS> (March 08, 2022)
- No changes.
Rails <IP_ADDRESS> (February 11, 2022)
- No changes.
Rails <IP_ADDRESS> (February 11, 2022)
- No changes.
Rails 5.2.6 (May 05, 2021)
- No changes.
Rails 5.2.5 (March 26, 2021)
- No changes.
Rails <IP_ADDRESS> (May 05, 2021)
- No changes.
Rails <IP_ADDRESS> (February 10, 2021)
-
Fix possible DoS vector in PostgreSQL money type
Carefully crafted input can cause a DoS via the regular expressions used for validating the money format in the PostgreSQL adapter. This patch fixes the regexp.
Thanks to @dee-see from Hackerone for this patch!
[CVE-2021-22880]
Aaron Patterson
Rails <IP_ADDRESS> (September 09, 2020)
- No changes.
Rails <IP_ADDRESS> (May 18, 2020)
- No changes.
Rails <IP_ADDRESS> (March 19, 2020)
- No changes.
Rails <IP_ADDRESS> (December 18, 2019)
- No changes.
Rails 5.2.4 (November 27, 2019)
-
Fix circular
autosave: true
causes invalid records to be saved.Prior to the fix, when there was a circular series of
autosave: true
associations, the callback for ahas_many
association was run while another instance of the same callback on the same association hadn't finished running. When control returned to the first instance of the callback, the instance variable had changed, and subsequent associated records weren't saved correctly. Specifically, the ID field for thebelongs_to
corresponding to thehas_many
wasnil
.Fixes #28080.
Larry Reid
-
PostgreSQL: Fix GROUP BY with ORDER BY virtual count attribute.
Fixes #36022.
Ryuta Kamizono
-
Fix sqlite3 collation parsing when using decimal columns.
Martin R. Schuster
-
Make ActiveRecord
ConnectionPool.connections
method thread-safe.Fixes #36465.
Jeff Doering
-
Assign all attributes before calling
build
to ensure the child record is visible inbefore_add
andafter_add
callbacks forhas_many :through
associations.Fixes #33249.
Ryan H. Kerr
Rails 5.2.3 (March 27, 2019)
-
Fix different
count
calculation when usingsize
with manualselect
with DISTINCT.Fixes #35214.
Juani Villarejo
-
Fix prepared statements caching to be enabled even when query caching is enabled.
Ryuta Kamizono
-
Don't allow
where
with invalid value matches to nil values.Fixes #33624.
Ryuta Kamizono
-
Restore an ability that class level
update
without giving ids.Fixes #34743.
Ryuta Kamizono
-
Fix join table column quoting with SQLite.
Gannon McGibbon
-
Ensure that
delete_all
on collection proxy returns affected count.Ryuta Kamizono
-
Reset scope after delete on collection association to clear stale offsets of removed records.
Gannon McGibbon
Rails <IP_ADDRESS> (March 11, 2019)
- No changes.
Rails 5.2.2 (December 04, 2018)
-
Do not ignore the scoping with query methods in the scope block.
Ryuta Kamizono
-
Allow aliased attributes to be used in
#update_columns
and#update
.Gannon McGibbon
-
Allow spaces in postgres table names.
Fixes issue where "user post" is misinterpreted as ""user"."post"" when quoting table names with the postgres adapter.
Gannon McGibbon
-
Cached columns_hash fields should be excluded from ResultSet#column_types
PR #34528 addresses the inconsistent behaviour when attribute is defined for an ignored column. The following test was passing for SQLite and MySQL, but failed for PostgreSQL:
class DeveloperName < ActiveRecord::Type::String def deserialize(value) "Developer: #{value}" end end class AttributedDeveloper < ActiveRecord::Base self.table_name = "developers" attribute :name, DeveloperName.new self.ignored_columns += ["name"] end developer = AttributedDeveloper.create developer.update_column :name, "name" loaded_developer = AttributedDeveloper.where(id: developer.id).select("*").first puts loaded_developer.name # should be "Developer: name" but it's just "name"
Dmitry Tsepelev
-
Values of enum are frozen, raising an error when attempting to modify them.
Emmanuel Byrd
-
update_columns
now correctly raises::ActiveModel::MissingAttributeError
if the attribute does not exist.Sean Griffin
-
Do not use prepared statement in queries that have a large number of binds.
Ryuta Kamizono
-
Fix query cache to load before first request.
Eileen M. Uchitelle
-
Fix collection cache key with limit and custom select to avoid ambiguous timestamp column error.
Fixes #33056.
Federico Martinez
-
Fix duplicated record creation when using nested attributes with
create_with
.Darwin Wu
-
Fix regression setting children record in parent
before_save
callback.Guo Xiang Tan
-
Prevent leaking of user's DB credentials on
rails db:create
failure.bogdanvlviv
-
Clear mutation tracker before continuing the around callbacks.
Yuya Tanaka
-
Prevent deadlocks when waiting for connection from pool.
Brent Wheeldon
-
Avoid extra scoping when using
Relation#update
that was causing this method to change the current scope.Ryuta Kamizono
-
Fix numericality validator not to be affected by custom getter.
Ryuta Kamizono
-
Fix bulk change table ignores comment option on PostgreSQL.
Yoshiyuki Kinjo
Rails <IP_ADDRESS> (November 27, 2018)
- No changes.
Rails 5.2.1 (August 07, 2018)
-
PostgreSQL: Support new relkind for partitioned tables.
Fixes #33008.
Yannick Schutz
-
Rollback parent transaction when children fails to update.
Guillaume Malette
-
Fix default value for MySQL time types with specified precision.
Nikolay Kondratyev
-
Fix
touch
option to behave consistently withPersistence#touch
method.Ryuta Kamizono
-
Fix
save
inafter_create_commit
won't invoke extraafter_create_commit
.Fixes #32831.
Ryuta Kamizono
-
Fix logic on disabling commit callbacks so they are not called unexpectedly when errors occur.
Brian Durand
-
Fix parent record should not get saved with duplicate children records.
Fixes #32940.
Santosh Wadghule
-
Fix that association's after_touch is not called with counter cache.
Fixes #31559.
Ryuta Kamizono
-
becomes
should clear the mutation tracker which is created inafter_initialize
.Fixes #32867.
Ryuta Kamizono
-
Allow a belonging to parent object to be created from a new record.
Jolyon Pawlyn
-
Fix that building record with assigning multiple has_one associations wrongly persists through record.
Fixes #32511.
Sam DeCesare
-
Fix relation merging when one of the relations is going to skip the query cache.
James Williams
Rails 5.2.0 (April 09, 2018)
-
MySQL: Support mysql2 0.5.x.
Aaron Stone
-
Apply time column precision on assignment.
PR #20317 changed the behavior of datetime columns so that when they have a specified precision then on assignment the value is rounded to that precision. This behavior is now applied to time columns as well.
Fixes #30301.
Andrew White
-
Normalize time column values for SQLite database.
For legacy reasons, time columns in SQLite are stored as full datetimes because until #24542 the quoting for time columns didn't remove the date component. To ensure that values are consistent we now normalize the date component to 2001-01-01 on reading and writing.
Andrew White
-
Ensure that the date component is removed when quoting times.
PR #24542 altered the quoting for time columns so that the date component was removed however it only removed it when it was 2001-01-01. Now the date component is removed irrespective of what the date is.
Andrew White
-
Fix
dependent: :destroy
issue for has_one/belongs_to relationship where the parent class was getting deleted when the child was not.Fixes #32022.
Fernando Gorodscy
-
Whitelist
NULLS FIRST
andNULLS LAST
in order clauses too.Xavier Noria
-
Fix that after commit callbacks on update does not triggered when optimistic locking is enabled.
Ryuta Kamizono
-
Fix
#columns_for_distinct
of MySQL and PostgreSQL to make ActiveRecord::FinderMethods#limited_ids_for use correct primary key values even ifORDER BY
columns include other table's primary key.Fixes #28364.
Takumi Kagiyama
-
Make
reflection.klass
raise ifpolymorphic?
not to be misused.Fixes #31876.
Ryuta Kamizono
-
PostgreSQL: Allow pg-1.0 gem to be used with Active Record.
Lars Kanis
-
Deprecate
expand_hash_conditions_for_aggregates
without replacement. Using aRelation
for performing queries is the prefered API.Ryuta Kamizono
-
Fix not expanded problem when passing an
Array
object as argument to the where method usingcomposed_of
column.david_balance = customers(:david).balance Customer.where(balance: [david_balance]).to_sql # Before: WHERE `customers`.`balance` = NULL # After : WHERE `customers`.`balance` = 50
Fixes #31723.
Yutaro Kanagawa
-
Fix
count(:all)
with eager loading and having an order other than the driving table.Fixes #31783.
Ryuta Kamizono
-
Clear the transaction state when an Active Record object is duped.
Fixes #31670.
Yuriy Ustushenko
-
Support for PostgreSQL foreign tables.
fatkodima
-
Fix relation merger issue with
left_outer_joins
.Mehmet Emin İNAÇ
-
Don't allow destroyed object mutation after
save
orsave!
is called.Ryuta Kamizono
-
Take into account association conditions when deleting through records.
Fixes #18424.
Piotr Jakubowski
-
Fix nested
has_many :through
associations on unpersisted parent instances.For example, if you have
class Post < ActiveRecord::Base belongs_to : has_many :books, through: : has_many :subscriptions, through: :books end class Author < ActiveRecord::Base has_one :post has_many :books has_many :subscriptions, through: :books end class Book < ActiveRecord::Base belongs_to : has_many :subscriptions end class Subscription < ActiveRecord::Base belongs_to :book end
Before:
If
post
is not persisted, thenpost.subscriptions
will be empty.After:
If
post
is not persisted, thenpost.subscriptions
can be set and used just like it would ifpost
were persisted.Fixes #16313.
Zoltan Kiss
-
Fixed inconsistency with
first(n)
when used withlimit()
. Thefirst(n)
finder now respects thelimit()
, making it consistent withrelation.to_a.first(n)
, and also with the behavior oflast(n)
.Fixes #23979.
Brian Christian
-
Use
count(:all)
inHasManyAssociation#count_records
to prevent invalid SQL queries for association counting.Klas Eskilson
-
Fix to invoke callbacks when using
update_attribute
.Mike Busch
-
Fix
count(:all)
to correctly workdistinct
with custom SELECT list.Ryuta Kamizono
-
Using subselect for
delete_all
withlimit
oroffset
.Ryuta Kamizono
-
Undefine attribute methods on descendants when resetting column information.
Chris Salzberg
-
Log database query callers.
Add
verbose_query_logs
configuration option to display the caller of database queries in the log to facilitate N+1 query resolution and other debugging.Enabled in development only for new and upgraded applications. Not recommended for use in the production environment since it relies on Ruby's
Kernel#caller_locations
which is fairly slow.Olivier Lacan
-
Fix conflicts
counter_cache
withtouch: true
by optimistic locking.# create_table :posts do |t| # t.integer :comments_count, default: 0 # t.integer :lock_version # t.timestamps # end class Post < ApplicationRecord end # create_table :comments do |t| # t.belongs_to :post # end class Comment < ApplicationRecord belongs_to :post, touch: true, counter_cache: true end
Before:
post = Post.create! # => begin transaction INSERT INTO "posts" ("created_at", "updated_at", "lock_version") VALUES ("2017-12-11 21:27:11.387397", "2017-12-11 21:27:11.387397", 0) commit transaction comment = Comment.create!(post: post) # => begin transaction INSERT INTO "comments" ("post_id") VALUES (1) UPDATE "posts" SET "comments_count" = COALESCE("comments_count", 0) + 1, "lock_version" = COALESCE("lock_version", 0) + 1 WHERE "posts"."id" = 1 UPDATE "posts" SET "updated_at" = '2017-12-11 21:27:11.398330', "lock_version" = 1 WHERE "posts"."id" = 1 AND "posts"."lock_version" = 0 rollback transaction # => ActiveRecord::StaleObjectError: Attempted to touch a stale object: Post. Comment.take.destroy! # => begin transaction DELETE FROM "comments" WHERE "comments"."id" = 1 UPDATE "posts" SET "comments_count" = COALESCE("comments_count", 0) - 1, "lock_version" = COALESCE("lock_version", 0) + 1 WHERE "posts"."id" = 1 UPDATE "posts" SET "updated_at" = '2017-12-11 21:42:47.785901', "lock_version" = 1 WHERE "posts"."id" = 1 AND "posts"."lock_version" = 0 rollback transaction # => ActiveRecord::StaleObjectError: Attempted to touch a stale object: Post.
After:
post = Post.create! # => begin transaction INSERT INTO "posts" ("created_at", "updated_at", "lock_version") VALUES ("2017-12-11 21:27:11.387397", "2017-12-11 21:27:11.387397", 0) commit transaction comment = Comment.create!(post: post) # => begin transaction INSERT INTO "comments" ("post_id") VALUES (1) UPDATE "posts" SET "comments_count" = COALESCE("comments_count", 0) + 1, "lock_version" = COALESCE("lock_version", 0) + 1, "updated_at" = '2017-12-11 21:37:09.802642' WHERE "posts"."id" = 1 commit transaction comment.destroy! # => begin transaction DELETE FROM "comments" WHERE "comments"."id" = 1 UPDATE "posts" SET "comments_count" = COALESCE("comments_count", 0) - 1, "lock_version" = COALESCE("lock_version", 0) + 1, "updated_at" = '2017-12-11 21:39:02.685520' WHERE "posts"."id" = 1 commit transaction
Fixes #31199.
bogdanvlviv
-
Add support for PostgreSQL operator classes to
add_index
.Example:
add_index :users, :name, using: :gist, opclass: { name: :gist_trgm_ops }
Greg Navis
-
Don't allow scopes to be defined which conflict with instance methods on
Relation
.Fixes #31120.
kinnrot
-
Add new error class
QueryCanceled
which will be raised when canceling statement due to user request.Ryuta Kamizono
-
Add
#up_only
to database migrations for code that is only relevant when migrating up, e.g. populating a new column.Rich Daley
-
Require raw SQL fragments to be explicitly marked when used in relation query methods.
Before:
Article.order("LENGTH(title)")
After:
Article.order(Arel.sql("LENGTH(title)"))
This prevents SQL injection if applications use the [strongly discouraged] form
Article.order(params[:my_order])
, under the mistaken belief that only column names will be accepted.Raw SQL strings will now cause a deprecation warning, which will become an UnknownAttributeReference error in Rails 6.0. Applications can opt in to the future behavior by setting
allow_unsafe_raw_sql
to:disabled
.Common and judged-safe string values (such as simple column references) are unaffected:
Article.order("title DESC")
Ben Toews
-
update_all
will now pass its values toType#cast
before passing them toType#serialize
. This means thatupdate_all(foo: 'true')
will properly persist a boolean.Sean Griffin
-
Add new error class
StatementTimeout
which will be raised when statement timeout exceeded.Ryuta Kamizono
-
Fix
bin/rails db:migrate
with specifiedVERSION
.bin/rails db:migrate
with empty VERSION behaves as withoutVERSION
. Check a format ofVERSION
: Allow a migration version number or name of a migration file. Raise error if format ofVERSION
is invalid. Raise error if target migration doesn't exist.bogdanvlviv
-
Fixed a bug where column orders for an index weren't written to
db/schema.rb
when using the sqlite adapter.Fixes #30902.
Paul Kuruvilla
-
Remove deprecated method
#sanitize_conditions
.Rafael Mendonça França
-
Remove deprecated method
#scope_chain
.Rafael Mendonça França
-
Remove deprecated configuration
.error_on_ignored_order_or_limit
.Rafael Mendonça França
-
Remove deprecated arguments from
#verify!
.Rafael Mendonça França
-
Remove deprecated argument
name
from#indexes
.Rafael Mendonça França
-
Remove deprecated method
ActiveRecord::Migrator.schema_migrations_table_name
.Rafael Mendonça França
-
Remove deprecated method
supports_primary_key?
.Rafael Mendonça França
-
Remove deprecated method
supports_migrations?
.Rafael Mendonça França
-
Remove deprecated methods
initialize_schema_migrations_table
andinitialize_internal_metadata_table
.Rafael Mendonça França
-
Raises when calling
lock!
in a dirty record.Rafael Mendonça França
-
Remove deprecated support to passing a class to
:class_name
on associations.Rafael Mendonça França
-
Remove deprecated argument
default
fromindex_name_exists?
.Rafael Mendonça França
-
Remove deprecated support to
quoted_id
when typecasting an Active Record object.Rafael Mendonça França
-
Fix
bin/rails db:setup
andbin/rails db:test:prepare
create wrong ar_internal_metadata's data for a test database.Before:
$ RAILS_ENV=test rails dbconsole > SELECT * FROM ar_internal_metadata; key|value|created_at|updated_at environment|development|2017-09-11 23:14:10.815679|2017-09-11 23:14:10.815679
After:
$ RAILS_ENV=test rails dbconsole > SELECT * FROM ar_internal_metadata; key|value|created_at|updated_at environment|test|2017-09-11 23:14:10.815679|2017-09-11 23:14:10.815679
Fixes #26731.
bogdanvlviv
-
Fix longer sequence name detection for serial columns.
Fixes #28332.
Ryuta Kamizono
-
MySQL: Don't lose
auto_increment: true
in thedb/schema.rb
.Fixes #30894.
Ryuta Kamizono
-
Fix
COUNT(DISTINCT ...)
forGROUP BY
withORDER BY
andLIMIT
.Fixes #30886.
Ryuta Kamizono
-
PostgreSQL
tsrange
now preserves subsecond precision.PostgreSQL 9.1+ introduced range types, and Rails added support for using this datatype in Active Record. However, the serialization of
PostgreSQL::OID::Range
was incomplete, because it did not properly cast the bounds that make up the range. This led to subseconds being dropped in SQL commands:Before:
connection.type_cast(tsrange.serialize(range_value)) # => "[2010-01-01 13:30:00 UTC,2011-02-02 19:30:00 UTC)"
Now:
connection.type_cast(tsrange.serialize(range_value)) # => "[2010-01-01 13:30:00.670277,2011-02-02 19:30:00.745125)"
Thomas Cannon
-
Passing a
Set
toRelation#where
now behaves the same as passing an array.Sean Griffin
-
Use given algorithm while removing index from database.
Fixes #24190.
Mehmet Emin İNAÇ
-
Update payload names for
sql.active_record
instrumentation to be more descriptive.Fixes #30586.
Jeremy Green
-
Add new error class
LockWaitTimeout
which will be raised when lock wait timeout exceeded.Gabriel Courtemanche
-
Remove deprecated
#migration_keys
.Ryuta Kamizono
-
Automatically guess the inverse associations for STI.
Yuichiro Kaneko
-
Ensure
sum
honorsdistinct
onhas_many :through
associations.Fixes #16791.
Aaron Wortham
-
Add
binary
fixture helper method.Atsushi Yoshida
-
When using
Relation#or
, extract the common conditions and put them before the OR condition.Maxime Handfield Lapointe
-
Relation#or
now accepts two relations who have different values forreferences
only, asreferences
can be implicitly called bywhere
.Fixes #29411.
Sean Griffin
-
ApplicationRecord
is no longer generated when generating models. If you need to generate it, it can be created withrails g application_record
.Lisa Ugray
-
Fix
COUNT(DISTINCT ...)
withORDER BY
andLIMIT
to keep the existing select list.Ryuta Kamizono
-
When a
has_one
association is destroyed bydependent: destroy
,destroyed_by_association
will now be set to the reflection, matching the behaviour ofhas_many
associations.Lisa Ugray
-
Fix
unscoped(where: [columns])
removing the wrong bind values.When the
where
is called on a relation after aor
, unscoping the column of that laterwhere
removed bind values used by theor
instead. (possibly other cases too)Post.where(id: 1).or(Post.where(id: 2)).where(foo: 3).unscope(where: :foo).to_sql # Currently: # SELECT "posts".* FROM "posts" WHERE ("posts"."id" = 2 OR "posts"."id" = 3) # With fix: # SELECT "posts".* FROM "posts" WHERE ("posts"."id" = 1 OR "posts"."id" = 2)
Maxime Handfield Lapointe
-
Values constructed using multi-parameter assignment will now use the post-type-cast value for rendering in single-field form inputs.
Sean Griffin
-
Relation#joins
is no longer affected by the target model'scurrent_scope
, with the exception ofunscoped
.Fixes #29338.
Sean Griffin
-
Change sqlite3 boolean serialization to use 1 and 0.
SQLite natively recognizes 1 and 0 as true and false, but does not natively recognize 't' and 'f' as was previously serialized.
This change in serialization requires a migration of stored boolean data for SQLite databases, so it's implemented behind a configuration flag whose default false value is deprecated.
Lisa Ugray
-
Skip query caching when working with batches of records (
find_each
,find_in_batches
,in_batches
).Previously, records would be fetched in batches, but all records would be retained in memory until the end of the request or job.
Eugene Kenny
-
Prevent errors raised by
sql.active_record
notification subscribers from being converted into::ActiveRecord::StatementInvalid
exceptions.Dennis Taylor
-
Fix eager loading/preloading association with scope including joins.
Fixes #28324.
Ryuta Kamizono
-
Fix transactions to apply state to child transactions.
Previously, if you had a nested transaction and the outer transaction was rolledback, the record from the inner transaction would still be marked as persisted.
This change fixes that by applying the state of the parent transaction to the child transaction when the parent transaction is rolledback. This will correctly mark records from the inner transaction as not persisted.
Eileen M. Uchitelle, Aaron Patterson
-
Deprecate
set_state
method inTransactionState
.Deprecated the
set_state
method in favor of setting the state via specific methods. If you need to mark the state of the transaction you can now userollback!
,commit!
ornullify!
instead ofset_state(:rolledback)
,set_state(:committed)
, orset_state(nil)
.Eileen M. Uchitelle, Aaron Patterson
-
Deprecate delegating to
arel
inRelation
.Ryuta Kamizono
-
Query cache was unavailable when entering the
ActiveRecord::Base.cache
block without being connected.Tsukasa Oishi
-
Previously, when building records using a
has_many :through
association, if the child records were deleted before the parent was saved, they would still be persisted. Now, if child records are deleted before the parent is saved on ahas_many :through
association, the child records will not be persisted.Tobias Kraze
-
Merging two relations representing nested joins no longer transforms the joins of the merged relation into LEFT OUTER JOIN.
Example:
Author.joins(:posts).merge(Post.joins(:comments)) # Before the change: #=> SELECT ... FROM authors INNER JOIN posts ON ... LEFT OUTER JOIN comments ON... # After the change: #=> SELECT ... FROM authors INNER JOIN posts ON ... INNER JOIN comments ON...
Maxime Handfield Lapointe
-
ActiveRecord::Persistence#touch does not work well when optimistic locking enabled and
locking_column
, without default value, is null in the database.bogdanvlviv
-
Fix destroying existing object does not work well when optimistic locking enabled and
locking_column
is null in the database.bogdanvlviv
-
Use bulk INSERT to insert fixtures for better performance.
Kir Shatrov
-
Prevent creation of bind param if casted value is nil.
Ryuta Kamizono
-
Deprecate passing arguments and block at the same time to
count
andsum
in::ActiveRecord::Calculations
.Ryuta Kamizono
-
Loading model schema from database is now thread-safe.
Fixes #28589.
Vikrant Chaudhary, David Abdemoulaie
-
Add
ActiveRecord::Base#cache_version
to support recyclable cache keys via the new versioned entries in::ActiveSupport::Cache
. This also means thatActiveRecord::Base#cache_key
will now return a stable key that does not include a timestamp any more.NOTE: This feature is turned off by default, and
#cache_key
will still return cache keys with timestamps until you setActiveRecord::Base.cache_versioning = true
. That's the setting for all new apps on Rails 5.2+DHH
-
Respect
SchemaDumper.ignore_tables
in rake tasks for databases structure dump.Rusty Geldmacher, Guillermo Iguaran
-
Add type caster to
RuntimeReflection#alias_name
.Fixes #28959.
Jon Moss
-
Deprecate
supports_statement_cache?
.Ryuta Kamizono
-
Raise error
UnknownMigrationVersionError
on the movement of migrations when the current migration does not exist.bogdanvlviv
-
Fix
bin/rails db:forward
first migration.bogdanvlviv
-
Support Descending Indexes for MySQL.
MySQL 8.0.1 and higher supports descending indexes:
DESC
in an index definition is no longer ignored. See https://dev.mysql.com/doc/refman/8.0/en/descending-indexes.html.Ryuta Kamizono
-
Fix inconsistency with changed attributes when overriding Active Record attribute reader.
bogdanvlviv
-
When calling the dynamic fixture accessor method with no arguments, it now returns all fixtures of this type. Previously this method always returned an empty array.
Kevin McPhillips
Please check 5-1-stable for previous changes.


{% include "partials/meta.html" %}
{% include "partials/icons.html" %}
{% include "pages/score.html" %} {% include "pages/game.html" %} {% include "pages/about.html" %} {# Default view needs to be at the end #} {% include "pages/menu.html" %}


Next: Keyword Arguments in Generic Functions and Methods, Previous: Agreement on Parameter Specializers and Qualifiers, Up: Generic Functions and Methods
These rules define the congruence of a set of lambda lists, including the lambda list of each method for a given generic function and the lambda list specified for the generic function itself, if given.
Each lambda list must have the same number of required parameters.
Each lambda list must have the same number of optional parameters. Each method can supply its own default for an optional parameter.
If any lambda list mentions &rest or &key, each lambda list must mention one or both of them.
If the generic function lambda list mentions &key, each method must accept all of the keyword names mentioned after &key, either by accepting them explicitly, by specifying &allow-other-keys, or by specifying &rest but not &key. Each method can accept additional keyword arguments of its own. The checking of the validity of keyword names is done in the generic function, not in each method. A method is invoked as if the keyword argument pair whose name is :allow-other-keys and whose value is true were supplied, though no such argument pair will be passed.
The use of &allow-other-keys need not be consistent across lambda lists. If &allow-other-keys is mentioned in the lambda list of any applicable method or of the generic function, any keyword arguments may be mentioned in the call to the generic function.
The use of &aux need not be consistent across methods.
If a method-defining operator that cannot specify generic function options creates a generic function, and if the lambda list for the method mentions keyword arguments, the lambda list of the generic function will mention &key (but no keyword arguments).


{% extends "_base.htm" %} {% block bodycontent %}
Explain sessionStorage. Also explain local vs. sessionstorage


Has to be used if a join refers to a different classMap.
refObjectMap -
Static variable in class org.d2rq.vocab.RR
A RefObjectMap element to generate the object component of the (predicate,
object) pair from a logical table row using a foreign key constraint definition.
RefObjectMap -
Static variable in class org.d2rq.vocab.RR


--- layout: page title: About Me description: This is what I do. background: '/img/bg-about.jpg' ---
The Lamb Lies Down on Broadway
Early morning Manhattan, Ocean winds blow on the land. The Movie-Palace is now undone, The all-night watchmen have had their fun.


doctoc_lang_cmdref - doctoc language command reference
This document specifies both names and syntax of all the commands which together are the doctoc markup language, version 1. As this document is intended to be a reference the commands are listed in alphabetical order, and the descriptions are relatively short. A beginner should read the much more informally written doctoc language introduction first.
Toc markup. The argument text is marked up as a comment standing outside of the actual text of the document. Main use is in free-form text.
Toc structure. This command closes the division opened by the last division_begin command coming before it, and not yet closed.
Toc structure. This command opens a division in the table of contents. Its counterpart is division_end. Together they allow a user to give a table of contents additional structure.
The title of the new division is provided by the argument text.
If the symbolic filename symfile is present then the section title should link to the referenced document, if links are supported by the output format.
Templating. The contents of the named file are interpreted as text written in the doctoc markup and processed in the place of the include command. The markup in the file has to be self-contained. It is not possible for a markup command to cross the file boundaries.
Toc structure. This command adds an individual element to the table of contents. Each such element refers to a document. The document is specified through the symbolic name file. The text argument is used to label the reference, whereas the desc provides a short descriptive text of that document.
The symbolic names are used to preserve the convertibility of this format to any output format. The actual name of the file will be inserted by the chosen formatting engine when converting the input. This will be based on a mapping from symbolic to actual names given to the engine.
Text. The command is replaced with a left bracket. Use in free-form text. Required to avoid interpretation of a left bracket as the start of a markup command. Its usage is restricted to the arguments of other markup commands.
Text. The command is replaced with a right bracket. Use in free-form text. Required to avoid interpretation of a right bracket as the end of a markup command. Its usage is restricted to the arguments of other commands.
Document structure. The command to start a table of contents. The arguments are a label for the whole group of documents the index refers to (text) and the overall title text for the index (title), without markup.
The label often is the name of the package (or extension) the documents belong to.
Document structure. Command to end a table of contents. Anything in the document coming after this command is in error.
Templating. In this form the command sets the named document variable to the specified value. It does not generate output. I.e. the command is replaced by the empty string.
Templating. In this form the command is replaced by the value of the named document variable
This document, and the package it describes, will undoubtedly contain bugs and other problems. Please report such in the category doctools of the Tcllib Trackers. Please also report any ideas for enhancements you may have for either package and/or documentation.
When proposing code changes, please provide unified diffs, i.e the output of diff -u.
Note further that attachments are strongly preferred over inlined patches. Attachments can be made by going to the Edit form of the ticket immediately after its creation, and then using the left-most button in the secondary navigation bar.
Documentation tools
Copyright © 2007 Andreas Kupries <andreas_kupries@users.sourceforge.net>


Hiking in nature is not only good for our bodies, it's good for our moods, our minds, and our relationships, too.


Master's in Human Computer Interaction: University of Michigan
August 2017 - April 2019
I'm attending the University of Michigan from fall 2017 until 2019 while I work on completing a Master's of Science degree in User Experience (UX) Research and Design / Human Computer Interaction (HCI) / Social Computing.
Bachelor's in Telecommunication & Creative Advertising: Michigan State University
December 2010 - May 2015
I completed my B.S. in Media and Information in four and a half years at Michigan State University with an approximate 3.5 G.P.A. During this time, I also worked on completing a second degree in Creative Advertising
User Experience Researcher & Accessibility Specialist: General Motors
Worked on General Motors’ next iteration of their in-vehicle touch screen systems. Responsible for conducting user research on various software applications designed for Infotainment 3.0. Research methodologies used include: usability testing, heuristic evaluations, online surveys, and contextual interviews. Additionally, provided accessibility guidance to UX Designers using WCAG 2.0 guidelines.
User Experience Intern: Usability/Accessibility Research & Design
Mainly responsible for conducting accessibility evaluations using WCAG 2.0 guidelines for contracted clients. Additionally, conducted usability testing, heuristic evaluations, contextual interviews, and trained student interns on how to use and apply WCAG 2.0 accessibility guidelines.
Research Volunteer: Taubman Health Sciences Library
Volunteered to conduct UX research for the Taubman Health Sciences Library in the University of Michigan. Project consisted of interviewing stakeholders and employees to learn why informationists within the library were not being utilized as a resource by other departments. The project utilized common UX techniques such as affinity walls, competitive analysis, and contextual interviews.
View Taubman Health Sciences ProjectResearch Volunteer: University of Michigan Medicine School - Health and Information Technology Services
Volunteered to conduct UX research for University of Michigan's Health and Information Technology Services. The project focused on using several User Experience Research methods, such as: creating an interaction map of client's website, user interviews, competitive/comparative analysis, heuristic evaluation, and usability testing.
View Health and Information Technology Services Project


Letters: Kahuku wind farm is too big; Sending aloha to Tagovailoa; Filter media reports | Honolulu Star-Advertiser
This wind farm has been fought against for 10 years and is too big, too close; Tua Tagovailoa’s season-ending injury is not only heartbreaking to Alabama Crimson Tide fans, but also to all of us here at home; Today’s media is not the same fair, objective and unbiased media it once was. Read more
Mahalo for reading the Honolulu Star-Advertiser!
You're reading a premium story. Read the full story with our Print & Digital Subscription.
Already a subscriber? Log in now to continue reading this story.
Print subscriber but without online access? Activate your Digital Account now.


4 Number Game
The 4 number game is a well known arithmetic puzzle that
can be played in groups. You are presented with four numbers, e.g. 1 1 11 11,
and are given the goal to make 24 by using the arithmetic operators +
, *
,
-
, /
and liberal use of parenthesis.
As the below code shows, adding all the numbers will solve the puzzle.
(+ 1 1 11 11)
In this blog post we will explore code that can find solutions to these puzzles. One puzzle that is a little more interesting than the other is to try to make 24 with 1 3 8 8.
Solution Path
Every arithmetic expression, e.g. 1 + 2 * 3
, can be seen as a a tree. In
this case the tree would be
+
/ \
1 *
/ \
2 3
This tree tells us that we need to add 1
and the product of 2
and 3
. I we
squint with our eyes and only take into account the structure of the tree, we
would see the following
/ \
/ \
The only thing that is missing from this tree are the operators, which should go into the internal positions of the tree, and the numbers, which should go in the leaf positions.
So our solution will be:
- Generate all the possible tree structures
- Decorate a tree structure with all possible operators and all possible values
- Evaluate an expression tree
- Putting it together
Generating all tree structures
In the following code snippet we generate all the tree structures with only one internal node. There is only one, which can be seen.
(require '[flippo.tree :refer [generate-structure-tree]])
(generate-structure-tree 1)
This blog post is enhanced with klipse, which means that all code snippets are interactive. Go ahead and change the number and see the corresponding tree structures.
How can one generate these structures?
Let's first think of growing a single tree. Below we have a tree with two internal node that corresponds to the arithmetic expression from the solution path section.
(def a-tree {:left nil, :right {:left nil, :right nil}})
We can visualize the nil
position as buds ready to spring a new tree part. So
in order to grow our tree we could try to adjoin a part to all buds.
(defn adjoin [tree part]
"Returns a sequence of structured trees where part is adjoined to
all the buds in tree"
(if (nil? tree)
(seq [part])
(concat
(map (fn [t] {:left t :right (:right tree)}) (adjoin (:left tree) part))
(map (fn [t] {:left (:left tree) :right t}) (adjoin (:right tree) part)))))
(adjoin a-tree :A)
Here we adjoined a keyword :A
and we see that we get three new tree
structures. Try to adjoin a small tree structure {:left nil :right nil}
.
This is the basis of the generate-structure-tree
algorithm. There is only one
tree with zero internal nodes, i.e. nil
. It can serve as a basis to sprout
small trees from the buds. Doing this recursively gives us our algorithm.
Decorate a Tree Structure
Now that we can generate tree structures, we would like to decorate them with tree operators and values. The basic algorithm for that is visiting all nodes in the tree and assign values to the leaves and operator to the internal nodes.
A generator helps us in this case. We could use it to request the next value we haven't use. Lets implement a generator.
(defn generator [elements]
"Creates a generator that loops through the vector elements"
(let [index (atom 0)]
(fn []
(let [current-index @index]
(do
(swap! index #(mod (inc %) (count elements)))
(nth elements current-index))))))
(def keyword-generator (generator [:A :B :C]))
(keyword-generator)
(keyword-generator)
Our generator
is a high-order function in the sense that it returns a
function. The function closes over an atom
that keeps track of an index. The index is used to retrieve an element from the
elements provided as an argument to generator
call.
We created a keyword generator and called it twice. This returns :B
. Add a new
call to keyword-generator
and it will cycle through the values :A
, :B
and
:C
.
How can we use this?
Lets assume we have a tree that we want to decorate. Furthermore, we have an
generator that cycles through a selection of operators, e.g. *
and +
, and a
generator that cycles through some values, e.g. 1
, 2
and 3
. What we could
do is walk the tree and transform it in the following fashion. For each internal
node of the tree, request and operator from the operator generator, and
associate it with that node. Furthermore, for each leaf node, request a value
from the value generator and make a value node.
The only unknown is the question: how to traverse a tree. Lets implement it right away.
(defn map-tree [f tree]
"Let f operate on all the nodes of the tree"
(if (nil? tree)
(f tree nil nil)
(f tree (map-tree f (:left tree)) (map-tree f (:right tree)))))
map-tree
takes a function f
and a tree and applies each node of the tree,
together with its two children to f
. We can use it to decorate the tree with
the operators and values.
(defn decorate [operators values tree]
"Transforms a structured tree into a tree ready for evaluation. It walks the tree
and transform nil nodes into value-nodes, and non-nil nodes into operator nodes.
This is done in a cyclic fashion, both for the operators and the values."
(let [
operator-generator (generator operators)
value-generator (generator values)
transformer (fn [tree left right]
(if (nil? tree)
{:value (value-generator)}
{:operator (operator-generator) :left left :right right}))]
(map-tree transformer tree)))
(decorate '[* +] [1 2 3] {:left nil :right {:left nil :right nil}})
It seems to have worked. Make sure to try different operators, values and tree.
Then move on to the next phase. Note that we have quoted the list of operators.
This is to clean up the output. See what happens when you remove the '
.
Evaluating a Tree
Now that we have a abstract syntax tree of our arithmetic expression, we want to evaluate it. Evaluation is nothing more than applying the correct operation to the (evaluated) value of the left sub-tree and the (evaluated) value of the right sub-tree.
(defn evaluate [tree]
"Evaluates a tree representation like {:operator + :left {:value 1} :right {:value 2}}
to the corresponding value, i.e. 3."
(if (:operator tree)
((:operator tree)
(evaluate (:left tree))
(evaluate (:right tree)))
(:value tree)))
(def tree (decorate [* +] [1 2 3] {:left nil :right {:left nil :right nil}}))
(evaluate tree)
The tree in the above snippet represents the calculation 1 + (2 * 3)
, so it
produces the correct answer. There is only one problem that could occur. If we
would allow the operator /
and the value 0
, possibly this could lead to a
divide by zero answer. A safe-evaluate
would catch this ArithmeticException
and just return nil
.
Putting it Together
If you have experimented with the tree decorations, you may have noticed that
the order the operators are listed is important. If instead of first applying
*
and than +
, you reverse the order, the answer is different.
So we should try to have all possible selections of operators and all permutation of values and each try them on a tree. Luckily there is a nice library that provides these functions.
(require '[clojure.math.combinatorics :refer [permutations selections]])
(permutations [:A :B :C])
Above we see all possible permutations of three elements. This is ideal for trying out all possible assignments of values, because no value is repeated. For a given puzzle we can use each value only once.
We need something else if we want to try out all assignments of operators, because
the same operator can be used multiple times. Luckily the
clojure.math.combinatorics
library also provides selections
(require '[clojure.math.combinatorics :refer [permutations selections]])
(selections [:A :B :C] 2)
Here we see all possible two element sequence drawn from the vector [:A :B
:C]
. We can use that in order to solve our puzzle. The algorithm is
- Generate all possible selection of operators.
- Generate all possible permutation of values.
- Generate all structure trees.
- Decorate each combination of trees with operators and values.
- Filter the ones that do not reach the target.
(require '[clojure.math.combinatorics :refer [permutations selections]]
'[flippo.tree :refer [generate-structure-tree]])
(defn solve
([operators target values]
"Returns all trees that use operators to form target"
(filter #(= target (evaluate %))
(let [nodes (dec (count values))]
(for [os (selections operators nodes)
vs (permutations values)
tree (generate-structure-tree nodes)]
(decorate os vs tree))))))
We can use that to solve our puzzle
(require '[flippo.solution :refer [solve]]
'[flippo.representation :refer [infix]])
(map infix (solve [* + - /] 24 [1 3 8 8]))


{{weather.currently.temperature}}°
Atlanta, GA
Low {{weather.daily.data[0].temperatureMin}}° | High {{weather.daily.data[0].temperatureMax}}°
Feels like {{weather.currently.apparentTemperature}}° | Chance of rain {{weather.currently.precipProbability}}%


Mappings clash with vim-surround
-
guns
Recently, I tried searching for a css file by typing
css
, and I discovered that thecs
mapping provided by vim-surround was putting me in normal mode in the search buffer, instead of typingcs
! (theds
andys
mappings are also affected)I took a look at CommandT::Controller#register_for_key_presses, but I didn't see any obvious reason why the vim-surround mappings weren't being overridden. But, I haven't spent a lot of time digging into the nuances of Vimscript or the vim mappings system, so the reason may actually be obvious.
The issue occurs in both urxvt and Terminal.app, where
set term?
is screen-256color-bce, rxvt-unicode, and xterm-color. -
guns
I guess I should have read the link called
wikitext markup
before I posted... the inconsistent coloring above is from quoting with backtick-singlequote. -
Greg Hurrell
(Edited your post to fix your markup.)
I'm a vim-surround user too and haven't seen what you describe, so it must be something local to your set-up. I just tried to reproduce it and typing "css" at the Command-T prompt just searches for "css".
Command-T doesn't try to override any existing mappings — that would be impossible seeing as it can't know what different mappings people have set up and it wouldn't make sense to try — but it does add its own mappings.
Can you paste your
.vimrc
up somewhere so that we can look at? It seems likely to me that the cause is somewhere in there. Also, how did you install vim-surround and what version is it? -
guns
So the problem is my own :(. Sorry to bring it to your door. If you don't mind taking a moment to help though, here is my
.vimrc
:http://github.com/guns/nerv-guns/blob/guns/etc/user.vimrc
and my
~/.vim
http://github.com/guns/nerv-guns/tree/guns/etc/user.vim
vim-surround is installed straight from the github repo.
--
It's a lot to wade through, so if you would like to instead just give me a direction to pursue, that would also be much appreciated.
-
guns
Oh! I found it.
I have
set notimeout
, because I like emacs-style mappings and am annoyed when vim times out my incantations.Setting
set timeout
seems to fix the issue, but I would prefer to keep that setting the way it is.Hmm...
-
Greg Hurrell
Instead of setting
notimeout
, have you considered setting a hightimeoutlen
?I have a hunch that that might fix the problem you're seeing without breaking your Emacs-style mappings (I could be wrong though, it's just a hunch).
If you look in the Command-T source, specifically the
MatchWindow
class, you'll see that inside the match window it sets thetimeoutlen
to0
in order to make the keys respond immediately; my suspicion is that by settingnotimeout
you prevent thetimeoutlen
for having effect.If the suggested work around doesn't work for you we can look at other alternatives (Command-T, for example, could be patched to
set timeout
whenever the match window is displayed, and restore it to its previous value afterwards). -
guns
Thanks for your help! I decided to just patch in the timeout setting for the match window just like you did for timeoutlen. Works perfectly, and seems like an appropriate addition.
Thanks for your awesome plugin!
From 5de1fb620f5a219217f960c13d5ae47aeec35721 Mon Sep 17 00:00:00 2001 From: guns<EMAIL_ADDRESS>Date: Mon, 13 Sep 2010 15:16:50 -0500 Subject: [PATCH] `set timeout' on match window creation and restore on close --- ruby/command-t/match_window.rb | 1 + ruby/command-t/settings.rb | 2 ++ 2 files changed, 3 insertions(+), 0 deletions(-) diff --git a/ruby/command-t/match_window.rb b/ruby/command-t/match_window.rb index b5c10c9..eae0f87 100644 --- a/ruby/command-t/match_window.rb +++ b/ruby/command-t/match_window.rb @@ -42,6 +42,7 @@ module CommandT # global settings (must manually save and restore) @settings = Settings.new + ::VIM::set_option 'timeout' # ensure mappings timeout ::VIM::set_option 'timeoutlen=0' # respond immediately to mappings ::VIM::set_option 'nohlsearch' # don't highlight search strings ::VIM::set_option 'noinsertmode' # don't make Insert mode the default diff --git a/ruby/command-t/settings.rb b/ruby/command-t/settings.rb index 93af32f..c15016a 100644 --- a/ruby/command-t/settings.rb +++ b/ruby/command-t/settings.rb @@ -33,6 +33,7 @@ module CommandT @report = get_number 'report' @sidescroll = get_number 'sidescroll' @sidescrolloff = get_number 'sidescrolloff' + @timeout = get_bool 'timeout' @equalalways = get_bool 'equalalways' @hlsearch = get_bool 'hlsearch' @insertmode = get_bool 'insertmode' @@ -44,6 +45,7 @@ module CommandT set_number 'report', @report set_number 'sidescroll', @sidescroll set_number 'sidescrolloff', @sidescrolloff + set_bool 'timeout', @timeout set_bool 'equalalways', @equalalways set_bool 'hlsearch', @hlsearch set_bool 'insertmode', @insertmode -- 1.7.3.rc1.5.gd9b1
-
Greg Hurrell
Thanks for the patch. Looks sane enough. I can't really see any drawbacks to applying it, so will do so tomorrow.
-
anonymous
I run into this problem as well and discovered another bug. If you open the command-T and midstream decide to cancel (CTRL-C, i.e., not to open a file), the settings are never restored. Since the settings are saved and timeoutlen is changed to 0, after I cancel, my mappings don't work anymore (cuz the timeout len is still 0 and never restored to my original set value). Can you issue a patch for that? Thanks. Rick
-
Greg Hurrell
timeoutlen
already is saved and restored (see the settings.rb file).Can you explain why or how it is not being restored?
Reply
This topic is now closed.


Let's Encrypt Stats - Let's Encrypt - Free SSL/TLS Certificates Let's Encrypt Growth Percentage of Web Pages Loaded by Firefox Using HTTPS (14-day moving average, source: Firefox Telemetry) Let's Encrypt Certificates Issued Per Day
dotNetDave Rocks NDC { Porto } 2020 For the first time, the dotNetDave No Apologies World Tour will land in Porto, Portugal for the NDC {Porto} conference on April 21-24! I’m very excited to speak in Portugal for the first time…
Creating Certificates for X.509 security in Azure IoT Hub using .NET Core This article shows how to create certificates in .NET Core which can be used for Azure IoT Hub. The chained certificates are created using the nuget package CertificateManager. Code: To use X.509 s…
Code Maze Weekly #10 - Code Maze This week we bring you a new set of fresh and interesting articles: .NET and C# Inserting middleware between UseRouting() and UseEndpoints() as a library author – Part 1 [andrewlock.net] Andrew discusses one possible solution to solving middleware inserti...
Creating Certificates in .NET Core for Vue.js development using HTTPS This article shows how to create development certificates for a Vue.js application, so that you can develop using HTTPS. The certificates are created using the CertificateManager nuget package. Cod…
2020 Java Technology Report | Rebel Our 2020 Java Technology Report explores the most used tools, technologies, and languages for Java developers. See usage statistics and key findings in our report.
SpaceX Boca Chica - Night Ops - Rings and Bulkhead Mate The new bulkhead for Starship SN1 received two steel rings at SpaceX Boca Chica as SpaceXers work the night shift to prepare various elements of the vehicle. Photos and Videos from Mary (@bocachicagal) for NSF Updates: https://forum.nasaspaceflight.com/...
Atlas V Solar Orbiter rollout and Wallops NG-13 Antares & Cygnus tour Atlas V rolls out to its SLC-41 launch pad at Cape Canaveral with Solar Orbiter in Florida AND Northrop Grumman prepares for the NG-13 launch of Antares with Cygnus to the Space Station from Virginia. It's NASASpaceflight's first double-header launch! F...
Failure: Zafar-1 - Simorgh - Imam Khomeini SC - February 9, 2020 -15:48UTC Failure: Zafar-1 - Simorgh - Imam Khomeini SC - February 9, 2020 -15:48UTC
Mobile Blazor Bindings – Getting Started + Why You Should Care TLDR: The Experimental Mobile Blazor Bindings can result in much less XAML and C#, 64% less in my experiment, but the tech isn’t quite ready for prime time. What are Mobile Blazor Bindings? F…
How do Managed Breakpoints work? In this blog entry, I’ll explain how setting source-level breakpoints in a managed debugger work under the hood from end to end.
allocate SocketAsyncEngine less frequenty to reduce the number of epoll_wait threads by adamsitnik · Pull Request #2346 · dotnet/runtime I have been investigating the performance of sockets on Linux using the TechEmpower Plaintext benchmark and a machine from ASP.NET lab with the following spec: E5-1650 v3 @ 3.50 GHz w/ 15MB Cache 6...
torvalds/linux Linux kernel source tree. Contribute to torvalds/linux development by creating an account on GitHub.
NASA Shares Initial Findings from Boeing Starliner Orbital Flight Test Investigation – Commercial Crew Program Following the anomaly that occurred during the December Boeing Starliner Orbital Fight Test (OFT), NASA and Boeing formed a joint investigation team tasked with examining the primary issues, which occurred during that test. Those issues included three spe...
ULA Atlas V 411 - Solar Orbiter - Cape Canaveral SLC-41 - Feb. 9/10, 2020 ULA Atlas V 411 - Solar Orbiter - Cape Canaveral SLC-41 - Feb. 9/10, 2020


Friendly Repository
/pt
Rename | Archive | Delete | Stop
| Questions: | |
|---|---|
|
What is your current IDE/Editor? 80% IntelliJ IDEA family (RubyMine, PhpStorm, WebStorm, etc.)
5% Atom
5% VS Code
2% Emacs or Vim
2% Emacs or Vim
5% Other: Gedit; Cloud9; Nano
|
Active
Show Edit Delete |
|
What is your current IDE/Editor? 80% IntelliJ IDEA family (RubyMine, PhpStorm, WebStorm, etc.)
5% Atom
5% VS Code
2% Emacs or Vim
2% Emacs or Vim
5% Other: Gedit; Cloud9; Nano
|
Pull
Show Edit Delete |


AUDITING AND ACCOUNTING SECTION ABSA BANK OF SOUTH AFRICA, Dear, (TOP SECRET) I am.MR Nathaniel Marcus .the director in charge of auditing and accounting section of ABSA BANK OF SOUTH AFRICA with due respect and regard. I have decided to contact you on a business transaction that will be very beneficial to both of us at the end of the transaction. During our investigation and auditing in this bank, my department came across a very huge sum of money belonging to a deceased person who died on October 31st 1999 in a plane crash and the fund has been dormant in his account with this Bank without any claim of the fund in our custody either from his family or relation before our discovery to this development. The said amount was U.S $25.2M (fifteen million two hundred thousand United States dollars) As it may interest you to know, I got your impressive information through the SOUTH AFRICA chamber of commerce on foreign business relations here in JOHANNESBURG SOUTH AFRICA. Meanwhile all the whole arrangement to put claim over this fund as the bonafide next of kin to the deceased, get the required approval and transfer this money to a foreign account has been put in place and directives and needed information will be relayed to you as soon as you indicate your interest and willingness to assist us and also benefit your self to this great business opportunity. In fact I could have done this deal alone but because of my position in this country as a civil servant (A Banker), we are not allowed to operate a foreign account and would eventually raise an eye brow on my side during the time of transfer because I work in this bank. This is the actual reason why it will require a second party or fellow who will forward claims as the next of kin with affidavit of trust of oath to the Bank and also present a foreign account where he will need the money to be re-transferred into on his request as it may be after due verification and clarification by the correspondent branch of the bank where the whole money will be remitted from to your own designation bank account. I will not fail to inform you that this transaction is 100% risk free. On smooth conclusion of this transaction, you will be entitled to 30% of the total sum as gratification, while 5% will be set aside to take care of expenses that may arise during the time of transfer and also telephone bills, while 65% will be for me and my partners. Please, you have been advised to keep "top secret" as I am still in service and intend to retire from service after we conclude this deal with you. I will be monitoring the whole situation here in this bank until you confirm the money in your account and ask me to come down to your country for subsequent sharing of the fund according to percentages previously indicated and further investment, either in your country or any country you advice us to invest in. All other necessary vital information will be sent to you when I hear from you. I look forward to receive your immediate response through my email<EMAIL_ADDRESS>Yours faithfully, MR. Nathaniel Marcus. AUDITING AND ACCOUNTING SECTION ABSA BANK OF SOUTH AFRICA,


Gecode::Iter::Values::Union< I, J > Class Template Reference
[Value iterators]
Value iterator for the union of two value iterators. More...
#include <values-union.hpp>
Protected Attributes | |
| I | i |
| First iterator. | |
| J | j |
| Second iterator. | |
| int | v |
| Current value. | |
| bool | done |
| Whether iterator is done. | |
Constructors and initialization | |
|
| |
| Union (void) | |
| Default constructor. | |
| Union (I &i, J &j) | |
| Initialize with values from i and j. | |
| void | init (I &i, J &j) |
| Initialize with values from i and j. | |
Iteration control | |
|
| |
| bool | operator() (void) const |
| Test whether iterator is still at a value or done. | |
| void | operator++ (void) |
| Move iterator to next value (if possible). | |
Value access | |
|
| |
| int | val (void) const |
| Return current value. |
Detailed Description
template<class I, class J>
class Gecode::Iter::Values::Union< I, J >
Value iterator for the union of two value iterators.
Definition at line 47 of file values-union.hpp.
Constructor & Destructor Documentation
| Gecode::Iter::Values::Union< I, J >::Union | ( | void | ) | [inline] |
Default constructor.
Definition at line 86 of file values-union.hpp.
| Gecode::Iter::Values::Union< I, J >::Union | ( | I & | i, | |
| J & | j | |||
| ) | [inline] |
Initialize with values from i and j.
Definition at line 119 of file values-union.hpp.
Member Function Documentation
| void Gecode::Iter::Values::Union< I, J >::init | ( | I & | i, | |
| J & | j | |||
| ) | [inline] |
Initialize with values from i and j.
Definition at line 112 of file values-union.hpp.
| bool Gecode::Iter::Values::Union< I, J >::operator() | ( | void | ) | const [inline] |
Test whether iterator is still at a value or done.
Definition at line 125 of file values-union.hpp.
| void Gecode::Iter::Values::Union< I, J >::operator++ | ( | void | ) | [inline] |
Move iterator to next value (if possible).
Definition at line 90 of file values-union.hpp.
| int Gecode::Iter::Values::Union< I, J >::val | ( | void | ) | const [inline] |
Return current value.
Definition at line 131 of file values-union.hpp.
Member Data Documentation
I Gecode::Iter::Values::Union< I, J >::i [protected] |
First iterator.
Definition at line 50 of file values-union.hpp.
J Gecode::Iter::Values::Union< I, J >::j [protected] |
Second iterator.
Definition at line 52 of file values-union.hpp.
int Gecode::Iter::Values::Union< I, J >::v [protected] |
Current value.
Definition at line 54 of file values-union.hpp.
bool Gecode::Iter::Values::Union< I, J >::done [protected] |
Whether iterator is done.
Definition at line 56 of file values-union.hpp.
The documentation for this class was generated from the following file:
- gecode/iter/values-union.hpp (Revision: 11595)