Empirical distribution alternative

Question: BOUNTY:
The full bounty will be awarded to someone who provides a reference to any published paper which uses or mentions the estimator $\tilde{F}$ below.
Motivation:
This section is probably not important to you and I suspect it won't help you get the bounty, but since someone asked about the motivation, here's what I'm working on.
I am working on a statistical graph theory problem.  The standard dense graph limiting object $W : [0,1]^2 \to [0,1]$ is a symmetric function in the sense that $W(u,v) = W(v,u)$.  Sampling a graph on $n$ vertices can be thought of as sampling $n$ uniform values on the unit interval ($U_i$ for $i = 1, \dots, n$) and then the probability of an edge $(i,j)$ is $W(U_i, U_j)$.  Let the resulting adjacency matrix be called $A$.
We can treat $W$ as a density $f = W / \iint W$ supposing that $\iint W > 0$.
If we estimate $f$ based on $A$ without any constraints to $f$, then we cannot get a consistent estimate.
I found an interesting result about consistently estimating $f$ when $f$ comes from a constrained set of possible functions.
From this estimator and $\sum A$, we can estimate $W$.
Unfortunately, the method that I found shows consistency when we sample from the distribution with density $f$.  The way $A$ is constructed requires that I sample a grid of points (as opposed to taking draws from the original $f$).  In this stats.SE question, I'm asking for the 1 dimensional (simpler) problem of what happens when we can only sample sample Bernoullis on a grid like this rather than actually sampling from the distribution directly.
references for graph limits:
L. Lovasz and B. Szegedy. Limits of dense graph sequences (arxiv).
C. Borgs, J. Chayes, L. Lovasz, V. Sos, and K. Vesztergombi. Convergent sequences of dense graphs i: Subgraph frequencies, metric properties and testing. (arxiv).
Notation:
Consider a continuous distribution with cdf $F$ and pdf $f$ which has a positive support on the interval $[0,1]$.  Suppose $f$ has no pointmass, $F$ is everywhere differentiable, and also that $\sup_{z \in [0,1]} f(z) = c < \infty$ is the supremum of $f$ on the interval $[0,1]$.  Let $X \sim F$ mean that the random variable $X$ is sampled from the distribution $F$.
$U_i$ are iid uniform random variables on $[0,1]$.
Problem set up:
Often, we can let $X_1, \dots, X_n$ be random variables with distribution $F$ and work with the
usual empirical distribution function as
$$\hat{F}_n(t) = \frac{1}{n} \sum_{i=1}^n I\{X_i \leq t\}$$
where $I$ is the indicator function. Note that this empirical distribution $\hat{F}_n(t)$ is itself random (where $t$ is fixed).
Unfortunately, I am not able to draw samples directly from $F$.  However, I know that $f$ has positive support only on $[0,1]$, and I can generate random variables $Y_1, \dots, Y_n$ where $Y_i$ is a random variable with a Bernoulli distribution with probability of success
$$p_i = f((i-1+U_i)/n)/c$$
where the $c$ and $U_i$ are defined above.
So, $Y_i \sim \text{Bern}(p_i)$.
One obvious way that I might estimate $F$ from these $Y_i$ values is by taking
$$\tilde{F}_n(t) = \frac{1}{\sum_{i=1}^n Y_i} \sum_{i=1}^{\lceil tn \rceil} Y_i$$
where $\lceil \cdot \rceil$ is the ceiling function (that is, just round up to the nearest integer), and redraw if $\sum_{i=1}^n Y_i = 0$ (to avoid dividing by zero and making the universe collapse).  Note that $\tilde{F}(t)$ is also a random variable since the $Y_i$ are random variables.
Questions:
From (what I think should be) easiest to hardest.

Does anyone know if this $\tilde{F}_n$ (or something similar) has a name?  Can you provide a reference where I can see some of its properties?
As $n \to \infty$, is $\tilde{F}_n(t)$ a consistent estimator of $F(t)$ (and can you prove it)?
What is the limiting distribution of $\tilde{F}_n(t)$ as $n \to \infty$?
Ideally, I'd like to bound the following as a function of $n$ -- e.g., $O_P(\log(n) /\sqrt{n})$, but I don't know what the truth is.  The $O_P$ stands for Big O in probability

$$
\sup_{C \subset [0,1]} \int_C |\tilde{F}_n(t) - F(t)| \, dt
$$
Some ideas and notes:

This looks a lot like acceptance-rejection sampling with a grid-based stratification. Note that it is not though because there we do not draw another sample if we reject the proposal.
I'm pretty sure this $\tilde{F}_n$ is biased.
I think the alternative
$$\tilde{F^*}_n(t) = \frac{c}{n} \sum_{i=1}^{\lceil tn \rceil} Y_i$$
is unbiased, but it has the unpleasant property that $\mathbb{P}\left(\tilde{F^*}(1) = 1\right) < 1$.
I'm interested in using $\tilde{F}_n$ as a plug-in estimator.
I don't think this is useful information, but maybe you know of some reason why it might be.

Example in R
Here is some R code if you want to compare the empirical distribution with $\tilde{F}_n$.
Sorry some of the indentation is wrong... I don't see how to fix that.
<code># sample from a beta distribution with parameters a and b
a <- 4 # make this > 1 to get the mode right
b <- 1.1 # make this > 1 to get the mode right
qD <- function(x){qbeta(x, a, b)} # inverse
dD <- function(x){dbeta(x, a, b)} # density
pD <- function(x){pbeta(x, a, b)} # cdf
mD <- dbeta((a-1)/(a+b-2), a, b) # maximum value sup_z f(z)

# draw samples for the empirical distribution and \tilde{F}
draw <- function(n){ # n is the number of observations
  u <- sort(runif(n))
  x <- qD(u) # samples for empirical dist
  z <- 0 # keep track of how many y_i == 1
  # take bernoulli samples at the points s
  s <- seq(0,1-1/n,length=n) + runif(n,0,1/n)
  p <- dD(s) # density at s
  while(z == 0){ # make sure we get at least one y_i == 1
    y <- rbinom(rep(1,n), 1, p/mD) # y_i that we sampled
    z <- sum(y)
  }
  result <- list(x=x, y=y, z=z)
  return(result)
}

sim <- function(simdat, n, w){
  # F hat -- empirical dist at w
  fh <- mean(simdat$x < w)
  # F tilde
  ft <- sum(simdat$y[1:ceiling(n*w)])/simdat$z
  # Uncomment this if we want an unbiased estimate.
  # This can take on values > 1 which is undesirable for a cdf.
  ### ft <- sum(simdat$y[1:ceiling(n*w)]) * (mD / n)
  return(c(fh, ft))
}

set.seed(1) # for reproducibility

n <- 50 # number observations
w <- 0.5555 # some value to test this at (called t above)
reps <- 1000 # look at this many values of Fhat(w) and Ftilde(w)
# simulate this data
samps <- replicate(reps, sim(draw(n), n, w))

# compare the true value to the empirical means
pD(w) # the truth
apply(samps, 1, mean) # sample mean of (Fhat(w), Ftilde(w))
apply(samps, 1, var)  # sample variance of (Fhat(w), Ftilde(w))
apply((samps - pD(w))^2, 1, mean) # variance around truth

# now lets look at what a single realization might look like
dat <- draw(n)
plot(NA, xlim=0:1, ylim=0:1, xlab="t", ylab="empirical cdf",
     main="comparing ECDF (red), Ftilde (blue), true CDF (black)")
s <- seq(0,1,length=1000)
lines(s, pD(s), lwd=3) # truth in black
abline(h=0:1)
lines(c(0,rep(dat$x,each=2),Inf),
     rep(seq(0,1,length=n+1),each=2),
     col="red")
lines(c(0,rep(which(dat$y==1)/n, each=2),1),
      rep(seq(0,1,length=dat$z+1),each=2),
      col="blue")
</code>

EDITS:
EDIT 1 --
I edited this to address @whuber's comments.
EDIT 2 --
I added R code and cleaned it up a bit more.
I changed notation slightly for readability, but it is essentially the same.
I'm planning on putting a bounty on this as soon as I'm allowed to, so please let me know if you want further clarifications.
EDIT 3 --
I think I addressed @cardinal's remarks.
I fixed the typos in the total variation.
I'm adding a bounty.
EDIT 4 --
Added a "motivation" section for @cardinal.
Comment: A couple of other questions/remarks: It seems implicitly based on how you are proposing to construct $p_i$ that you are really considering a triangular array $Y_{i,n}$, $i=1,\ldots,n$ for the purposes of convergence analysis. From how you construct the $p_i$, it seems you should also be able to (just as easily) sample Bernoulli random variables with conditional probability of success $f(U)/c$ where $U$ is a uniform random variable. Is that true? (A little more context to your question would likely resolve a lot of these queries.) Cheers.
Comment: This question has been improved so much I didn't even recognize it until I realized I'd seen the comments before. It's now a really interesting and much more well-written question.
Comment: Your question started to become ambiguous the moment you referred to undefined objects and to use some idiosyncratic notation. For instance, $f$ appears early on but has no apparent connection to $F$ and it is only by reading much further that we learn you're thinking of it as "not a discrete distribution"--but what kind of object is it? Crucially, what does "$\sup_z f(z)$ mean? "$\sup$" usually means *supremum* but maybe it has something to do with the essential support of a distribution? Because everything in the question depends on what these mean, I cannot make sense of the question.
Comment: Thanks @whuber for your comments.  Please let me know if the revised question is still confusing.
Comment: Aha! That's the first indication I have seen that $n$ is not fixed and that you are interested in the asymptotics. If it's true you have flexibility to choose $n$, doesn't that open up a wealth of possibilities, such as adaptive choices of the sample points (rather than limiting to a fixed grid $\{i/n\}$)? It is also evident you are making unstated assumptions, such that $f$ is continuous (equivalently, $F$ is *absolutely continuous*). What else can you assume about the underlying distribution $F$ that can help with this analysis?
Comment: I don't actually have any data. I have a paper that says something like "if you use the standard plug-in estimator here, then this thing (that I haven't described) that you're trying to bound is order $n^{-1}\log(n)$". Unfortunately, I can't use the standard plug-in estimator based on the empirical distribution because it is impossible for me to sample from the distribution $F$. I can take samples along the unit interval wherever I want though, but I have to specify where I'm taking them before I am told what $F$ is.  Once I have said where I'm going to take them, then I can sample the $Y_i$.
Comment: Some remarks: (**1**) Ignoring for a moment the imprecision of the statement itself, note that "$f$ has no pointmass" is not equivalent to $F$ being differentiable everywhere (counterexample?). (**2**) Should the $c$ be outside of $f$ in the definition of $p_i$? (**3**) The definition of TV distance you give seems unconventional, is discordant with the intuition behind it and doesn't match the link you provided. Maybe these are just typos? (**4**) Do you know $f$ explicitly or can you only sample "implicitly" as you describe (in your application)?
Comment: (...) (ii) with potentially superior properties. (**3**) I would suggest you consider a little more flexibility with regard to the bounty. You may be surprised at some of the answers you get and awarding it too quickly may stunt that process to a certain degree.
Comment: Fair enough. Thanks for the response. My main point of raising the issue of the sampling scheme was to address the *theory*, i.e., with (presumably) no extra work to sample as I've described (compared to the scheme you've laid out), one can obtain a more recognizable estimator with behavior that will be (I think) very easy to compare to the empirical distribution function.
Comment: (Continued). Why do you introduce $y_0$? What role does it play?  What does "$\text{Var}(\hat{F_n}(t))$" mean when $\hat{F_n}$ is a distribution--and so $\hat{F_n}(t)$ would be a *number*? Are you implicitly replacing the $x_i$ in the definition of $\hat{F_n}$ by $X_i$ or do you intend $\text{Var}(\hat{F_n})$? The risk in trying to write your entire background and question in mathematical notation is that a single little slip  can render the entire thing nonsensical, so it would really help to see a bit of English explanation of terminology and context.
Comment: Thanks--I am glad I asked for those details, because obviously I *was* misreading some of the notation. I'm still struggling to understand what's going on. The first thing I notice is that the denominator in $\tilde{F}_n(t)$ could have a substantial chance of being zero, making this--to put it mildly--rather an awkward estimator. I know you have tried to rule that out by *fiat*, but the possibility really has to be considered in assessing the properties of the estimator. Also, is the asymmetry inherent? Do you truly sample $1=n/n$ but never $0=0/n$?
Comment: Since $f$ is continuous and has no point mass, as $n \to \infty$ it isn't going to cause much of a problem for me that I never sample at 0.  One hack around this is to first sample $U_i$ in the interval $[(i-1)/n, i/n)$ and then sample $Y_i \sim \text{Bern}(f(U_i) / (\sup_{z \in [0,1]}))$ which is possible in my situation.
Comment: (The indentation problems in the code are a bug resulting from an interaction with the $\TeX$ markup: unbalanced dollar signs result in the subsequent lines being indented.  The only workaround I have found is to place a comment after any line having an odd number of dollar signs and to insert an odd number of dollar signs within the comment, as in `#$`.)
Comment: I am going to be nitpicky; please take it as a sign of my interest. (**1**) The expression given for TV is still incorrect. Consider two random variables, one is $\mathcal U(0,1/2)$ and the other is $\mathcal U(1/2,1)$. The TV distance between them is 1 (Choose $C = (0,1/2)$, for example), but your expression yields 1/2. (**2**) I would really like to know if you are married to the sampling scheme you have described. My last comment asks about an alternate sampling scheme. The purpose is to potentially give you an estimator that is (i) easier to analyze and (...)
Comment: I removed all references to total variation in the above question because I saw that you were correct and what I'm interested in is not the same as total variation. Yes, I am married to that sampling scheme. This isn't for data analysis or MCMC simulation, it's for a theory paper I'm working on. I really want to just cite some paper and say "this is what s/he did", and be done with it. Thanks for your comment regarding the bounty. This is the first time I've used one, so if I'm not satisfied with the responses I get, I'll just answer more questions and set up another bounty on this problem.
Comment: Items 2 and 4 can be proved by very pedestrian arguments. Item 4 yields $\mathcal O_P(n^{-1/2})$ at the very least. Item 3 is slightly complicated by the fact that $\sqrt{n} (\tilde F_n(t) - \tilde F_n^{\star}(t)) \to \mathcal N(0,\sigma^2)$ in distribution for $\sigma^2$ which is a function of $F(t)$, $c$ and $\int f^2$. In the aforementioned sense, these two estimators are not as "close" to one another as one might hope. Also, $\tilde F_n^{\star}(t)$ is not unbiased, as a straightforward calculation will show.
Comment: @user: Can you provide a reference (or two) that motivated your original consideration of this sampling scheme and estimator? That would provide helpful context, I think.
Comment: @cardinal, I added my motivation for this problem.  I hope that it's helpful (though regretfully, I suspect it won't be).
Comment: That's a fantastic update and gives a much clearer picture of what you're interested in and what potential connections to other problems might be. This $W$ function employed as you describe essentially looks like some generalization of how one might construct a random version of a classical threshold graph. Thanks!
Comment: indeed it is related:  http://www-stat.stanford.edu/~susan/papers/threshold0817.pdf
Comment: Resembles intensity estimation for some restricted point process. It may have a name in survival analysis...
Answer: While this reference
EDIT: ADDED REFERENCE TO VERY SIMILAR STATISTIC
"Nonparametric Estimation from Incomplete Observations" E. L. Kaplan and Paul Meier, Journal of the American Statistical Association, Vol. 53, No. 282 (Jun., 1958), pp. 457-481
is not to your ECDF-like estimator on $[0,1]$ I believe it is logically equivalent to the Kaplan-Meier estimator (aka.  product limit estimator) as used in Survival Analysis, even though that's applied to a time range $[0,\infty)$.
Estimating the bias would be possible once you have a reasonable estimate of the distribution via kernel smoothing if it is well enough behaved (see, e.g., Khmaladze transformation on Wikipedia).
In the bivariate case in your graph problem estimating $f = W / \iint W$ from $A$ albeit with a trivial symmetry constraint seems similar to the approach in Jean-David Fermanian, Dragan Radulovic, and Marten Wegkamp (2004), Weak convergence of empirical copula processes, Bernoulli, vol. 10, no. 5, 847–860, as @cardinal indicated "Multivariate Delta Method".
Answer: This answers questions 2 and 3 above.  I still really want a reference though (from question 1).
This doesn't yet take into account when $\sum Y_i = 0$.
Consider $g(A,B) = A/(A+B)$, then
\begin{align}
  g_A(A,B) &= (A+B)^{-1} + A(A+B)^{-2}\\
  g_B(A,B) &= -A(A+B)^{-2}\\
  g_{AA}(A,B) &= 2B(A+B)^{-3}\\
  g_{AB}(A,B) &= (A-B)(A+B)^{-3}\\
  g_{BB}(B,B) &= 2A(A+B)^{-3}
\end{align}
where the subscripts denote the derivatives.
Recall $p_i = f((i-1+U_i)/n)/c$.
Let
\begin{align}
  R = \frac{1}{n}\sum_{i=1}^{\lceil nt \rceil} Y_i, \quad&
  \mu_R = \mathbb{E}(R) = \int_0^t p(u) \,  d  u = c^{-1}F(t)\\
  S = \frac{1}{n}\sum_{\lceil nt \rceil +1}^n Y_i, \quad&
  \mu_S = \mathbb{E}(S) =  \int_t^1 p(u) \,  d  u = c^{-1}(1-F(t))
\end{align}
So note that
$\mu_R + \mu_S = c^{-1}F(t) + c^{-1}(1-F(t)) = c^{-1}$
and $g(\mu_R, \mu_S) = F(t)$.
Also,
\begin{align}
  \text{ Var}(R)
  &= \frac{1}{n^2} \sum_{i=1}^{\lceil nt \rceil} \text{ Var}(Y_i)
  = \frac{1}{n} \int_0^t f(u)/c(1-f(u)/c) \, d u
  = \frac{1}{nc^2} \int_0^t f(u)(c-f(u)) \, d u\\
  \text{ Var}(S)
  &= \frac{1}{nc^2} \int_t^1 f(u)(c-f(u)) \, d u
\end{align}
Note that
$\text{ Cov}(R,S) = 0$ by independence of the $Y_i$s.
Now, we use a taylor expansion to get
\begin{align}
  &\mathbb{E}\left(\tilde{F}_n(t)\right)
  =\mathbb{E}\left(
    \frac{1}{\sum_{i=1}^n Y_i} \sum_{i=1}^{\lceil tn \rceil} Y_i
  \right)
  =\mathbb{E}\left(\frac{nR}{nR+nS}\right)
  =\mathbb{E}\left(\frac{R}{R+S}\right)
  =\mathbb{E}\left(g(R,S)\right)\\
  &=g(\mu_R,\mu_S)
  + \frac{1}{2}\mathbb{E}((R - \mu_R)^2)g_{RR}(\mu_R, \mu_S)
  \nonumber\\  &\quad
  + \mathbb{E}((R - \mu_R)(S-\mu_S))g_{RS}(\mu_R, \mu_S)
  + \frac{1}{2}\mathbb{E}((S - \mu_S)^2)g_{SS}(\mu_R, \mu_S)
  + \dots
  \\
  &= F(t)
  + \frac{1}{2}\mathbb{E}((R - \mu_R)^2)2\mu_S(\mu_R+\mu_S)^{-3}
  \nonumber\\  &\quad
  + \mathbb{E}((R - \mu_R)(S-\mu_S))(\mu_R-\mu_S)(\mu_R+\mu_S)^{-3}
  \nonumber\\  &\quad
  + \frac{1}{2}\mathbb{E}((S - \mu_S)^2) 2\mu_R(\mu_R+\mu_S)^{-3}
  + \dots\\
  &= F(t)
  + (\mu_R+\mu_S)^{-3}
  \bigg(
    \mathbb{E}((R - \mu_R)^2)\mu_S
    + \mathbb{E}((R - \mu_R)(S-\mu_S))(\mu_R-\mu_S)
  \nonumber\\  &\quad
    + \mathbb{E}((S - \mu_S)^2) \mu_R
  \bigg)
  + \dots \\
  &= F(t)
  + c^3
  \left(
    \text{ Var}(R)c(1-F(t)) \right.
  \nonumber\\  &\quad
    + \left.\text{ Cov}(R,S)(cF(t) - c(1-F(t)))
    + \text{ Var}(S) cF(t)
  \right)
  + \dots \\
  &= F(t)
  + c^4
  \left(
    \left(\frac{1}{n} \int_0^t f(u)(c-f(u)) \, d u\right) (1-F(t))
\right.   \nonumber\\  &\quad \left.
    + \left(\frac{1}{n} \int_t^1 f(u)(c-f(u)) \, d u \right) F(t)
  \right)
  + \dots\\
  &= F(t) + \tilde{V}_{F(t)}/n + \dots\\
  &= F(t) + {\cal O}(n^{-1})
\end{align}
where
\begin{align}
\tilde{V}_{F(t)}
  &=
  c^2\left(\int_0^t f(u)(c-f(u)) \, d u\right) (1-F(t))
  + c^2\left(\int_t^1 f(u)(c-f(u)) \, d u \right) F(t)\\
  &< c^2\left( \int_0^t cf(u) \, d u\right)(1 - F(t))
  + c^2\left( \int_t^1 cf(u) \, d u\right)F(t)\\
  &< c^3 2F(t)(1-F(t))
\end{align}
In particular, we get
\begin{align}
  \sqrt{n}\left(\tilde{F}_n(t) - F(t)\right)
  \overset{d}{\to}
  N(0,V_{F(t)})
\end{align}
Please comment if you see something wrong with this.
EDITS:
Edit 1 --
Fixed a typo in $V_{F(t)}$.
Thanks @cardinal for your suggestion in the comments about question 4.
Edit 2 --
Fixed plenty of typos: I had $c^{-1}$ where I should have had $c$ in many places.
I still need to address @cardinal's response about $\sum Y_i = 0$.
Comment: (**3**) Item 4 in your list is handled as follows. Note that $$\sup_{C\subset [0,1]} \int_C |\tilde F - F| \leq \sup_{[0,1]} |\tilde F - \tilde F^{\star}| + \int_0^1 |\tilde F^\star - \mathbb E \tilde F^\star| + O(n^{-1})\>.$$ The first term on the right-hand side, $\{\sum_i Y_i > 0\}$, is $\leq |1 - c n^{-1}\sum_i Y_i|$, so is clearly $\mathcal O_p(n^{-1/2})$. You're left only to deal with the middle term, but that succumbs readily to Markov's inequality followed by Jensen's and is also $\mathcal O_p(n^{-1/2})$.
Comment: Dear @user: This is on the right track; here are some suggestions. (**1**) The mean of $\tilde F_n(t)$ doesn't exist, at least not until you specify what happens when $\sum_i Y_i = 0$, so strictly speaking the analysis in the answer is not correct. Defining a behavior at zero will break the independence structure, but all is not lost. (**2**) Essentially, what you're doing is applying the multivariate delta method. Note that this *doesn't* require the existence of the mean of $\tilde F_n(t)$, so it will be cleaner (and more correct) if you go this route.
Comment: Dear @user: It would be helpful to see some more elaboration to your remark regarding not needing to considering the case $\sum_i Y_i = 0$. What you are describing is conditional sampling. The $Y_i$ conditional on $\{\sum_i Y_i > 0\}$ are *not* independent (or conditionally independent), so the (implicit) analysis in the answer does not hold. It may be helpful to look at the $n=2$ case to see this (just draw the $2 \times 2$ table).
Comment: As an additional aside, it may be worth noting that $\sup_C \int_C |\tilde F - F|  = \int_0^1 |\tilde F - F|$, so this definition can be simplified.

Empirical distribution alternative


What kind of objects act on bounded linear operators?

Question: I am currently studying for a first course in operator theory, and I was wondering about the following that occurred to me whilst doing my reading:
It seems to me that, by talking about maps in general we have a process that allows us to change from very "basic" mathematical objects, such as a point, to more and more complex objects.
For example:
Suppose $n$ is a natural number. We can think of the set $\mathbb{R}$ as the vector space of all the possible (continuous) functions $n \mapsto x_n \in \mathbb{R}$. In the next step we have the vector space $C(\mathbb{R})$ of all possible continuous functions $\mathbb{R} \ni x \mapsto f(x)$. And then there is the vector space $\mathcal{C}(C(\mathbb{R}))$ of all possible continuous operators $C(\mathbb{R}) \ni f \mapsto Af$.
So in each step we take the previous object and think about all possible continuous functions on it. The thing I was wondering about is - what are the objects that we use in the next step ? That is, what objects act on the space $\mathcal{C}(C(\mathbb{R}))$ ?
\begin{equation}
n \to \mathbb{R} \to C(\mathbb{R}) \to \mathcal{C}(C(\mathbb{R})) \to \, ?
\end{equation}
I realize this question might be very stupid, I hope it makes sense at least .. appologies in case not, I am just starting to learn about operators. Thanks for your help !
EDIT: the notation $\mathcal{C}(C(\mathbb{R}))$ might not be the one that is used commonly, so far I have only seen linear operators and their common notation, in case somebody could hint towards the proper notation that would be great ! I shall also have a look at books to find out, but until that I appologize if the notation looks extravagant
Comment: This does not look convincing to me at all. The passage from $C(\mathbb{R})$ to $\mathcal{B}(C(\mathbb{R}))$ is not that much analogous than the one from $\mathbb{R}$ to $C(\mathbb{R})$, because one case is concerned with linearity and the other one isn't. And I don't understand what you mean by $n\to \mathbb{R}$ or $n\mapsto \mathbb{R}$.
Comment: @Florian: For any singleton, e.g. $\{n\}$, there is an obvious correspondence between $\Bbb R$ and the set of maps from the singleton to $\Bbb R$; that's what harlekin is talking about for his first step.
Comment: @Florian: thanks for your comment! The map you wondered about looked strange indeed, what Brian M. Scott suggests is what I wanted to write. I edited the post accordingly. With regards to the second step - you are right the process looses generality in that it restricts to linear maps (operators) on the preceeding space. I could probably reduce the post to the question "what are the maps that act on bounded linear operators ?" ..
Comment: Well, once you have a vector space, you can always take the dual. But this may not be what you are looking for.
Comment: @M Turgeon: that's a very good point - though the dual would then "collapse" everything back to $\mathbb{R}$ (roughly speaking). I was rather looking for a space of maps $\mathcal{B}(C(\mathbb{R})) \to \mathcal{B}(C(\mathbb{R})) $. But in any case, what you say partly answers the question, thanks for pointing this out!
Comment: @harlekin In the first and second step you apply $C(\cdot, \mathbb R)$, i. e. you take *all* continuous mappings from the space you have to $\mathbb R$. In the third step you take all *linear* mappings *to* $C(\mathbb R)$. So IMO you are doing different things in different steps, so it is not possible to tell, what the next step should be.
Comment: @martini I have edited the question accordingly so that it is now more clear (hopefully), my initial restriction to linear operators was due to the fact that I am just a beginner in operator theory, so I haven't seen anything on non - linear operators hence I was a little scared to mention them. But it seems it makes the question unclear, as Florian already mentioned this issue
Answer: When you say "continuous functions on $C(\mathbb{R})$", you don't say what topology you are taking. The most natural choice is probably uniform convergence (because it makes it complete); but then you get a topological space which is not particularly nice, as it is not locally compact. And I don't think much can be said about the set of continuous functions over a non-LC space.


Is $(ab+1)^{a^n}-1$ always divisible by $a^{n+1}b$?

Question: Let $a,b,n\in\mathbb{Z}^+$, and consider the expression $(ab+1)^{a^n}-1$. No matter which positive integers I try, I always get that $(ab+1)^{a^n}-1$ is divisible by $a^{n+1}b$. Can this be true in general?
Let's try to find out! By the binomial theorem, $$(ab+1)^{a^n}=\sum_{k=0}^{a^n}\binom{a^n}{k}(ab)^{k}.$$
It seems like all terms but the first (which equals $1$) should be divisible by $a^{n+1}b$, and then the claim would follow. However, it this intuition actually correct?
Note: For a prime $p$, we know that $\binom{p}{r}$ is divisible by $p$. But $a^n$ is not necessarily prime here.
Answer: To prove by induction on $n$, the base case $n = 0$ is trivial. Now suppose $a^n b \mid (ab + 1)^{a^{n - 1}} - 1$. Because$$
(ab + 1)^{a^n} - 1 = ((ab + 1)^{a^{n - 1}} - 1) \left( \sum_{k = 0}^{a - 1} ((ab + 1)^{a^{n - 1}})^k \right),
$$
and$$
\sum_{k = 0}^{a - 1} ((ab + 1)^{a^{n - 1}})^k \equiv \sum_{k = 0}^{a - 1} 1 \equiv 0 \pmod{a} \Longrightarrow \left. a \,\middle|\, \sum_{k = 0}^{a - 1} ((ab + 1)^{a^{n - 1}})^k \right.,
$$
then$$
\frac{(ab + 1)^{a^n} - 1}{a^{n + 1} b} = \frac{(ab + 1)^{a^{n - 1}} - 1}{a^n b} · \frac{1}{a} \sum_{k = 0}^{a - 1} ((ab + 1)^{a^{n - 1}})^k \in \mathbb{Z},
$$
i.e.$$
\left. a^{n + 1} b \,\middle|\, (ab + 1)^{a^n} - 1 \right..
$$
End of induction.
Comment: Never mind, I see where I missed.  Just deleted my comments.   Confused summing 1's with summing consecutive numbers.
Answer: Mind that
$$
(1+x)^n = 1+n x+ \frac{n(n-1)}{2!}x^2+\cdots+x^n
$$
and
$$
(1+x)^n - 1 = n x+ \frac{n(n-1)}{2!}x^2+\cdots+x^n
$$
or
$$
(1+ab)^{a^n} - 1 = a^{n+1}b P(a,b)
$$
hence
$$
(1+ab)^{a^n} - 1 \equiv 0 \mod a^{n+1}b
$$
Comment: How do you prove that $\binom{a^n}{k}$ is divisible by $a^{n+1-k}$? This is essentially what the third equality says.
Comment: Why does the third equality follow? This step is what I'm trying to prove!
Comment: It is sufficient that $a > 1$ in which case $a ^ n > n + 1$ Mind that the last expansion term is $(ab)^{a^n}$


Proving $\lambda(ab) = \mathrm{lcm}\{\lambda(a),\lambda(b)\}$ where $\lambda(.)$ is Carmichael's Function

Question: In proving :

if $a$ and $b$ are coprime integers then $\lambda(ab) = \mathrm{lcm}\{\lambda(a),\lambda(b)\}$

where $\lambda(.)$ is Carmichael's Function
where does $a$ and $b$ are coprime is used?
One proof is here  (lemma 6)
Comment: @labbhattacharjee Would you mind explaining the statement?
Actually, I want to know why if that condition is removed then the property doesn't hold?
Comment: @BalarkaSen I corrected it. Thanks.
Comment: This is an immediate consequence of the recursive definition (http://en.wikipedia.org/wiki/Carmichael_function#Composition)
Comment: @MahdiKhosravi, $\lambda(8)=2\iff a^2\equiv1\pmod{2^3}$ if $(a,2)=1$ and $\lambda(6)=2$ But, $\lambda(8\cdot6)=?$ try with $a=5$
Answer: It is used implicitly in the paragraph preceding Lemma 6, namely
$$\rm\lambda_{ab}\mid n\!\!\overset{\ Lem3}\iff\! x^{n}\!\equiv 1\,\ (mod\ ab)\ \color{#c00}\Leftarrow\!\!\!\!\!\overset{CRT\ \ \ \ \  }\Rightarrow\!\!  \begin{array}{}x^{n}\!\equiv 1\,\ (mod\ a)\\ \rm x^{n}\!\equiv 1\,\ (mod\ b)\end{array}\!\!\overset{\ Lem3}\iff\! \lambda_a,\lambda_b\mid n\!\iff\! lcm(\lambda_a,\lambda_b)\mid n $$
$(\color{#c00}\Leftarrow)$ needs $\rm\,(a,b)= 1,\,$ i.e. $\rm\,a,b\mid c\!\iff\! {\rm lcm}(a,b)\mid c,\, $ and $\rm\,{\rm lcm}(a,b) = ab\iff (a,b)=1.$
Comment: For $n = \lambda_{ab}$ the $(\Rightarrow)$ gives ${\rm lcm}(\lambda_a,\lambda_b)\mid \lambda_{ab}.$ For $\,n={\rm lcm}(\lambda_a,\lambda_b)\,$ the $(\Leftarrow)$ gives $\,\lambda_{ab}\mid {\rm lcm}(\lambda_a,\lambda_b).\,$ So they are equal, dividing each other.
Comment: Thanks. But why does it need to be correct in the other direction?
Comment: @Mahdi I edited the answer to make it clearer how the other direction is used, i.e. the deduction is a series of $\iff$ equivalences. The linked proof is not as clear as it could be.
Comment: Why do the right-arrows aren't enough to prove the statement?


Multiple filters in mongoDB

Question: Theres is a part of my application where i can specify some filters to retrieve certain data. But not all the filters are necessary so i can left some of them empty and the query just wouldn't use them. How can i achieve this in mongoDB. Thanks in advance.
client-side:
        $('#filter').click(function(e){
        e.preventDefault();
        var filters = JSON.stringify({ Marca : $('#Marca').val(), Modelo : $('#Modelo').val(), Fecha : $('#Fecha').val()});

            $.ajax({
            type: 'POST',
            data: filters,
            url: '/filterFees',
            contentType: 'application/json'
            }).done(function( response ) {
                if(response.msg === ''){
                    filterFees(response.data);
                }
                else {
                    alert('Error: ' + response.msg);
                }
            })
        })

node.js(using monk):
app.post('/filterFees', function(req, res){
  var db = req.db;
  var collection = db.get('Fees');

  collection.find({'Marca' : req.body.Marca, 'Modelo' : req.body.Modelo, 'Fecha' : req.body.Fecha, },{},function(err,docs){
        res.send((err === null) ? { msg: '', data : docs } : { msg:'error: ' + err });
    });
})

Answer: Check if there the value exists in the filters
var filter = {}, filters;
if $('#Marca').val()
    filter.Marca = $('#Marca').val();

if $('#Modelo').val()
    filter.Modelo = $('#Modelo').val();

if $('#Fecha').val()
    filter.Fecha = $('#Fecha').val()

filters = JSON.stringify(filter);

and find data where filters
collection.find(req.body,{},function(err,docs){
    res.send((err === null) ? { msg: '', data : docs } : { msg:'error: ' + err });
});

PS. not sure why you stringify the parameters
instead of sending object
Comment: Thanks a lot, it worked!. I use the  `JSON.stringify()` because of the `contentType`. Otherwise i get an error 400 (Bad Request).

Multiple filters in mongoDB


Using machine learning to compare the probability of success of two different treatment strategies

Question: I would like to preface by saying I am relatively new in the world of machine learning, however I have a decent background in statistics.
I have a large database of patients who underwent a certain procedure. This database contains patient information, as well as the outcome of the procedure (success or failure). There are two different treatment strategies used for this type of procedure, let's call them A and B.
What I want to do is create "calculator" that will take user input on the various patient characteristics and then output the strategy that has the highest chance of success for this particular patient.
For example, let's say we have 3 patient characteristics (there are more in the actual database): age, gender, and BMI.
User input:
Age = 58
Gender = Male
BMI = 28
Output: Strategy A has a better chance of success
I came up with a potential way to do this, by creating two models (eg logistic regression), one for each strategy, and training them and testing them using my database. Then I will get user input for the patient characteristics and use those in each model to get the probability of success for each strategy (using model.predict_proba in python). Lastly, I will compare the two probabilities and suggest the strategy with the highest value.
I am not sure if this is a correct way of approaching this problem, or if there is a better method.
Thank you in advance for the help!
Comment: It's a particular version of causal inference on observational data, where you don't want to just compare the treatments, but even figure out whether there are subsets of patients with differential efficacy (which [even for a randomized trials you'd need a much larger sample size than for just the treatment main effect](https://statmodeling.stat.columbia.edu/2018/03/15/need-16-times-sample-size-estimate-interaction-estimate-main-effect/)).
Comment: I don't think you need two models. You can simply fit a single model to your data and then for the new data have two versions that are only different with respect to the strategy. Then predict the probability of success for both of them and choose the one with higher probability of success.
Comment: Your two LRs are equivalent to a single one with every model term having an interaction with treatment (assuming you penalize the same way), still needs making sure to adjust for confounders the right way or propensity score strategy or the like on top.
Comment: Thank you very much for your comments AminShn and @Björn. So, if I am getting this correctly, you suggest creating a single model that accounts for the interaction of each variable with the treatment strategy and then running it twice for new data (once for each strategy), and comparing the probability of success with each strategy?
Comment: Since in your title you're saying Machine Learning I assume using something like Random Forest, Neural Nets, and etc that automatically take care of the interactions among variables. So yes, I would train an ML algorithm with the strategy as a binary input among other inputs. After training the model, for predicting for a new situation, I keep all inputs fixed except for strategy predicting two probabilities for each strategy and then deciding based on the results of their outcome.
Answer: Following my comments, I have made an example to show my suggested approach. First I simulate some data with a binary outcome, and two continues predictors and a binary variable for strategy:
# Some R code to simulate data

library(boot) # Package contains the logit transform

T <- 1000
set.seed(123)
x_1 <- runif(T, 0, 10)
x_2 <- runif(T, 0, 10)
strategy <- c(rep(1,T/2), rep(0,T/2))
alpha <- 1
beta_1 <- 0.2
beta_2 <- -0.5
beta_3 <- 0.4
logit_p <-  alpha + beta_1 * x_1 + beta_2 * x_2 + beta_3 * strategy
p <- inv.logit(logit_p)
y <- rbinom(T, 1, p)

df = data.frame(y = as.factor(y), x1 = x_1, x2 = x_2, x3 = strategy)

Then I fit a random forest model to the data:
# -- fitting random forest
library(randomForest)
library(dplyr)

rf.fit = randomForest(y ~ ., data = df[1:T-1,]) # I keep the last row out as future observation

For brevity I skipped the cross-validation and hyperparameter tuning steps here. Now we use the fitted model to predict the probability of the outcome for both scenarios (using strategy 1 and 2):
strategy_1 = df[T,]
strategy_2 = strategy_1 %>% mutate(x3 = 1) # switching the strategy of the query from 0 to 1

prob_1 = predict(rf.fit, newdata = strategy_1 ,type="prob")
prob_2 = predict(rf.fit, newdata = strategy_2 ,type="prob")

# --- Printing probability of success for each strategy
print(prob_1[2])
print(prob_2[2])

> print(prob_1[2])
[1] 0.192
> print(prob_2[2])
[1] 0.222

As we expected (according to the beta_3 coefficient), strategy 2 is more favourable showing higher probability of success.
Answer: What you're referring to is estimating an optimal treatment rule. Assuming you can satisfy certain causal assumptions, one approach for this is using a counterfactual framework. Denote the set of all possible treatment rules as $\mathcal{D}$ , the rule $d$ that maximizes the counterfactual $E[Y_d]$ is the optimal rule.
$$
d_{\text{opt}} \equiv \text{arg max}_{d \in \mathcal{D}} E [Y_{d}]
$$
A strategy to do this is to learn the conditional average treatment effect (CATE); this is frequently referred to as the blip function in this scenario: $E[Y_1 - Y_0 | V]$ where $V$ is the set of variables you want to use to define your rule. If you want to maximize $E[Y_d]$, then you would assign individuals to the treatment group where the blip function is positive, and to the control where the blip function is negative.
A valid way to do all this, and incorporate machine learning is to:

Estimate the efficient influence function of the average treatment effect using a machine learning approach of your choice.

Regress this on the set of variables $V$ using a machine learning algorithm of your choice.

Generate predictions from this model as your estimate of the CATE

Assign treatment according to the sign of the CATE for each individual

For an example of all this used in a real study, see this paper (https://academic.oup.com/aje/advance-article/doi/10.1093/aje/kwac217/6957041).
Applying this to your example:
{r}
T <- 1000
set.seed(123)
x_1 <- runif(T, 0, 10)
x_2 <- runif(T, 0, 10)
strategy <- c(rep(1,T/2), rep(0,T/2))
alpha <- 1
beta_1 <- 0.2
beta_2 <- -0.5
beta_3 <- 0.4
logit_p <-  alpha + beta_1 * x_1 + beta_2 * x_2 + beta_3 * strategy
p <- boot::inv.logit(logit_p)
y <- rbinom(T, 1, p)

df = data.frame(y = as.factor(y), x1 = x_1, x2 = x_2, x3 = strategy)

Estimate the efficient influence function of the average treatment effect using a machine learning approach. In this case using a Super Learner with a GLM and random forest.
library(dplyr)
library(SuperLearner)

learners = c("SL.glm", "SL.randomForest")

propensity.fit <- SuperLearner(df$x3, df[, c("x1", "x2")], family = "binomial", SL.library = learners)

propensity <- predict(propensity.fit, onlySL = TRUE)$pred[, 1]

y.fit = SuperLearner(df$y, df[, c("x1", "x2", "x3")], family = "binomial", SL.library = learners)

ya <- predict(y.fit, onlySL = TRUE)$pred[, 1]
y1 <- predict(y.fit, mutate(df, x3 = 1), onlySL = TRUE)$pred[, 1]
y0 <- predict(y.fit, mutate(df, x3 = 0), onlySL = TRUE)$pred[, 1]

eif_ate <- ((2*df$x3 - 1) / propensity) * (df$y - ya) + y1 - y0

Estimate the blip function by regressing the EIF of the ATE on $V$ and then predicting
blip.fit <- SuperLearner(eif_ate, df[, c("x1", "x2")], SL.library = learners)
blip <- predict(blip.fit, onlySL = TRUE)$pred[, 1]

Assign treatment according to the sign of the blip for each individual. In this scenario, there is no treatment effect heterogeneity, so everyone should be assigned treatment.
d <- ifelse(blip > 0, 1, 0)
# or if you want to minimize Y
# ifelse(blip < 0, 1, 0)
table(d)


C++ Pointers and Functions with no return - need to recall the output as a pointer

Question:
Write a C++ code that calls the function add_three() that takes three float numbers and add them together, the function should not return anything, and the output variable should be passed as an input to the function. Note: the number of argument is four.

#include <iostream>
using namespace std;

void add_three(float, float *);

int main()
{
  float s,r;
  float a[3];
  add_three(a[3], &r); //use of undeclared identifier 'a'

  cout<< "The sum is " << s; //use of undeclared identifier 's'

  return 0;
}

void add_three(float a[3], float *s)
{
  float r = 0;

  for(int i=0; i<3; i++)
    {
      cin >> a[i];
      r = r + a[i]; //invalid operands to binary expression ('float *' and 'float')
    }
  *s = &r;

}

Errors:
assigning to 'float' from incompatible type 'float *'; remove &
  *s = &r;

I am stuck and can't understand what I am doing wrong (BTW, I am a complete novice).
Comment: `*s = &r` is nonsense. It should be `*s = r;` . And in `main`, besides the out-of-range improper use of `a[3]`, the variable `r` is what is being used to reap the sum. Therefore printing `s` is also useless (and in fact, in `main` the variable `s` itself is completely useless and should just be removed entirely).
Comment: The compiler is entirely right in this case: `remove &`.
Comment: as far as I understood it the prototype should like `void add_three(float,float,float,float&)` then you pass the first three by value and the fourth you pass as a reference (or pointer if you prefer) where the result will be placed. So first get the values from the user, then call the function and then present the result.
Comment: Deleted my answer because the other one is much more thorough, but its worth noting your exact error ( `use of undeclared identifier 'a'`) was because a[3] was off the end of the array.
Comment: Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer.
Answer: The first problem is that you attempt to pass a single float value to the function, which is declared to take a single float value.
Then you create an overload of that function, which takes a pointer to a float value. The function declaration
void add_three(float, float*);

is different from
void add_three(float*, float*);

You also make it worse by passing the fourth element from your three-element array.
Then there's the assignment
*s = &r;

It tries to assign the pointer to the variable r (the type of the expression &r is float*) to the floating-point value *s.
You probably want
*s = r;

Or better yet, use proper references to pass s by reference:
// First argument: Pass a pointer to the first element of the array
// Second argument: Pass a reference to the variable
void add_three(float* a, float& s);

Call as:
float a[3];
float s;
add_three(a, s);

As an alternative you could return the sum instead of passing references. This is actually the method I recommend:
// First argument: Pointer to the first element of your array
// Returns: The sum of all three elements
float add_three(float* a);

Call as:
float a[3];
float s = add_three(a);

Or considering that you don't actually use a in the main function, you could skip passing it as an argument. In fact, you don't need an array at all:
float add_three()
{
    float input, sum = 0;  // Initialize sum to zero

    for (unsigned i = 0; i < 3; ++i)
    {
        // Note: Really need some error checking and validation here
        std::cin >> input;
        sum += input;
    }

    return sum;
}

Simply call as:
float s = add_three();

Even if you must use arguments to "return" the value, you can do it without the array.


React error: warning maximum update depth exceeded

Question: I have added a screen from where admin can add products to store. Whenever I try to enter this page I get following warning and it keeps on repeating until my browser freezes or crashes:

Maximum update depth exceeded. This can happen when a component calls
setState inside useEffect, but useEffect either doesn't have a
dependency array, or one of the dependencies changes on every render.

Here is the code for my ProductEditScreen.js
import React, { useState, useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import ErrorMessage from "../../components/ErrorMessage/ErrorMessage";
import Loader from "../../components/Loader/Loader";
import { Link } from "react-router-dom";
import { listProductDetails } from "../../redux/actions/productActions";
import "./ProductEditScreen.scss";

const ProductEditScreen = ({ match, history }) => {
  const productID = match.params.id;
  const [name, setName] = useState("");
  const [price, setPrice] = useState(0);
  const [image, setImage] = useState("");
  const [brand, setBrand] = useState("");
  const [category, setCategory] = useState("");
  const [countInStock, setCountInStock] = useState(0);
  const [description, setDescription] = useState("");

  const dispatch = useDispatch();

  const productDetails = useSelector((state) => state.productDetails);
  const { loading, error, product } = productDetails;

  useEffect(() => {
    if (!product.name || product._id !== productID) {
      dispatch(listProductDetails(productID));
    } else {
      setName(product.name);
      setPrice(product.price);
      setImage(product.Image);
      setBrand(product.brand);
      setCategory(product.category);
      setCountInStock(product.setCountInStock);
      setDescription(product.description);
    }
  }, [dispatch, history, product, productID]);

  const submitHandler = (e) => {
    e.preventDefault();
  };

  return (
    <>

        {/* {loadingUpdate && <Loader />}
        {errorUpdate && <ErrorMessage>{errorUpdate}</ErrorMessage>} */}

EDIT PRODUCT

          {error ? (
            <ErrorMessage>{error}</ErrorMessage>
          ) : (
            <form onSubmit={submitHandler}>

                <input
                  className="userEdit-input"
                  type="name"
                  placeholder="name"
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                />
                <input
                  className="userEdit-input"
                  type="number"
                  placeholder="Price"
                  value={price}
                  onChange={(e) => setPrice(e.target.value)}
                />
                <input
                  className="userEdit-input"
                  type="text"
                  placeholder="Enter image url"
                  value={image}
                  onChange={(e) => setImage(e.target.value)}
                />
                <input
                  className="userEdit-input"
                  type="text"
                  placeholder="Brand Name"
                  value={brand}
                  onChange={(e) => setBrand(e.target.value)}
                />
                <input
                  className="userEdit-input"
                  type="text"
                  placeholder="Category"
                  value={category}
                  onChange={(e) => setCategory(e.target.value)}
                />
                <input
                  className="userEdit-input"
                  type="number"
                  placeholder="Count In Stock"
                  value={countInStock}
                  onChange={(e) => setCountInStock(e.target.value)}
                />
                <input
                  className="userEdit-input"
                  type="text"
                  placeholder="Description"
                  value={description}
                  onChange={(e) => setDescription(e.target.value)}
                />

                <button type="submit" value="submit">
                  UPDATE
                </button>
                <Link to="/admin/productlist">
                  <button>Go Back</button>
                </Link>

            </form>
          )}

    </>
  );
};

export default ProductEditScreen;

warning says useEffect either doesn't have a dependency array but I have passed all the dependencies. Also, I don't see any dependency changing every render.
Comment: The dependency array is only supposed to contain variables that should generate a re-render when they change. Make it `[]` first, then only add back dependencies you actually need.
Comment: try what chris suggests, i imagine the issue is going to be one of these `dispatch, history,`.. -> your deps array should probably just `[productID]`
Comment: Thanks, for the quick reply I removed all dependencies and console recommended me dependencies. I will be adding them in the answer.
Answer: As Chris G suggested above in comments I first ran useEffect with empty [] and then added what console recommended me.

useEffect(() => {
    if (!product.name || product._id !== productID) {
      dispatch(listProductDetails(productID));
    } else {
      setName(product.name);
      setPrice(product.price);
      setImage(product.Image);
      setBrand(product.brand);
      setCategory(product.category);
      setCountInStock(product.setCountInStock);
      setDescription(product.description);
    }
  }, [
    dispatch,
    productID,
    product.Image,
    product._id,
    product.brand,
    product.name,
    product.price,
    product.category,
    product.setCountInStock,
    product.description,
  ]);


Por que o Box Alignment não está funcionando?

Question: Eu gostaria de criar um espaço entre Register e Remember, mas não está funcionando.

  <link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">

Todo Authentication

        <input type="text" class="border w-2/5 py-2 px-2 focus:placeholder-black " placeholder="Username" />
        <input type="password" class="border  w-2/5 py-2 px-2 focus:placeholder-black " placeholder="Password" />

          Register

         <input type="checkbox">
Remember

        <button class="border w-2/5 p-4 text-lg font-bold bg-blue-200 border-black rounded">Log in</button>

Atualização
Resolvi o problema colocando uma width entre esses elementos.
Comment: Como assim espaço, que tipo de espaço, só uma pequena margem? Ou um de um lado e o outro do outro? Não ficou muito claro o que  vc realmente pretendo como resultado final
Comment: Eu atualizei o resultado com o FIX que eu queria
Answer: Eu lhe sugiro criar um novo arquivo para colocar estilos que você precisar e colocar de acordo com um nome/classe/id
Sem o arquivo você pode usar o style="propriedade:valor, para o que você quer, que é criar um espaço ficaria style="margin-right: 10px" ao colocar na tag  ou então style="margin-left: 10px" para a tag <input>
Aqui está dois exemplos para cada tag, (supondo que você irá estilizar a partir do html mesmo)

  <link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">

Todo Authentication

        <input type="text" class="border w-2/5 py-2 px-2 focus:placeholder-black " placeholder="Username" />
        <input type="password" class="border  w-2/5 py-2 px-2 focus:placeholder-black " placeholder="Password" />

          Register
          <input type="checkbox">Remember

        <button class="border w-2/5 p-4 text-lg font-bold bg-blue-200 border-black rounded">Log in</button>

  <link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">

Todo Authentication

        <input type="text" class="border w-2/5 py-2 px-2 focus:placeholder-black " placeholder="Username" />
        <input type="password" class="border  w-2/5 py-2 px-2 focus:placeholder-black " placeholder="Password" />

          Register
          <input type="checkbox" style="margin-left: 10px">Remember

        <button class="border w-2/5 p-4 text-lg font-bold bg-blue-200 border-black rounded">Log in</button>


Why does C use statement as for-loop's condition?

Question: Like the title says. If I recall correctly, statement shouldn't return any value, then how could C retrieve the value from a statement? (Yes I know compilers can do that, but that would need a little hack, and not beautiful.)
And the increment part of for loop is a expression, which is very confusing too, because you would never need the increment operation's return value.
All my knowledge of C grammar is from here.
In fact, I'm writing a DSL which tries to follow C's grammar, but it just feels so wrong when implementing the for-loop, especially I decide to make assignment a statement not a expression.
Comment: I'll admit I'm not exactly clear on what you're asking but the "increment part" of the for-loop can be used to make an assignment; the increment is an implicit assignment itself; no?
Comment: @ChiefTwoPencils in C, assignment is a expression, which can be used  in the "increment part".
Answer: In C for loop has two grammatical forms and neither of them uses statement as condition
for ( expression[opt] ; expression[opt] ; expression[opt] ) statement
for ( declaration expression[opt] ; expression[opt] ) statement

At your link someone apparently tried to use expression_statement as a replacement for expression followed by ;. That might work grammatically, but it does not reflect the semantics of this language construct. Semantically, the language does not see any "statements" there. The language sees and uses the expression.

And the increment part of for loop is a expression, which is very confusing too, because you would never need the increment operation's return value.

But that true for [almost] every expression statement in C language. The result of the full expression in expression statement is always discarded. Every time you say
printf("Hello World");

you discard the result of printf. Every time you do
a = b + c;

you discard the result of the entire expression.
Answer: You are misreading your reference material — the ANSI C Yacc Grammar at Lysator.  It says:
iteration_statement
    : WHILE '(' expression ')' statement
    | DO statement WHILE '(' expression ')' ';'
    | FOR '(' expression_statement expression_statement ')' statement
    | FOR '(' expression_statement expression_statement expression ')' statement
    ;

They are expression_statements, not statements.  And it makes sense to use expressions in the conditional part of the loop.
expression_statement
    : ';'
    | expression ';'
    ;

statement
    : labeled_statement
    | compound_statement
    | expression_statement
    | selection_statement
    | iteration_statement
    | jump_statement
    ;

Looking at it, that's a grammar for C90, not C99 or C11 — you can tell from the date as well as the content.  Be aware that C has evolved since that was written.  Not radically, but definitely changed.
Comment: If you're not misreading it, then you are misunderstanding it.  You can't use any old statement in the context of the `for` loop; you can only use an expression statement, not a labeled statement or a jump statement, etc.  And where a `statement` can be used, any of the alternatives for a `statement` (such as a jump statement) can be used, but that's simply not allowed by the grammar in the control part of a `for` loop.  You can only use expression statements; you cannot use the other types of statement.
Comment: Thanks, but no, I'm not misreading my reference, expression_statement is also a statement, just more specific. And statement don't return values, this is where it cause problems, think of that, you are building a AST node for a for-loop, you will need the conditional part's result to decide whether exit the loop or not, but all you got is a statement node, which will not have a return value in theory, then you either step into that statement node to get the expression, or make expression_statement return values, both are bad practice, I think.
Comment: Yes, I know that you can only use expressions there, that is not the problem. The problem is the logic behind the choice of expression_statement rather than expression ';'. But since AnT points out that my reference is not that accurate, I think the our discuss about this is pointless. Thanks for your answer, anyway.
Answer: interesting: however, this kind of statement:
FOR '(' expression_statement expression_statement ')' statement

does not compile.  here is an example:
#include <stdio.h>

int main()
{
    int a;
    //FOR '(' expression_statement expression_statement ')' statement
    for( a=0; a<10 ) printf( "a=%d\n", a );
    return 0;
}

which results in the compiler outputting:
  gcc -ggdb  -Wall -Wextra  -Wconversion -std=gnu11 -pedantic -Wmissing-prototypes  -c "untitled2.c"  -I.   (in directory: /home/rkwill/Documents/forum)
untitled2.c: In function 'main':
untitled2.c:7:20: error: expected ';' before ')' token
    for( a=0; a<10 ) printf( "a=%d\n", a );
                ^
Compilation failed.

Comment: Your initial quote is part of a Yacc grammar.  Since each `expression_statement` explicitly includes a semicolon, that quoted line characterizes a `for` loop such as `for (i = 0; i < 37; )` with no 'increment' in the third section — which is perfectly valid (if marginally unorthodox) C.  The statement after the loop allows for braces or other statements that form the loop body.
Comment: @JonathanLeffler,  Thanks for the clarification.  As an aside, and and all of the expressions in a `for()` statement are optional.  I just did not know about the 'implicit' in the grammer ';
Comment: And, as an FYI, the grammar in the C90 standard lists `for ( expression_opt ; expression_opt ; expression_opt ) statement` as the 'official' grammar (where I've used `_opt` to indicate an 'opt' subscript).  However, the grammar quoted in the question is equivalent to that because of the way it defines `expression`.  C99 and C11 list the notations shown by AnT in his answer.


How to use grid widget in Drupalgap?

Question: I cannot reproduce the grid widget. The page shows nothing except the title. Here is my code:
/**
 * Implements hook_menu()
 */
function test_grid_menu() {
  var items = {};
  items['test_grid'] = {
    title:'test grid',
    page_callback: 'test_grid_page',
  };
  return items;
}

function test_grid_page() {

var content = {};
content['my_grid'] = {
  theme: 'jqm_grid',
  columns: 2,
  items: [
    bl('Foo', 'foo'),
    bl('Bar', 'bar'),
    bl('Baz', 'baz'),
    bl('Chop', 'chop')
  ]
};
return content;
}

I also tried to put the theme('jqm_grid', ...) in the page_callback, but it does not work.
function test_grid_page() {

var content = {};
content['my_grid'] = {
  theme: 'jqm_grid',
  columns: 2,
  items: [
    bl('Foo', 'foo'),
    bl('Bar', 'bar'),
    bl('Baz', 'baz'),
    bl('Chop', 'chop')
  ]
};
return content;

var html = theme('jqm_grid', {
  columns: 2,
  items: [
    bl('Foo', 'foo'),
    bl('Bar', 'bar'),
    bl('Baz', 'baz'),
    bl('Chop', 'chop')
  ]
});
return html;

}

I place the jQuery Block code in the page_callback. The page display is fine as expect, but the linking is a problem.(cannot reach the localhost node) It seems this can only give good display but without the function. (in my following code, search and the linking have no function).
function test_grid2_page() {

var  html = '
<form>Search:';
     html += '<input type="search" name="search-1" id="search-1" value=""></form>
';
     html += '
';
     html += '

Foo

';
     html += '

Bar

';
     html += '

Baz

';
     html += '

Chop

';
     html += '

Computer

';
     html += '

Wine

';
     html += '
';
return html;
}

I have fixed the linking using l(...) and bl(...), but I would like my buttons fill all the grid. The name of the button also out of the range, so it just show partially. Here is the code and result:
var  html = '
<form>Search:';
     html += '<input type="search" name="search-1" id="search-1" value=""></form>
';
     html += '
';
     html += '

';
     html += bl('Foo', 'node/966', {attributes:{'data-icon':'action'}});
     html += '

';
     html += '

';
     html += bl('Bar', 'node/1028', {attributes:{'data-icon':'action'}});
     html += '

';
     html += '

';
     html += bl('Baz', 'node/1021', {attributes:{'data-icon':'action'}});
     html += '

';
     html += '

';
     html += bl('Chop', 'node/1027', {attributes:{'data-icon':'action'}});
     html += '

';
     html += '

';
     html += bl('Computer', 'node/1021', {attributes:{'data-icon':'action'}});
     html += '

';
     html += '

';
     html += bl('Wine', 'node/1025', {attributes:{'data-icon':'action'}});
     html += '

';
     html += '
';
return html;

Comment: @tyler I meant it seemed like it might be JS problem territory rather than Drupal-centric. DrupalGap questions are of course very welcome here
Comment: This is probably better suited for the GitHub for DrupalGap. At a glance this looks like a PHP question.
Comment: It's JS @Kevin but you might be right about it being better suited to the GitHub queue
Comment: Yeah that is what I meant - which is why I deleted my answer.
Comment: thanks you guys. After lots of experiments, I have found a way to do it by directly return the jQuery code in the page_callback.
Comment: FYI, drupal.stackexchange.com is a great place for DrupalGap related questions, in fact it's listed as one of the places to get support for DrupalGap. That being said, would you mind updating your question to include your solution, I'd like to see your workaround, and am curious why the code in your question isn't working, because it looks perfect. Perhaps download the latest `drupalgap.min.js` file...
Comment: thank you Tyler. I have put my solution and will try the latest drupalgap.min.js later today.
Comment: the `drupalgap.min.js` I use is 7.0.2 and after checking signalpoint. It seems to be the latest one.
Comment: I guess the theme "jqm_grid" is not supported. Where can I find the information of all the available theme types?
Answer: @Clive, thank you for confirming, and for your efforts. @artphys, try the latest dev snapshot, jqm_grid is definitely supported: https://raw.githubusercontent.com/signalpoint/DrupalGap/7.x-1.x/bin/drupalgap.min.js
Comment: I replaced `bin/drupalgap.js` and `bin/drupalgap.min.js` with the new ones, the code using jqm_grid still does not work. So I tried to replace all the directory of mobile-app with new Drupalgap-7.x-1.x and keep my own `app/setting.js` and modules, I cannot even display the original dashboard. It only shows the picture of Drupalgap in the centre and nothing eles. Did I miss somethings?
Comment: I replaced `bin/drupalgap.min.js` with the new one, and modified `index.html` to '
'. The grid widget from the document starts to work! Thank you.
Answer: Thanks to Tyler. I am giving more detail of the solution.
First download the new drupalgap.min.js from https://raw.githubusercontent.com/signalpoint/DrupalGap/7.x-1.x/bin/drupalgap.min.js
and place it in the bin directory.
Modified the index.html where originally
       to the new drupalgap.min.js.
Then the grid widget from the drupalgap document http://docs.drupalgap.org/7/Widgets/Grid_Widget  starts to work! Both Render Array and theme('jqm_grid', ...) can successfully do it. Just pick one. The code below is using render array.
/**
 * Implements hook_menu()
 */
function test_grid2_menu() {
  var items = {};
  items['test_grid2'] = {
    title:'test grid2',
    page_callback: 'test_grid2_page',
  };
  return items;
}

function test_grid2_page() {

var content = {};
content['my_grid'] = {
  theme: 'jqm_grid',
  columns: 2,
  items: [
    bl('Foo', 'foo'),
    bl('Bar', 'bar'),
    bl('Bar', 'bar'),
    bl('Baz', 'baz'),
    bl('Chop', 'chop')
  ]
};
return content;
}

How to use grid widget in Drupalgap?


how to use a graph to understand constraint optimization and Lagrange multipliers

Question:
let's say we have a circle on x-y plane and then we tilt the circle around 30 degree and point A is anchor.

we want to maximize the distance from the point $(x, y, z)$ to the origin $$f(x,y,z)=x^2+y^2+z^2$$ subject to the constraint that the point lie on the circle.
It is obvious that B is the point we want. But according to the optimisation theory,  $\nabla f(x,y,z)$ has to be orthogonal to the tangent plane of B in the circle, but that's impossibile, I know I must have something wrong, but where do I go wrong?
Comment: Do you mean to say that $B$ maximizes the distance to the origin?
Comment: @florence Yes, it is obvious for me that $B$  maximizes the distance to the origin? Is it correct?
Comment: Yes, but you wrote "minimize."
Comment: @florence sorry, I changed it back. And how come $\nabla f(x,y,z)$ has to be orthogonal to the tangent plane of B in the circle? I can't see a way of that
Comment: Are you sure about "the tangent plane of $B$" ? Isn't it true that the gradient is orthogonal to the circle ?
Answer: You're thinking in terms of, for example, optimizing a function of two variables on a curve in $\Bbb{R}^2$, or optimizing a function of three variables over a surface in $\Bbb{R}^3$. In these situations, you have a function $f$ which you want to optimize, and a function $g$ so that $g(\mathbf{x})=c$ defines your constraint. Then (roughly) at a local maximum or minimum, we have $\nabla f = \lambda \nabla g$, where $\lambda$ is a constant, i.e. $\nabla f$ is parallel to $\nabla g$, causing $\nabla f$ to be perpendicular to the curve.
However, this situation is different; we're looking to optimize a function of three variables over a curve in $\Bbb{R}^3$. Provided that $g$ is "nice" enough to work with for these purposes at $c$, any constraint $g(\mathbf{x}) = c$ would actually define a surface (intuitively: $g$ is a function of three variables, setting $g(\mathbf{x})=c$ removes one degree of freedom, leaving a region parametrized by two variables). So, in order to describe the curve in the OP, we wold need two constraints: $g_1(\mathbf{x}) = c_1$ and $g_2(\mathbf{x})=c_2$. In this situation, you find the local extrema by solving the following system of equations:
$$\nabla f = \lambda \nabla g_1+\mu \nabla g_2$$
Where $\lambda, \mu$ are constants. This equation does not impose any impossible constraints on the direction of $\nabla f$. Geometrically speaking, the curve is the intersection of two surfaces given by $g_1(\mathbf{x}) = c_1$ and $g_2(\mathbf{x})=c_2$ (one for each constraint), and at $B$, $\nabla f$ must merely be in the plane generated by $\nabla g_1 (B)$ and $\nabla g_2(B)$.
Comment: It's a one-dimensional curve that exists in three dimensions. Something two-dimensional would be like a surface, something three-dimensional would be like a region that encloses some volume. The important thing here, though, is that you'd need tow constraints to describe it; for a circle on the $x-y$ plane centered at the origin, for instant, you could have $x^2+y^2=1$ and $z=0$.
Comment: I still don't understand how to get  $g_1(\mathbf{x}) = c_1$ and $g_2(\mathbf{x})=c_2$, how these  $g_1(\mathbf{x})$ and $g_2(\mathbf{x})$ come from the $g(\mathbf{x})$? and
Comment: and let's say $g$ is $x^3+y^2+z$,a function of three variables, setting $g(\mathbf{x,y,z})=c$ , we have $x^3+y^2+z=c$ how come this region is parametrized by two variables rather than three variables?
Comment: $g_1$ and $g_2$ don't "come from" $g$. In order to describe a one-dimensional curve in $\Bbb{R}^3$ you need two constraints to begin with. And the reason that surface is parametrized by two variables is because you can choose $x$ and $y$, but then this automatically determines the value of $z$.
Comment: do you mean the circle is just one-dimensional curve? I think it is still three-dimensional curve?
Comment: Then in your example as $x^2+y^2=1$, and $z=0$, let we tilt the circle 30 degree on point A(-1,0,0), what is the $g_1$ and $g_2$?


Android MVVM: how can I update data in a Repository from another Repository, when same data is part of response from different server endpoints?

Question: I'm trying to move Android project to MVVM. Two different repositories get same data response, when calling different server endpoints. What is the right way to keep both up-to-date?
There are different server endpoints returning "UserData": "/get_user_data" and "/get_user_statistics". I need to update data in "UserRepository", when making request in "UserStatisticsRepository" (which returns UserData as well).
Should I inject both Repositories in a ViewModel and then set the "UserData" via ViewModel to "UserRepository"? It just feels to me not really right way to set data to a Repository from a ViewModel...
Let's say, I have:
data class UserData(
        @SerializedName("id") val id: Int,
        @SerializedName("name") val name: String
)

and
data class UserStatisticData(
        @SerializedName("id") val id: Int,
        @SerializedName("active_users_count") val activeUsersCount: Int,
        @SerializedName("users") val users: List<UserData>
)

and
class UserStatisticRepository(...) {
    ...
    suspend fun makeUserStatisticDataRequest(){
        withContext(Dispatchers.IO) {
            val networkResponse = myAppAPI?.getUserStatisticData(params)
            try {
                if (networkResponse!!.isSuccessful) {
                    _userStatisticData.value = networkResponse.body()?.userStatisticData
                    // TODO: Should I set UserData (networkResponse.body()?.userData) to UserRepository here???
                    // How can I access UserRepository?
                } else {
                    throw UserStatisticDataResponseError(Exception("Response body error..."))
                }
            } catch (e: Exception) {
                throw UserStatisticDataResponseError(Exception("Network error..."))
            }
        }

    }
    ...
}

Answer: I am not sure how your projwct is set up but If I was in this kind of situation I would :

Either have a single state that is mutated by both of the repository,  make it reactive. Both of the repostitory can take that state as argument when being constructed and they can also mutate the state.
A reactive database that is mutated by both the calls. i.e. whenever any new UserData entity is fetched, its written to databse. When we need UserData we listen it directly from Reactive Database like "Room"  instead of those API endpoints directly.

When to do what?
I would choose the first option if I did not have to persist the fetched data & I am cool with losing all the data once app is closed where as If I wanted the data from those endpoints to survive App restart the  I would go for the second options.
For the first option the code may look like this :
data class UserDataSource(val userDataList : List<UserData>)

class UserDataRepo(val subject :  PublishSubject<UserDataSource>){
 UserdataService.getUserData(userID).subscribe{
   // Do calculations to find the old list of user and edit or update the new user
   subject.onNext(UserDataSource(newUserList))
 }
}

class UserStatRepo(subject :  PublishSubject<UserDataSource>){
   UserdataService.getUserStat().subscribe{
   // Do calculations to find the old list of user and edit or update the new user
   subject.onNext(UserDataSource(newUserList))
 }}

In Ui subscribe to the userDataSource subject..
class UserDataViewModel{
   val userDataSource = PublishSubject.create<userDataSource>()
   val userDataRepository = UserDataRepo (userDataSource)
   val userDataRepository = UserStatRepo (userDataSource)
}

Comment: Thank you, this idea sounds good to me! Maybe the first option is exactly, what I need. Could you please give an example of this single state that is mutated?
Comment: you can make a RxJava publish subject of the list of UserData inside a class called "Datasource". And whenever you get a response from retrofit you can call datasource.userDataListSubject.onNext(listOf(userData) or List depending upon the Retrofit call you are making)
Comment: Check the answer I have tried to provide a skeleton of what could be implementation
Comment: You can accept the answer with green tick and upvote if it was helpful :)


List of template suggestion used for a node

Question: I'm building a module that return you an HTML styled node via ajax but I have a question.
I want to add a node suggestion only for this module. How?
So drupal have to check:
Exist [in active theme] ajaxnode.tpl? And ajaxnode--nodetype.tpl? If they don't exist choice the normal drupal suggestion template and render the node.
How can i do this correctly?
Comment: You could use the documentation from https://drupal.org/node/1089656 for template hinting in drupal.
Answer: I'd go and get the Theme developer module.  Simply get the element you want to theme and click on it - then you'll get a list of any template files and/or theme functions that were called in the processing of the element you clicked.

Firebug for Drupal themeing. See the screenshot and screencast. Note
  that this module injects markers into the DOM to do its magic. This
  may cause some themes to behave erratically and less capable browsers
  may make it worse (especially IE)/. Enable it when needed, and disable
  it afterwards.
Comment: I need to have the template files's list in the module not in interface..


Criar um vetor 2D a partir de um vetor 1D em Python

Question:
Possuo um vetor com os seguintes valores:
a = [10, 20, 30, 40, 50, 60, 70, 80]
Preciso criar vetor 2D com esses valores. Por exemplo, ele teria que ficar assim:
b = [[10, 20], [30, 40], [50, 60], [70, 80]]

Por gentileza, alguém poderia me ajudar com isso?
Desde já grato, aos que puderem.
Answer: Você pode fazer algo assim:
<code>b = [a[i:i+2] for i in range (0, len(a), 2]
</code>
Comment: Muito Obrigado. Funcionou corretamente.


Migrating a changed view

Question: I've created a view that I then turned into a 'Feature.'  I then successfully added this feature to a second site by copying the module files from the first site into the module folder of the second. Only the first-site has the D8 Features Module.
Then on the first site I changed the Title of the View and went through the process of detecting the change and regenerating the Feature:

Edit the view with the new title
Go to the Features Config page where the state of the feature shows "Changed"
Import the code back into the database (i.e. 'revert')
Re-re-edit the view title
Export the view as a feature

Now I want to import the changes of the first-site Feature into second-site Feature.

Uninstall the imported/copied module from second-site
Replace module folder of second site w/ new module from first-site
Re-install the module

I then receive a long error:

Unable to install My Image Gallery, core.base_field_override.node.my_image.promote, core.entity_form_display.node.my_image.default, core.entity_view_display.node.my_image.default, core.entity_view_display.node.my_image.teaser, field.field.node.my_image.body, field.field.node.my_image.field_my_image_field, field.storage.node.field_my_image_field, node.type.my_image already exist in active configuration.

Obviously there is a problem with either my procedure or my understanding of how to use the 'Feature' feature of Drupal 8, or I have a misconception of what it's supposed to do. Any help would be appreciated.
Answer: Procedurally, you should skip steps 3 and 4 in the first list.  For views, reverting will delete the view's config from the database, which is why you had to re-re-edit the title.  FYI, reverting works differently for other objects.

In some cases (e.g. views), the revert operation will delete the respective configuration in the database, so the system will instead use the default configuration that is defined in the feature module's code.

https://www.drupal.org/node/582680
I am not sure what caused the error you received.  It might be related to the steps you used.  I'd try again and see what happens. :)

Migrating a changed view


What is the difference between a Random Vector (Joint r.v.) and a Random Process?

Question: What is the difference between a Random Vector (Joint r.v.) and a Random Process?
Kindly, explain with a simple example (like toss of a coin, roll of a die, picking a card, etc.).
Note. As far as I understand, random process is a collection of equally spaced and indexed (generally, by time) random variables.
Comment: The duplicate link is broken. Maybe check this out: https://math.stackexchange.com/questions/569951/what-is-the-difference-between-a-random-vector-and-a-stochastic-process
Comment: The target of the duplicate link exists but is visible only to those with the reputation to see deleted posts.  It is, however, a duplicate of a (currently) undeleted post on Mathematics: see https://math.stackexchange.com/questions/2946642/give-an-example-of-a-random-vector.
Comment: Possible duplicate of [Give an example of a Random Vector](https://stats.stackexchange.com/questions/370690/give-an-example-of-a-random-vector)
Answer: A random vector is a special case of a random process, where a random vector has discrete indexing (natural numbers) while a random process can be sampled everywhere and return a random variable. Actually, it's more common to say stochastic process instead of random process.
Comment: You describe a narrow sense of random process, one in "continuous time" (or space).  Although it is mathematically correct--and insightful--to point out that a random vector is a special case, that doesn't seem to capture what is special about the study and application of random processes in statistics.  Statistics exploits *additional structure* (such as temporal sequence or spatial proximity) to formulate models of interdependency among the values of the stochastic process.
Comment: I would add to this that a random vector arises as a result of sampling a random process at a single value of the parameter (continuous; time or space) or index (when discretized). The natural numbering is immaterial, as a random.vector arises at any real (not necessarily positive integer) sample valu of the time or space parameter. Also, "stochastic process" is typically used for a one--dimensional random process (e.g., with time as index), while "random field" usually refers to a multi-dimensional one (e.g., spatial process)..


Modelagem para tabela de endereço compartilhado

Question: Possuo 3 entidades: Ponto, Solicitante e Serviço. Cada uma possui um endereço próprio, porém é possível que as 3 tenham o mesmo endereço.
Se uma entidade alterar o seu endereço, esta não deve alterar o endereço das outras entidades, mesmo quando possuírem o mesmo endereço.
Por exemplo: Um solicitante possui um serviço para o seu endereço atual. Quando o solicitante mudar de endereço, o serviço ainda estará relacionado com o endereço antigo.
Também é possível que vários Serviços possuam o mesmo endereço. E se o endereço de um serviço for alterado, essa alteração não deve afetar o endereço dos demais.
Dado o modelo de dados atual (abaixo), qual seria a melhor estratégia para evitar dados duplicados garantindo que nenhuma alteração afetará a outra?
Comment: O que é o ponto? Existe algum motivo para o serviço ter um endereço, não basta ter só o solicitante? Me parece que no fundo não os endereços não são os mesmos, eles podem ser coincidentemente os mesmos, o que não é suficiente para o aproveitamento. Como você determina como aproveitar o mesmo endereço?
Comment: @bigown O motivo para o 'Serviço' ter um endereço e o 'Solicitante' outro, é que o endereço de realização do serviço, nem sempre será igual ao endereço do solicitante.
Ponto é um local, um pedaço de rua, que é identificado pelo endereço. Este não tem relação com o serviço nem solicitante.
Comment: Sobre o aproveitamento, não decidi ainda como fazer. Só acho estranho manter vários registros iguais na tabela endereço. Não sei se altero a modelagem para outra, ou se crio algum algoritmo para controlar isso.
Answer: Eu não sei como vai reaproveitar o endereço já existente. Minha experiência é que isso funciona melhor no papel do que na prática, mas foi só um comentário complementar.
O que pode fazer é usar imutabilidade. Então se cadastra um endereço que terá um id de alguma forma pode ser usado por outras entidades. Até aí acho que é ok. Quando precisar mudar partindo de uma dessas entidades, a aplicação não gravará na linha existente onde os dados foram lidos, ela criará uma nova linha com os dados alterados.
Aí pense o que acontece se tiver que alterar o endereço e a alteração ter que ser aplicada para todos que apontam para este endereço. Como resolver isso? Não faço ideia. Vai deixar o usuário decidir? Não costuma funcionar, eles sempre erram nisto. E se tem que alterar em alguns pontos, mas não em outros? Confuso não é?
Aí é provável que comece proliferar novas linhas onde não deviam. Claro que pode ser que precise disso mesmo. Por outro lado se um endereço está vinculado a um serviço, então este nunca deveria ser alterado. Isso costuma ocorrer em nota fiscal por força de lei. Se por acaso o endereço estiver errado tem que usar uma retificação do endereço, não pode simplesmente ir lá e mudar o existente, ele é imutável.
Neste caso pode ser interessante:

O endereço é cadastrado pela primeira vez no solicitante;
o serviço é criado e usa o mesmo endereço (id) que está no cadastro do solicitante;
quando o solicitante muda o endereço, faz o esquema imutável que eu falei e cria um novo endereço para ele (muda o apontamento na chave estrangeira do solicitante), mas não afeta os outros que estão usando aquele endereço;
o serviço fica proibido de mudar o endereço. Isso significa que se houver mudança precisa ser uma retificação ou o serviço na verdade é outro (em algum caso isso pode ser relaxado).

Não entendi bem a função do ponto aí. Mas se não tem relação com os demais, não importa, só achei estranho estar na descrição da pergunta.
Leituras que podem ajudar (ou complicar :) ):

Banco de dados deve seguir o padrão OO?
Quando é interessante desnormalizar o banco de dados?

Coloquei no GitHub para referência futura.
Comment: Sim, @bigown você tem razão quanto ao reaproveitamento do endereço funcionar bem no papel e não na prática. Cheguei a essa conclusão. Essa solução de incluir um novo endereço a cada alteração, ficaria meio estranho, pois imagine que assim um endereço poderia ficar sem ligação com nenhuma entidade. Vou utilizar cada inclusão de endereço sendo um novo registro na tabela de endereços, não importando se já existe um igual. Pois o endereço é único para cada um de qualquer forma. Assim, se alterar, alterará somente o endereço correto.


How to find $\lim_{n \rightarrow +\infty } \left(\sqrt[m]{\prod_{i=1}^{m}(n+{a}_{i})}-n\right)$?

Question: I think it is zero;
$$\lim_{n \rightarrow +\infty } \left(\sqrt[m]{\prod_{i=1}^{m}(n+{a}_{i})}-n\right)$$
we can make that steps:
$$\lim_{n \rightarrow +\infty } \left(\sqrt[m]{{n}^{m}\prod_{i=1}^{m}\left(1+\frac{a_i}n\right)}-n\right)$$
and then:
$$\lim_{n \rightarrow +\infty } \left(n \cdot \sqrt[m]{\prod_{i=1}^{m}\left(1+\frac{{a}_{i}}{n}\right)}-n\right)$$
each bracket aspires to unit
so we have:
$$\lim_{n\rightarrow \infty} (n-n)$$
and..
$$\lim_{n\rightarrow \infty} (0) = 0$$
Comment: What are the $a_i$ in your limit?
Comment: Some of your LaTeX delimiters didn't match up. I fixed them but I hope the square roots and parentheses are in the places you wanted them to be ...
Comment: And what is $n?$
Comment: Not sure what the last two equalities are supposed to mean, but from $\lim_{n \rightarrow +\infty } \left(n \sqrt[m]{\prod_{i=1}^{m}\left(1+\frac{{a}_{i}}{n}\right)}-n\right)$ you can only get a $0 \cdot \infty$ type thing, after factoring $n$. But every such indeterminate form can be transformed into a more managable one, for instance by writing $n=\frac{1}{1/n}$.
Answer: $$\lim_{n \rightarrow +\infty } \left(\sqrt[m]{\prod_{i=1}^{m}(n+{a}_{i})}-n\right)=\lim_{n \rightarrow +\infty } \left(\sqrt[m]{{n}^{m}\prod_{i=1}^{m}\left(1+\frac{a_i}n\right)}-n\right)=\lim_{n \rightarrow +\infty } \left(n \cdot \sqrt[m]{\prod_{i=1}^{m}\left(1+\frac{{a}_{i}}{n}\right)}-n\right)=\lim_{n \rightarrow +\infty }\frac{ \sqrt[m]{\prod_{i=1}^{m}\left(1+\frac{{a}_{i}}{n}\right)}-1}{\frac{1}{n}}=$$$$=\lim_{n \rightarrow +\infty }\frac{ \sqrt[m]{\prod_{i=1}^{m}\left(1+\frac{{a}_{i}}{n}\right)}-1}{\prod_{i=1}^{m}\left(1+\frac{{a}_{i}}{n}\right)-1}\cdot\frac{\prod_{i=1}^{m}\left(1+\frac{{a}_{i}}{n}\right)-1}{\frac{1}{n}}=$$$$=\frac{1}{m}\cdot\lim_{n \rightarrow +\infty }\frac{1+\frac{a_1+a_2+...a_m}{n}+\frac{a_1a_2+a_2a_3+...+a_{m-1}a_m}{n^2}+...-1}{\frac{1}{n}}=\frac{a_1+a_2+...a_m}{m}.$$
We applied $$\lim_{x_n \rightarrow 0 }\frac{(1+x_n)^r-1}{x_n}=r.$$
Answer: $\newcommand{\+}{^{\dagger}}%
 \newcommand{\angles}[1]{\left\langle #1 \right\rangle}%
 \newcommand{\braces}[1]{\left\lbrace #1 \right\rbrace}%
 \newcommand{\bracks}[1]{\left\lbrack #1 \right\rbrack}%
 \newcommand{\ceil}[1]{\,\left\lceil #1 \right\rceil\,}%
 \newcommand{\dd}{{\rm d}}%
 \newcommand{\ds}[1]{\displaystyle{#1}}%
 \newcommand{\equalby}[1]{{#1 \atop {= \atop \vphantom{\huge A}}}}%
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}%
 \newcommand{\fermi}{\,{\rm f}}%
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}%
 \newcommand{\half}{{1 \over 2}}%
 \newcommand{\ic}{{\rm i}}%
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}%
 \newcommand{\isdiv}{\,\left.\right\vert\,}%
 \newcommand{\ket}[1]{\left\vert #1\right\rangle}%
 \newcommand{\ol}[1]{\overline{#1}}%
 \newcommand{\pars}[1]{\left( #1 \right)}%
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}%
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,#2\,}\,}%
 \newcommand{\sech}{\,{\rm sech}}%
 \newcommand{\sgn}{\,{\rm sgn}}%
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}%
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$
$\color{#ff0000}{\large\mbox{With}\ n \gg 1}$:
\begin{align}
\ln\pars{\root[m]{\prod_{i = 1}^{m}\pars{n + a_{i}}}}
&=
{1 \over m}\sum_{i = 1}^{m}\ln\pars{n + a_{i}}
=
{1 \over m}\sum_{i = 1}^{m}\bracks{\ln\pars{n} + \ln\pars{1 + {a_{i} \over n}}}
\sim
\ln\pars{n} + {1 \over m}\sum_{i = 1}^{m}{a_{i} \over n}
\\[3mm]&\mbox{With}\ \ol{a} \equiv {1 \over m}\sum_{i = 1}^{m}a_{i}\ \mbox{we'll get}
\\
\root[m]{\prod_{i = 1}^{m}\pars{n + a_{i}}} - n
&\sim \exp\pars{\ln\pars{n} + {\ol{a} \over n}} - n = n\pars{\expo{\ol{a}/n} - 1}
\sim n\bracks{\pars{1 + {\ol{a} \over n}} - 1} = \ol{a}
\end{align}
$$\color{#0000ff}{\large%
\lim_{n \to \infty}\bracks{\root[m]{\prod_{i = 1}^{m}\pars{n + a_{i}}} - n}}
=
\ol{a} = \color{#0000ff}{\large{1 \over m}\sum_{i = 1}^{m}a_{i}}
$$
Answer: The hard part is
showing that
$ P_n
=\sqrt[m]{\prod_{i=1}^{m}\left(1+\frac{{a}_{i}}{n}\right)}
\to 1$
as $n \to \infty$.
If $n > km\max(|a_i|)$,
$1+\frac{{a}_{i}}{n}
< 1+\frac1{km}
$
so $P_n
<\sqrt[m]{\prod_{i=1}^{m}\left(1+\frac1{km}\right)}
< 1+\frac1{km}
$.
By choosing $k$ large enough,
$P_n$ can be made as close to $1$
as wanted,
showing that
$\lim_{n \to \infty} P_n = 1$.


Is there a way to select a component's prop?

Question: I'll explain better with an example:
<template>
    <Comp prop="ex" @click.native="log" />
</template>

Having this component in my app is there a way to get the prop value from the script with something like this? (Expecting "ex" to log):

And if there is a way, does it change when having multiple instances of the same component?
Comment: Since you're already passing in the prop from the consuming component (the parent), you don't need to attempt to access the prop from the child: the prop value is already present in the parent.
Comment: I see the following solutions: Either you store all those `prop` values in a variable and loop them in the template. Then, you have access to the value as variable. Or you define separate variables for all props. Or you just duplicate the value ``. Or you pass the value to the child and then emit it back to the parent on an event (you cannot use native events for that though).
Comment: How about printing the same variable as passed to the component (i.e. `console.log(this.ex)`)?
Comment: @ssc-hrep3 It's not a variable but 'ex' string
Comment: @ssc-hrep3 because I have different components with different values of the same prop, and I need the value of the components that I click on
Answer: In this example prop prop is hard-coded to be ex string. This value is available in Comp child but not in the parent. In order to access it in the parent, it should available in parent's state:
data() {
  return {
    compPropValue: 'ex'
  }
},
methods: {
    log(value) {
        console.log(value)
    }
}

And used like:
<Comp :prop="compPropValue" @click.native="log(compPropValue)" />

Comment: I can see that working, the problem is that I have different components with different values of the same prop, and I need the value of the components that I click on.
Comment: Consider updating the question with the actual case you have. If these components are siblings then they should be output with v-for from an array, etc. Any way, prop data should be handled in script part of the parent, not template. And you can always duplicate the code and write what the comment suggests, https://stackoverflow.com/questions/70723828/is-there-a-way-to-select-a-components-prop/70723980#comment125028123_70723828 , although it doesn't look good
Comment: Thank you, I'm still new to vue and I don't know what are the best practices.
Answer: It just occurred to me that I can simply pass the value that I need as a parameter of the function:
<template>
    <Comp prop="ex" @click.native="log("ex") />
</template>

If someone knows how to actually do what I wanted it would still be helpful though!


Read only List view and covariance

Question: I wanted to make a read-only indexable "view" of a list, with the slight twist that the read only view should enumerate to an interface of the list type.
interface IIndexable<out T> : IEnumerable<T>
{
   T this[int i] { get; }
   int Count { get; }
}

The usage scenario would look something like this.
List<Dog> dogs = new List<Dog>[]{ dog1, dog2 }; // Dog implements IAnimal

IIndexable<IAnimal> animals = dogs.AsIIndexable<Dog, IAnimal>();
IAnimal first = animals[0];

I thought this would be possible given covariance and type constraints, but maybe I'm mistaken here.
My first attempt looks like this, which doesn't work because of the type of the enumerator.
internal class ListIndexable<TC, T> : IIndexable<T> where TC : T
{
   private List<TC> list;
   public ListIndexable(List<TC> list) { this.list = list; }

   public T this[int i] { get { return list[i]; } }

   public IEnumerator<T> GetEnumerator()
   {
      return list.GetEnumerator(); // Computer says no.
   }
}

Why can't I return an IEnumerator<TC> as an IEnumerator<T>? The type is covariant and I have constrained it with TC : T. Would it really be unsafe to return an IEnumerator<TC>, or is it simply a weakness here that the compiler's reasoning ignores the type constraint?
I could solve it by using a custom enumerator that wraps the IEnumerator<TC> and returns its items as T's which is of course perfectly legal, but I'm just curious why the above solution can't work.
internal class ListIndexable<TC, T> : IIndexable<T> where TC : T
{
   private List<TC> list;
   public ListIndexable(List<TC> list) { this.list = list; }

   public T this[int i] { get { return list[i]; } }

   public IEnumerator<T> GetEnumerator()
   {
      return new Enumerator(list.GetEnumerator());
   }

   class Enumerator : IEnumerator<T>
   {
      private IEnumerator<TC> inner;
      internal Enumerator(IEnumerator<TC> inner) { this.inner = inner; }

      public bool MoveNext()
      {
         return inner.MoveNext();
      }

      public T Current
      {
         get { return inner.Current; }
      }

      // ...
   }
}

Comment: I don't know if the real question was lost in the noise of the contrived example: the question is about type constraints i.e. "Why can't I return...", it's not about solving this particular concrete problem.
Comment: Why does `ListIndexable` have two type parameters? An `IIndexable` is an `IIndexable` due to covariance.
Comment: Why not use ReadOnlyCollection? Why are you creating your own class?
Comment: @Lee that IS a good question
Answer: Your original code does not work because of value types. You cannot do the following:
IEnumerable<int> ints = new[] { 1, 2 };
IEnumerable<object> os = ints;

so the compiler won't accept your definition since it can't guarantee that IEnumerable<TC> is compatible with IEnumerable<T> in general. If you add class constraints to T and TC it compiles:
internal class ListIndexable<TC, T> : IIndexable<T> where TC : class, T where T : class
{
}

However, you can define ListIndexable with only one type parameter instead of two. If you change your definition to:
internal class ListIndexable<T> : IIndexable<T>
{
   private List<T> list;
   public ListIndexable(List<T> list) { this.list = list; }

   public T this[int i] { get { return list[i]; } }

   public IEnumerator<T> GetEnumerator()
   {
      return list.GetEnumerator();
   }
}

then you can do:
IIndexable<IAnimal> animals = dogs.AsIIndexable();

where AsIndexable can be defined simply as:
public static ListIndexable<T> AsIndexable<T>(this List<T> list)
{
    return new ListIndexable<T>(list);
}

Comment: That solves my problem, but the problem itself was just there to illustrate a question I had about type constraints and covariance. This solution just shows my example to be stupid/contrived but it still holds as an example of type constraints + covariance I think
(I *will* use this solution in my code, thank you, an upvote for you even though it dosn't answer the question) :)
Comment: @AndersForsgren - I would guess it's because of value types - you can't do `IEnumerable ints = new[] { 1, 2 }; IEnumerable os = ints;`. So in your case the compiler can't guarentee that `IEnumerator` is compatible with `IEnumerator` in general.
Comment: @AndersForsgren - You can get it to compiler if you restrict, `T` and `TC` to be classes, see update.
Answer: If all you need is to create a read-only collection, you can use ReadOnlyCollection to wrap your list, eg:
var dogs = new List<Dog> {new Dog{Name="A"}, new Dog{Name="B"}, new Dog{Name="C"}};
var ro=new ReadOnlyCollection<Dog>(dogs);

IEnumerable<IAnimal> a = ro;

Comment: That works, and @Lee 's answer (That two type parameters are just not necessary) of course also solves the problem. But the question wasn't about solving a problem, the question was about how the compiler combines (or doesn't combine) generic type constraints with covariance.
Comment: That is not clear from the actual question. Perhaps you should edit it?
Comment: In this concrete problem I don't only need a read only collection, I need an indexable datastructure of generic type `IAnimal`. So something that is `IList` for example. But `ReadOnlyCollection` implements only `IList`, not `IList`.

Read only List view and covariance