Bootstrapping estimates of out-of-sample error

Question: I know how to use bootstrap re-sampling to find confidence intervals for in-sample error or R2:
# Bootstrap 95% CI for R-Squared
library(boot)
# function to obtain R-Squared from the data
rsq <- function(formula, data, indices) {
  d <- data[indices,] # allows boot to select sample
  fit <- lm(formula, data=d)
  return(summary(fit)$r.square)
}
# bootstrapping with 1000 replications
results <- boot(data=mtcars, statistic=rsq,
     R=1000, formula=mpg~wt+disp)

# view results
results
plot(results)

# get 95% confidence interval
boot.ci(results, type="bca")

But what if I want to estimate out-of-sample error (somewhat akin to cross-validation)? Could I fit a model to each boostrap sample, and then use that model to predict for each other bootstrap sample, and then average the RMSE of those predictions?
Comment: This form of bootstrapping isn't guaranteed to work. If the true predictive ability of the model is zero, then you don't get asymptotic normality of the quantity being bootstrapped, and the bootstrap confidence intervals above are not valid confidence intervals. With close to zero predictive ability, in finite sample sizes you still get badly-miscalibrated intervals.
Comment: This sounds somewhat akin to an older technique called CV5. You divide the sample into 5 parts. You fit on 1-4, and then use the 5th as a holdout. You then combined the error terms.  The choice of 5 was arbitary; this was often used where "split half" would have resulted in the model being fit on too few observations.   The bootstrapping will just allow you to do more variations than CV5, but then computers are more powerful now as well.
Comment: @zbicylist: so is the bootstrap traditionally used to estimate "in-sample" statistics, while cross-validation is traditionally used to estimate "out-of-sample" statistics?
Comment: Yes. I misread this "model to each boostrap sample, and then use that model to predict for each other bootstrap sample" as "model each bootstrap sample, and then use that model to predict the non-bootstrapped observations".  I'd do it the second way, so there's no contamination between the observations you model and the ones you predict.
Comment: Lookup "leave one out bootstrap" in EOSL: https://web.stanford.edu/~hastie/ElemStatLearn/
Answer: This calls for the standard Efron-Gong "optimism" bootstrap.  In R you can do this:
require(rms)
# Allow age to interact with sex and age and BP to have nonlinear effects
# using restricted cubic splines (5 and 4 knots)
f <- ols(y ~ rcs(age,5)*sex + rcs(blood.pressure,4), x=TRUE, y=TRUE)
validate(f, B=300)

This will give you the bootstrap overfitting-corrected estimate of $R^2$, MSE, and other indexes.  To get a bootstrap overfitting-corrected calibration curve (estimate of relationship between $\hat{Y}$ and $Y$), run plot(calibrate(f, B=300)).
This type of bootstrap estimates the likely future performance of the final model on new subjects from the same "stream" of subjects.  Some observations are duplicated, triplicated, etc., and "training" and "test" datasets overlap during the bootstrap.  The bootstrap provides a highly competitive estimate of future performance, along the lines of 100 repeats of 10-fold cross-validation.
Comment: Dr. Harrell, Would you suggest this method only for "smaller" sample sizes where there is not the luxury of being able to sample out a test set? My process for what Zach is asking is to sample out the test set from the beginning and use the training set for model selection, then fit the full model on the training set. In order to calculate a confidence interval around the out-of-sample performance, I will use an ordinary nonparametric bootstrap on the test set and apply the final model to every bootstrap sample - thus creating a performance index distribution.
Comment: No, I would use it for all sample sizes.  Single training/test splits are often unreliable unless $n > 20000$.
Comment: @Frank Harrell Efron and Gong described optimism bootstrap for classification problem and 0-1 loss. Though it seems straightforward for regression and quadratic loss, somehow I could not find it in the literature. Can you suggest a reference? Thank you.
Comment: See http://www.citeulike.org/user/harrelfe/article/13264256 and http://www.citeulike.org/user/harrelfe/article/13264735
Answer: The short answer, if I understand the questions, is "no".  Out of sample error is out of your sample and no bootstrapping or other analytical effort with your sample can calculate it.
In answer to your comment on whether the bootstrap can be used in checking a model with data  outside a training set:  two possible interpretations.
It would be fine, and absolutely standard, to fit a model on your training set with traditional methods and then use bootstrapping on the training set to check for things like distribution of your estimators, etc.  Then use your final model from that training set to test against the test set.
It would be possible to do a bootstrap-like procedure that involves a loop around:

selecting a subset of the whole sample as your training set
fit a model to that training set of the data
compare that model to the testing set of the remaining data and generate some kind of test statistic that says how well the model from the training set goes against the test set.

And then considering the results of doing that many times.  Certainly, it would give you some insight into the robustness of your train/test process.  It would reassure you that the particular model you got was not just due to the chance of what ended up in the test set in your one split.
However, it's difficult to say exactly why but there seems to me to be a philosophical clash between the idea of a testing/training division and the bootstrap.  Perhaps if I didn't think of it as a bootstrap, but just a robustness test of the train/test process it would be ok...
Comment: I was wondering if there was a "bootstrap" equivalent to cross-validation, where each observation may be in the training set more than once, but error is still aggregated out-of-sample.
Comment: I must be confused by the terminology, sorry.  When you say error is aggregated out-of-sample do you mean of the whole sample, including those points which are not in the training set?  I'd think of that as whole-of-sample, as you still don't have any points from outside your sample (be definition...).
Comment: sorry-- by out-of-sample, I meant "out of the sample selected for each boostrap replicate."  Sort of like what "out of bag" means for random forests.
Answer: Bootstrap is neither in-sample or out-of-sample test.
Consider the bootstrap logic:
1. a statistic is computed in the original sample;
2. a resample is constructed by sampling from the sample with replacement (this sample is considered to be a possible sample from the same population)
3. the same statistic a computed
4. step 2 and 3 are repeated and the distribution of the obtained statistics is then used to construct a confidence interval
Now translate this to the notion of out-of-sample testing, where you estimate a prediction model based on the original sample and then test out-of-sample. The out-of-sample sample should be any sample other than the original sample drawn from the same population.
Resampling with replacement provides you with such a sample, or indeed many such samples should you so wish. Now you can use the original model estimates from your original prediction model to predict outcomes in the new resample(s).
You can now compute a model-fit statistic to see if these predicted outcomes predict a similar share of the variation in the original sample and all of the resamples. Are all results comparatively similar, then overfitting is no issue. Are the results of resamples (significantly) worse than the model fit in the original sample, then you've got evidence of overfitting.
When comparing different training models, you can select the model with the best (average) modelfit in the resamples. More advanced strategies involve the variance of the modelfit, but add little in my opinion.
Best wishes


Trying to solve a two-point boundary value problem on MATLAB

Question: I have the following ODE
$$ u'' = -(1 + e^u), u(0)=0, u(1)=1$$
with boundary conditions and $t \in (0,1)$. I want to solve this ODE using the shooting method. First,we convert this to a system of equations. Let $y_1=u, y_2=u'$ and so
$$ \begin{bmatrix} y_1' \\ y_2' \end{bmatrix} = \begin{bmatrix} y_2 \\ -(1+e^{y_1}) \end{bmatrix}, \; \; \; \; \begin{bmatrix} y_1(0) \\ y_2(0) \end{bmatrix} = \begin{bmatrix} 0 \\ u'(0) \end{bmatrix}$$
Im trying to understand how the shooting method works and hopefully code it in matlab. So,I have to make a guess for $u'(0)$ and then use a ODE solve to get $u(1)=1$. Is this how we procced with this method?
Comment: As you said, make a guess for $u'(0)$. Then, compute the numerical solution $\vec{y_1}$ and see how far is $y_1(N)$ from $1$. Where $y_1(N)$ I mean numerical approximation of $u(1)$ (N is the number of points)
Answer: As you did, you first write the system as
$\begin{bmatrix} y_1' \\ y_2' \end{bmatrix} = \begin{bmatrix} y_2 \\ -(1+e^{y_1}) \end{bmatrix}, \; \; \; \; \begin{bmatrix} y_1(0) \\ y_2(0) \end{bmatrix} = \begin{bmatrix} 0 \\ u'(0) \end{bmatrix}$
in order to use a standard numerical method for ODEs.
So, the goal is to give the right value to $u'(0)$ in order to have $u(1)=1$. In your system, you have to guess the value of $y_2(0)$.
Of course you could do it by hand, but you can actually write a bisection method in order to find the correct value for the first derivative. The function you have to set to zero is, actually, $F=y_1(N)-1$.
So, assume to use a numerical method for solving your ODE, say explicit Euler (EE) (for sake of simplicity):

Consider two initial data $y_0= [0,a]^T$, $y_0=[0,b]^T$
Solve the ODE with (EE) those different initial values. Then you compute, for both the numerical solutions you get $f_a=y_1(N)-1$ and $f_b=y_1(N)-1$.
Compute the mean of $a,b$, call it $x_m$, and set another initial data $y_0=[0,x_m]^T$, and solve the ODE with (EE) and the last initial data and define $f_m=y_1(N)-1$.
Apply a standard bisection method: if $f_m \cdot f_a <0$, then $b=x_m$ and $f_b=f_m$, otherwise $a=x_m,f_a=f_m$
Repet the above procedure until the distance between $a$ and $b$ is $|b-a| \leq
\epsilon$, where $\epsilon$ is a chosen tolerance

The following (runable) MatLab code computes the right value for $y_2(0)$, which is approximately $2.4592$.
<code>fun=@(t,y) [y(2);-1-exp(y(1))];
m=200; %time steps
tstar=1;
k=tstar/m;
t = linspace(0,tstar,m+1);
y=zeros(2,m+1);
a=-5;
b=5; % extreme initial points for bisection
iter=0;
maxit=100;
tol=1e-6; %tolerance

while (abs(b-a)>tol) && (iter<maxit)

y(:,1)=[0,a]; %a initial guess iniziale for y2

for n = 1:m
    y(:,n+1) = y(:,n)+k*fun(t(n),y(:,n)); %EE
end
fa=y(1,end)-1; %I have to set to zero F=y(1) - 1. (Want y(1)=1)

y(:,1)=[0,b];

for n = 1:m
    y(:,n+1) = y(:,n)+k*fun(t(n),y(:,n)); %EE
end
fb=y(1,end)-1;

iter=iter+1;
xm=(a+b)/2;
y(:,1)=[0,xm];

for n = 1:m
    y(:,n+1) = y(:,n)+k*fun(t(n),y(:,n)); %EE
end

fm=y(1,end)-1;

if fa*fm<=0
    b=xm;
    fb=fm;
else
    a=xm;
    fa=fm;
end

end

disp('The correct value is')
disp(xm)

%%%PLOT THE NUM SOLUTION%%

y=zeros(2,m+1);
y(:,1)=[0,2.4592];
for n = 1:m
     y(:,n+1) = y(:,n)+k*fun(t(n),y(:,n)); %EE
end
plot(t,y(1,:),'-*')
</code>
The correct numerical solution is the following
Comment: @ILoveMath You are using whatever ODE IVP solver you want in order to find $u'(0)$ in the first place. So when you are finished you can just retain the solution function instead of discarding it. Also this is not a programming related SE.
Comment: Another option is to use the secant method which is likely a bit faster.
Comment: Of course, I also know a Newton's method for this type of problem, which is also faster, but I think bisection is a good way to "visualize" the problem
Comment: Once we have $u'(0)$, then we can just use, say Euler's method to find the solution, correct?
Comment: Well, in my specific code I used Euler's method because I didn't want to write much code, but yes, in this simple case you can use Euler with $y_2(0)=2.4592$, and check that actually your numerical solution is one at the boundary $t=1$
Comment: how do you do plots in matlab?
Comment: I do plot(t,xm) but it displays blank
Comment: Follow @Ian advice. Anyway, I edited my answer in order to do a plot of the solution
Comment: @ILoveMath of course... $x_m$ is just a number, while $t$ is a vector.
Comment: if we want to use finite difference, how would we discretize the nonlinear term $e^u$?
Comment: @ILoveMath You don't have to. Look at your scheme more carefully; for an ODE IVP solver it does not (structurally) matter whether $f(t,u)$ is linear or nonlinear in a first order system $u'=f(t,u)$.
Comment: https://math.stackexchange.com/questions/3195378/using-finite-differences-to-solve-bvp I asked this question as a separate question instead
Comment: @ILoveMath The kind of discretization that you're describing in that thread is not needed in the IVP setting, which is how the shooting method works. You would only need something like that if you wanted to use a more direct BVP method.


Simplifying a sum of products related to Vandermonde determinant

Question: How to show this equality?
$$
1=(-1)^n\sum_{k=0}^n\frac{x_k^n}{\prod_{\substack{l=0 \\ l \neq k}}^n(x_l-x_k)}
$$
This is part of a proof to show the value of the determinant of the Vandermonde matrix equals some give product.
Comment: What have you tried, what exactly is the setup of the problem you are trying to solve?
Comment: i've tried to proof this with induction but it ends in a mess an i see no way to simplify it.
Answer: Let
\begin{align}
f(x)=\dfrac{(1-x_1x)(1-x_2x)\cdots(1-x_nx)}{(1-\dfrac{x_1}{x_0})(1-\dfrac{x_2}{x_0})\cdots(1-\dfrac{x_n}{x_0})}+\dfrac{(1-x_0x)(1-x_2x)\cdots(1-x_nx)}{(1-\dfrac{x_0}{x_1})(1-\dfrac{x_2}{x_1})\cdots(1-\dfrac{x_n}{x_1})}+\cdots+\dfrac{(1-x_0x)(1-x_1x)\cdots(1-x_{n-1}x)}{(1-\dfrac{x_0}{x_n})(1-\dfrac{x_1}{x_n})\cdots(1-\dfrac{x_{n-1}}{x_n})}
\\
\end{align}
$\hspace{17mm}=\sum \limits_{k=0}^{n}\prod \limits_{l=0,l\neq k}^{n}\dfrac{1-x_lx}{1-\dfrac{x_l}{x_k}}$
Now $\operatorname{deg}(f)=n$, and for each $0\leqslant k\leqslant n,\space f(\dfrac{1}{x_k})=1$. Since $f(x)-1$ is a polynomial of $n$, it only has $n$ roots. So $f(x)-1\equiv 0$ or $f(x)\equiv 1$. Take $x=0$, we have
$$f(0)=1=\sum \limits_{k=0}^{n}\prod \limits_{l=0,l\neq k}^{n}\dfrac{1}{1-\dfrac{x_l}{x_k}}=\sum \limits_{k=0}^{n}\prod \limits_{l=0,l\neq k}^{n}\dfrac{x_k^n}{x_k-x_l}=(-1)^n\sum \limits_{k=0}^{n}x_k^n\prod \limits_{l=0,l\neq k}^{n}\dfrac{1}{x_l-x_k}$$
Comment: but sorry i don't get it. why is f(1/x_k)=1 ?
Comment: For example, $x=1/x_0$. The 1st term in $f(x)$ is $1$ because it has no factor of $1-x_0\dfrac{1}{x_0}$ and nominator equals denominator. The 2nd term is $0$ because it has factor of $1-x_0\dfrac{1}{x_0}=0$. The rest are all $0$ because it has factor of $1-x_0\dfrac{1}{x_0}=0$. For $x=1/x_k$, The kth term in $f(x)$ is $1$ because it has no factor of $1-x_k\dfrac{1}{x_k}=0$ and nominator equals denominator, and all others are $0$ because it has factor of $1-x_k\dfrac{1}{x_k}=0$.
Answer: Suppose we seek to verify that
$$1 = (-1)^n \sum_{k=0}^n
\frac{x_k^n}{\prod_{l=0\atop l\ne k}^n (x_l - x_k)}$$
with the $x_l$ distinct.
This is the same as
$$1 = \sum_{k=0}^n
\frac{x_k^n}{\prod_{l=0\atop l\ne k}^n (x_k - x_l)}.$$
Introduce $$f(z) = \frac{z^n}{\prod_{l=0}^n (z-x_l)}$$
which yields for the sum
$$\sum_{k=0}^n \mathrm{Res}_{z=x_k} f(z).$$
We  evaluate this using  the negative  of the  residue at  infinity as
these residues sum to zero. We obtain
$$\mathrm{Res}_{z=\infty} f(z)
= - \mathrm{Res}_{z=0} \frac{1}{z^2} f(1/z)
\\ = - \mathrm{Res}_{z=0} \frac{1}{z^2} \frac{1}{z^n}
\prod_{l=0}^n \frac{1}{1/z-x_l}
= - \mathrm{Res}_{z=0} \frac{1}{z^{n+2}}
\prod_{l=0}^n \frac{z}{1-x_l z}
\\ = - \mathrm{Res}_{z=0} \frac{1}{z}
\prod_{l=0}^n \frac{1}{1-x_l z}.$$
This is the constant term i.e.
$$- [z^0] \prod_{l=0}^n \frac{1}{1-x_l z} = -1.$$
The negative of this is $$1$$
as claimed.


Faithful representations and small tensor powers

Question: Let $ G $ be a finite group. Let $ (\pi,V) $ be a faithful representation of $ G $. Then every irrep of $ G $ is contained in some tensor power of $ V $. See
https://mathoverflow.net/questions/18194/faithful-representations-and-tensor-powers
In particular this answer
https://mathoverflow.net/a/192103/387190
shows that every irrep shows up in some tensor power less than or equal to the size of $ G $.
I am interested in a tighter bound. In particular, replacing the size of $ G $ by just the number of conjugacy classes of $ G $.
That is:
Let $ G $ be a finite group with $ k $ conjugacy classes. Let $ (\pi,V) $ be a faithful representation of $ G $. Does every irrep of $ G $ appear as a subrepresentation of
$$
\bigoplus_{j=1}^k V^{\otimes j}
$$
In other words, does every irrep of $ G $ appear in some small tensor power $ V^{\otimes j} $ for $ j \leq k $.
Answer: Yes, in fact we can write down an even better bound than this. If $\chi$ is a faithful character and $\psi$ is an irreducible character, then for $n \ge 1$ the sequence $\langle \chi^n, \psi \rangle$ satisfies a linear recurrence relation of order the number $d$ of distinct nonzero values that the character $\chi$ takes (which satisfies $d \le c(G)$, the number of conjugacy classes, but can be strictly less than it). (We need to take $n \ge 1$ so we can ignore the zero values.) Hence if it is zero for $n = 1, \dots d$ then it vanishes identically (since we can compute the rest of the terms using the linear recurrence). So any of the other arguments which show that this sequence is not identically zero in fact show that $\langle \chi^n, \psi \rangle \neq 0$ for some $\boxed{ 1 \le n \le d }$.
This argument can be extended slightly to give a proof, which is also given in the linked MO thread. We just consider the generating function
$$\sum_{n \ge 0} \langle \chi^n, \psi \rangle t^n = \sum_{n \ge 0} \frac{1}{|G|} \sum_{g \in G} \chi^n(g^{-1}) \psi(g) t^n = \frac{1}{|G|} \sum_{g \in G} \frac{\psi(g)}{1 - \chi(g^{-1}) t}.$$
Because $\chi$ is faithful, $g = e$ is the only element satisfying $\chi(g) = \chi(e)$, so the corresponding term $\frac{\psi(e)}{1 - \chi(e) t}$ is not canceled out by any other term in the above sum (it is the dominant singularity of the generating function), so the above generating function is nonzero and hence has some nonzero coefficient. Alternatively we can use a Vandermonde matrix, which is also alluded to in the linked MO thread.
As a simple application of this stronger bound, if we take $\chi$ to be the character of the regular representation then $d = 1$ which gives that every irreducible appears in the regular representation. Of course we knew this already but it's nice to see that this result is strong enough to give it.
As a more interesting application, let $V$ be the $n$-dimensional permutation representation of $S_n$. The character of this representation is the number of fixed points of a permutation, which takes exactly $d = n-1$ distinct nonzero values, namely $1, 2, \dots n-2, n$ (so excluding $n-1$). We conclude that every irreducible of $S_n$ appears in $V^{\otimes k}$ for some $1 \le k \le n - 1$, which is much better than either the bound $|S_n| = n!$ or the bound $|c(S_n)| = p(n)$. We ought to have a similar bound for induced representations but I don't know what that bound should be exactly.


Switching back to English from Chinese adds line break

Question: I implemented Localisation in my app but I am facing complication in UIButton. When I switch back to English from Chinese it looks something like this:

I added width and height to that particular button but it don't seem to be working.
Answer: You have to give button Width By Multiplier 1


Find the minimum of an expensive-to-sample noisy paraboloid

Question: I have a function on the unit square that's expensive to evaluate,
and want to estimate where it reaches its minimum in at most $N$ evaluations, $N$ ~ 10 say.
Assuming a model of the form paraboloid + noise,
$ \qquad \text{f}( x; x_{min}, a, c, \sigma )
\approx a (x - x_{min})^2 + c + \mathcal{N}( 0, \sigma^2 ) $
what's an algorithm to generate points $x_0 \dots x_{N-1}$ to sample f() at,
for a best estimate of $x_{min}$ ?
(My real problem is 2d, but it may be helpful to do 1d first,
so $ x\ x_{min}\ a\ c\ \sigma $ are 1d or 2d as appropriate.)
After sampling f() at the 4 corners and the middle,
one can alternate:

fit a paraboloid to the data so far $\rightarrow x_{min}$
generate the next sample point $x_i$ ... how ?

Heuristics come to mind, e.g. "near $x_{min}$ but not too near",
but this is surely a well-known problem ?
(I imagine the cases $\sigma$ known and $\sigma$ unknown will be different.)

Added 11 Feb:
In grid search, one typically evaluates f() 5 times at each point (5-fold cross-validation),
on a say 10 x 10 grid, for 500 evaluations in all.
The 5 values would give an estimate of $\sigma$ at each point,
but then what —
how would a statistician combine the 5 x 100 values ?
This question on SVM grid search
shows 12 different bumpy not-so-paraboloids,
but does not show the spread at each point.
Also, search grid+search on stats.stackexchange.
Comment: This problem looks over-parameterized in 1D and under-parameterized in higher dimensions.  In 1D, $a(x-x_\text{min})^2 + c$ suffices.  (That's three parameters: $a, x_\text{min}, c$.)  In 2D, use $(x-x_\text{min})^t a (x-x_\text{min}) + c$ for a symmetric positive-definite matrix $a$.  (That's six parameters: three for $a$, two for $x_\text{min}$, and one for $c$.)
Comment: If you take two samples at precisely the same point, will you get the same value of f() or different values due to the error term?
Comment: @onestop, that's a good, fundamental point. Should we ask a separate question on "least squares with multiple values at the same point" or is that well-known ?
Comment: Are you sampling one at a time, or do you have to specify them all ahead of time? In the latter case, I think you may be screwed. For a given $Z$, one could construct a bad case by moving the minimum very far away and making the bowl very shallow.
Answer: One approach is to reparametrize your model, revealing a completely boring OLS regression. You can then find the covariance of the parameters as a function of $z$, convert it back to get the covariance of $x_{min}$, and optimize some function of it.
Reparameterizing
If $y_i = (x_i^T-x_{min})^Ta(x_i^T-x_{min}) + c + \epsilon_i$, then $y_i = z_i \beta $ for some $z=g(x)$ and $\beta = h(a, x_{min}, c)$.
Define $b \equiv -2ax_{min}$. The conversions are:
$$z = [x_1^2, 2x_1x_2, x_2^2, x_1, x_2, 1]$$
$$\beta = [a_{11}, a_{12}, a_{22}, b_1, b_2, c]$$.
$$x_{min, 1} = \frac{ a_{22} b_1 - a_{21}b_2}{a_{22} a_{11} + a_{21}^2}$$
$$x_{min, 2} = \frac{-a_{21} b_1 + a_{11}b_2}{a_{22} a_{11} + a_{21}^2}$$
Finding the variance and covariance
For a typical OLS regression, the estimate of $\beta$ is $\hat \beta =
 (Z^TZ)^{-1}Z^TY$, and the covariance of $\hat \beta$ is $\sigma^2(Z^TZ)^{-1}$. An unbiased estimator for error variance $\sigma^2$ is $\frac{1}{n-6}||Y - Z(Z^TZ)^{-1}Z^TY||_2^2$. This answers one of OP's sub-questions: how would a statistician integrate their 500 samples to estimate $\sigma^2$?
We still need to quantify the uncertainty in the original parameters. Using the delta rule, the covariance of $x_{min}$ is approximately proportional to $\phi^T(Z^TZ)^{-1}\phi$, where $\phi$ is the Jacobian of $x_{min}$ w.r.t. $\beta$ evaluated at the true $\beta$. This Jacobian's components are:

yucky but calculable, for $a$
elements of $a^{-1}$, for $b$
zeroes, for $c$.

This allows you to quantify uncertainty in $x_{min}$ for a given dataset or to choose good $x_i$'s for a given set of parameters.
When the parameters are completely unknown
One reasonable approach in this situation is to minimize the maximum penalty you could incur. If the penalty you want to minimize is the norm of the covariance of $x_{min}$, i.e. $||\phi^T(Z^TZ)^{-1}\phi||_F$, then there is no minimum. It decreases as long as $Z^TZ$ gets bigger. At this point, I wonder if there are other considerations to take into account --
 do you really want $z_i$'s at each corner of the known universe? What if $f$ is not ... quite ... a parabola?


More than 11 players

Question: Is there any instance of more than 11 players from one team, on field during a professional football match? If yes, then what action was taken against the team?
Comment: [This question](https://sports.stackexchange.com/a/15575/15589) describes a friendly match between Dinamo Moscow and Arsenal in which Dinamo allegedly ended up with 12 men at one point due to foggy conditions. I'm not posting it as an answer, since it was only a friendly and not a competitive fixture, but it's still worth mentioning.
Answer: A well documented occasion happened during the Dutch national championship in 2015, Utrecht versus Ajax. Edouard Duplan, Utrecht's forward, had an injury and left the field for medical attention. Meanwhile, the coach replaced him with Tommy Oar.
However, Duplan recovered and stepped into the field again without realising that Oar had already replaced him. It took two minutes until the referee realised the issue, apparently because people were laughing and booing.

In the image above you can see 11 players (12 with the goalkeeper, which is not visible).
Here is a link (disclaimer, I don't speak Dutch): https://www.voetbalprimeur.nl/nieuws/430022/duplan-over-lachwekkend-moment-dus-ik-dacht-dat-kan-maar-n-ding-zijn-.html?itm_source=www.voetbalprimeur.nl&itm_medium=Navigatie%20Pijltjes

PS: In the comment below OP asks if any action was taken. Despite not finding anything online I don't think that that was the case, because everybody saw that Duplan made a mistake in good faith. That, for instance, is very different from what happened in the Santos vs Corinthians match for the Brazilian championship in 2006, in which Santos' coach deliberately put 12 players in the field for the kick-off, just to cause confusion ("confusion and delay", I should say, because it took 15 minutes for the match to start).
Comment: @adithskv I didn't find anything regarding this, but I don't think so: everybody saw that the mistake was done in good faith.
Comment: https://www.transfermarkt.co.uk/spielbericht/index/spielbericht/2459843 according to this report no action was taken. A mistake like that should lead to a yellow card for Duplan, but he was lucky in this case.
Comment: Was any action taken against them?
Comment: @dly that's funny: can a player **already replaced** receive an yellow card? I reckon he can, but still it's an interesting question.
Comment: Yes, absolutely. Even a red card would be possible.
Comment: @dly that's interesting... but what's the practical effect of a red card for a player that has already left the field? A suspension for the next game?
Comment: @GerardoFurtado correct. A suspension for the next game(s) for that player and the team can keep all players on the pitch in such a case.

More than 11 players


How to use mathematical induction with inequalities?

Question: I've been using mathematical induction to prove propositions like this:
$$1 + 3 + 5 + \cdots + (2n-1) = n^2$$
Which is an equality. I am, however, unable to solve inequalities. For instance, this one:
$$ 1 + \frac{1}{2} + \frac{1}{3} + \cdots + \frac{1}{n} \leq \frac{n}{2} + 1 $$
Every time my books solves one, it seems to use a different approach, making it hard to analyze. I wonder if there is a more standard procedure for working with mathematical induction (inequalities).
There are a lot of questions related to solving this kind of problem. Like these:

How to prove $a^n < n!$ for all $n$ sufficiently large, and $n! \leq n^n$ for all $n$, by induction? - in this one, the asker was just given hints (it was homework)
How to prove $n < n!$ if $n > 2$ by induction? Ilya gave an answer, but there was little explanation (and I'd like some more details on the procedure)
how: mathematical induction prove inequation Also little explanation. Solving it with one line is great, but I'd prefer large blocks of text instead.

Can you give me a more in depth explanation of the whole procedure?
Comment: It's similar to proof of equality. The inequality holds for $n = 1$. Suppose it is true for $n$ and you need to prove it is satisfied for $n+1$.
Answer: The inequality certainly holds at $n=1$. We show that if it holds when $n=k$, then it holds when $n=k+1$. So we assume that for a certain number $k$, we have
$$1+\frac{1}{2}+\frac{1}{3}+\cdots +\frac{1}{k} \le \frac{k}{2}+1.\tag{$1$}$$
We want to prove that the inequality holds when $n=k+1$. So we want to show that
$$1+\frac{1}{2}+\frac{1}{3}+\cdots+\frac{1}{k}+\frac{1}{k+1}\le\frac{k+1}{2}+1.\tag{$2$}$$
How shall we use the induction assumption $(1)$ to show that $(2)$ holds? Note that the left-hand side of $(2)$ is pretty close to the left-hand side of $(1)$. The sum of the first $k$ terms in $(2)$ is just the left-hand side of $1$. So the part before the $\frac{1}{k+1}$ is, by $(1)$, $\le \frac{k}{2}+1$.
Using more formal language, we can say that by the induction assumption,
 $$1+\frac{1}{2}+\frac{1}{3}+\cdots+\frac{1}{k}+\frac{1}{k+1}\le \frac{k}{2}+1+\frac{1}{k+1}.$$
We will be finished if we can show that
$$\frac{k}{2}+1+\frac{1}{k+1}\le \frac{k+1}{2}+1.$$
This is equivalent to showing that
$$\frac{k}{2}+1+\frac{1}{k+1}\le \frac{k}{2}+\frac{1}{2}+1.$$
The two sides are very similar. We only need to show that
$$\frac{1}{k+1}\le \frac{1}{2}.$$
This is obvious, since $k\ge 1$.
We have proved the induction step. The base step $n=1$ was obvious, so we are finished.
Comment: Ah! I would have never seen that induction step procedure like that. Awesome thinking - thank you! Question: is this induction step some kind of "standard" or are all exercises of this kind significantly different?
Comment: @Omega: I think of it as standard. I wrote down the formula for "holds at $n=k$." This was $(1)$. Mechanical, we can always do that. Then wrote down formula for "holds at $k+1$. This was $(2)$, mechanical. Then I looked for something in $(1)$ that would help prove $(2)$. This part is not quite mechanical, but the $1+\cdots+\frac{1}{k}$ part of $(2)$ is kind of saying "use what $(1)$ tells you about me." Finally, we had to do the last part, showing that $\frac{k}{2}+1+\frac{1}{k+1}\le \frac{k+1}{2}+1$. This was the only part that was a bit different from the inductions you have done.
Answer: How rigorous does your proof have to be? You don't need induction/perturbation to prove it. You can notice that your inequality is the same as
$$
\frac{1}{2}+\frac{1}{3}+\ldots +\frac{1}{n} <\frac{1}{2}+\frac{1}{2}+ \ldots +\frac{1}{2}=\frac{n}{2} \ \forall \ n \ \geq \ 2
$$
It is event easier if you notice that
$$
1+\frac{1}{2} +\ldots +\frac{1}{n} =H_n = O( \log n) \subseteq O(n)
$$
since $\frac{n}{2}+1=O(n)$
Comment: Well, given it is a book exercise in a chapter about induction, I'd like to approach it with induction either way. But thanks for the great idea!
Comment: You are welcome
Answer: I'm not sure what you expect exactly, but here is how I would do the inequality you mention.
We start with the base step (as it is usually called); the important point is that induction is a process where you show that if some property holds for a number, it holds for the next. First step is to prove it holds for the first number. So, in this case, $n=1$ and the inequality reads
$$
1<\frac12+1,
$$
which obviously holds.
Now we assume the inductive hypothesis, in this case that
$$
1+\frac12+\cdots+\frac1n<\frac{n}2+1,
$$
and we try to use this information to prove it for $n+1$. Then we have
$$
1+\frac12+\cdots+\frac1n+\frac1{n+1}=\left(1+\frac12+\cdots+\frac1n\right)+\frac1{n+1}.
$$
I inserted the brackets to show that we have the sum we know about, through the inductive hypothesis: so
$$
1+\frac12+\cdots+\frac1n+\frac1{n+1}<\frac{n}2+1+\frac1{n+1}.
$$
Now comes the nontrivial part (though not hard in this case), where we need to somehow get $(n+1)/2+1$. Note that this is equal to $n/2+1$ (which we already have) plus $1/2$. And this suggests the proof: as $n\geq1$, $1/(n+1)\leq1/2$. So
$$
1+\frac12+\cdots+\frac1n+\frac1{n+1}<\frac{n}2+1+\frac1{n+1}\leq\frac{n}2+1+\frac12=\frac{n+1}2+1.
$$
So, assuming the inequality holds for $n$, we have shown it holds for $n+1$. So, by induction, the inequality holds for all $n$.
Answer: I see this post is old, but I answer it in case another one has the same problem.
If you have to prove $$1 + 3 + 5 + \cdots + (2n-1) = n^2\tag{*}$$  it is enough to find the LHS of the previous equation in the LHS of $$1 + 3 + 5 + \cdots + (2n-1) + (2(n+1)-1)= (n+1)^2\tag{**}$$The next step is assuming the first equation is true and replace the RHS of (*) in LHS of (**) to obtain $$n^2+(2(n+1)-1)=n^2+2n+1$$ Algebraically, it simplifies as $$n^2+2n+1=n^2+2n+1$$ which proves the first statement.
If you have to prove an inequality holds, the trick is to find what you have on each side of (n) assumption on each side of (n+1)  assumption.
In the induction step of your example, you have $$1+\frac{1}{2}+\frac{1}{3}+\cdots+\frac{1}{k}+\frac{1}{k+1}\le\frac{k+1}{2}+1\tag{1}$$
Which can be organized as $$(\frac{1}{k+1})+(1+\frac{1}{2}+\frac{1}{3}+\cdots+\frac{1}{k})\le(\frac{k}{2}+1)+\frac{1}{2}\tag{2}$$
I did not add anything, I just reorganized each side of the inequality to show that the statement $1 + \frac{1}{2} + \frac{1}{3} + \cdots + \frac{1}{k} \leq \frac{k}{2} + 1$ is contained in (1).
Now, if I assume that $1 + \frac{1}{2} + \frac{1}{3} + \cdots + \frac{1}{n} \leq \frac{n}{2} + 1$ is true, then (2) must be true since $\frac{1}{k+2}\leq\frac{1}{2}$ for every positive integer.


Visible Geopoints within phone screen

Question: I am displaying some marker on map. i want to find out the visible geopoints(markers) within phone screen. Is it possible?
Answer: Its possible to add marker on geo point location. See this
Answer: Check this out if you want to put marker on map after touch some certain area:
Returning a GeoPoint on user touch MapView Android

Visible Geopoints within phone screen


How can I attach an existing server image to an image field rather than uploading a new image file?

Question: Is there a module or some other way of attaching an image to an image field by selecting the image from existing files on the server rather than upload a new image?
I'm working on a project where many nodes have an image field. That image is displayed in various places at different sizes using image styles.
The users are migrating from another system and they're very used to the "image library" concept. They like to upload images that they will later use in various places around the site. The standard image field on a node only lets you upload from the local file system.
Ideally we'd like to have a "browse server" button instead of the upload button but end up with the same resulting image field.
The Media module comes tantalizingly close and I'm sure we'll use it for videos etc but it creates a media asset field, not an image field which I don't think can be resized with image styles and used so easily in views etc.
I tried the image picker module late last night. Maybe I need to try it again but I don't think I quite understood it. We don't really want resizing and create thumbnails etc on the node edit screen. We really just want a way to create an image field where the path points to an existing file somewhere below /sites/default/files. The files will be uploaded with something like IMCE.
Thanks for any ideas.
Comment: This question is open again for Drupal 8, where the answers below do not seem to be working (yet)
Answer: I think Filefield Sources along with IMCE does what you need.
Comment: This works perfectly.  Thanks.

The other answers sound good too.
Comment: Thank you for recommending this. This is just a wonderful module. It even looks cleaner in page edit screen.
Answer: You can also use IMCE for filefield that was just released. IMCE for File Field allows users to select files from IMCE File Browser for file fields. It supports FTP uploaded files by automatically registering them as IMCE files thus making them usable in a file field.
Answer: The Media module is also useful for images, but you can also use a regular image field and use the Media widget to upload or select images from the server. The field remains the same, only the way for the image to get inputted changes. I believe you even have the possibility to search and filter in the widget that comes with Media module 2.x
Comment: [Media 2.x](https://drupal.org/project/media) is the new hotness, yes. The same file can be re-used in multiple places. The Media file selector widget allows users to choose an existing uploaded file, or upload a new one.


Test for bias in the residuals of regressions

Question: Most of the answers I found say "look at the residual plots". Which is great!
But I have a large set of curves, and would like to "distinguish" time series curves that fit a model without bias in the residuals. For example, testing whether curves are mostly "white noise" and fit a model like y = constant_mean + random_noise .
Examples
In the following example time series, a polynomial fit does not give biased residuals:

And, as expected, a linear fit does have biased residuals:

How can i test for bias in the residuals?
Is there a correct way of doing this? Or any thoughts?
Mine so far include:
Looking for a test similar to heteroscedasticity, but for the mean of the residuals.
Maybe some kind of sliding window scan, of the residuals of a linear fit with null slope. In that case perhaps the "distributions of means" over all time windows (continuous subsets) must be the same across all windows then there is no bias. For example, that should be the case in curves of this appearance:

I've also seen some suggestions for using auto-correlation, "serial correlation" or a "white noise test" for the residuals may work (see comments).
Use case
I have many curves, and i would like to find which of them fit noisy (flat|straight) lines and which do not. Or at least rank my curves in some way.
Thanks!
Comment: what does 'mostly white noise" mean.:) There are tests if a model is white noise or not. The issue here btw is serial correlation not bias as I understand that term. I don't think that something that is not white noise is biased.
Comment: Hi thanks for replying! by white noise i mean "random fluctuations around a mean value". What are the tests for that?
Comment: I had not heard of "serial correlation" but it seems that it is the same as autocorrelation. How would you use that to approach the question?
Comment: "not white noise" will have biased residuals if the model is linear and the data is not, right? If i tried to fit a straight line to data 3000000230, the residuals of the fit would be biased.
Comment: serial correlation includes MA patterns I believe while I think autocorrelation is only AR patterns - although I could be wrong at that. There are many tests for white noise - which is the absence of AR and MA effects. In ARIMA  Ljung Box tests for this. In regression I think Breusch-Godfrey  is preferred because their are doubts about of the validity of Ljung Box. This link from this board is useful in that light. https://stats.stackexchange.com/questions/148004/testing-for-autocorrelation-ljung-box-versus-breusch-godfrey
Comment: My understanding of bias is this is error in the parameters (the slopes in regression). Which is different then whether the error term has time patterns in it I believe (but again I might not understand this correctly). AC is usually seen not to cause bias, but only impact the Standard Errors (there are some exceptions in some time series approaches that use lags, there autocorrelation can cause bias in the parameters).
Answer: for the DHARMa::plotResiduals function, my current solution to detecting patterns / bias in the residuals is to use test for the significance of a 0.5 quantile regression (package qgam) from the null expectation, which would be a flat line at 0 in your case.
In principle, you could use the DHARMa function directly on your residuals, however, it assumes that residuals are scaled between 0 and 1, so in your case, so you would first have to calculate DHARMa residuals from your model. The alternative is to fit a qgam models on your residuals by hand.
Comment: Thank you Florian, It might take a while but I will look into your solution and come back.


Há alguma forma de conectar um projeto feito em node.js direto a um dominio?

Question: Bom o meu problema é porque tenho um site aberto na porta 80 e um projeto feito em node aberto na porta 8080. Possuo o dominio:https://erkonow.com, ao tentar acessar ele só direciona todos os subdomínios ao meu site(fazendo com que o meu aplicativo fique sem dominio), há alguma forma de eu fazer o aplicativo apontar pra um subdomínio? No caso: https://coup.erkonow.com, uso o Xampp.  Alguém consegue me explicar ou dar uma orientação?

Uma outra saída possível seria uma forma de rodar *.php nesse meu app,
  pois assim eu conseguiria encaixar a página que desejo ao aplicativo.
Comment: Cara, muda a porta do node pelo express (ou sei lá que web server você está usando com node), só isso. Põem porta 3000.
Answer: Não há nenhum problema em usar a porta 8080 para isso. Embora possível, você não precisa do Xampp para prover uma aplicação node, ele próprio cria um http server e escuta na porta definida.
Primeiro de tudo, sua aplicação deve ser acessível pela porta 8080, ou seja, a porta tem que estar aberta no seu server e a aplicação rodando na mesma. Depois disso, você precisa acessar o seu provedor de domínio e procurar lá como criar um subdomínio apontando para o seu IP do servidor juntamente com a porta 8080 (ex: 127.168.0.1:8080). Cada provedor irá fazer isso de uma forma diferente, e alguns nem permitem fazer isso pela interface, aí você teria que enviar um email para eles. Você provavelmente terá que configurar o CNAME para isso.
talvez ajude:
https://www.cyberciti.biz/faq/howto-rhel-linux-open-port-using-iptables/


"On the consequences of an exact de Bruijn Function", or "If Ramanujan had more time..."

Question: In this question on Math.SE, I asked about Ramanujan's (ridiculously close) approximation for counting the number of 3-smooth integers less than or equal to a given positive integer $N$, namely,
\begin{eqnarray}
\frac{\log 2 N \ \log 3 N}{2 \log 2 \ \log 3}.
\end{eqnarray}
In his posthumously published notebook, Ramanujan generalized this formula to similarly counting numbers of the form $b_1^{r_1} b_{2}^{r_{2}}$, where $b_1, b_2 > 1$ are (not necessarily distinct) natural numbers and $r_1, r_2 \geq 0$:
\begin{eqnarray}
\frac{\log b_1 N \ \log b_2 N}{2 \log b_1 \ \log b_2},
\end{eqnarray}
where a factor of $\frac{1}{2}$ is to be added if $N$ is of the prescribed form. Both of these problems could be understood by counting the number of non-negative integer solutions of the Diophantine inequality: $(\log b_1) x_1 + (\log b_2) x_2 \leq \log N$, which also counts the number of $\mathbb{Z}$-lattice points in the $\log N$ dilate of the $2$-polytope $\mathcal{P} = \textbf{conv}(\mathbf{0}, (\log b_{1})^{-1} \mathbf{e}_1, (\log b_2)^{-1} \mathbf{e}_{2})$. Here, $\{ \mathbf{e}_{i}\}$ is the standard basis of $\mathbb{R}^{n}$. Unfortunately, counting lattice points in real polytopes is hard.
My question, now, is how important a contribution to mathematics would it be if one had an exact formula for counting $y$-smooth integers less than or equal to a real $x > 0$, i.e., an exact formula for the de Bruijn function $\Psi(x,y)$? This would, at the same time, translate into an exact formula for counting lattice points of real polytopes of the form $\textbf{conv}(\mathbf{0}, a_{1} \mathbf{e}_{1}, \dots, a_{n} \mathbf{e}_{n})$ with $a_{i} \in \mathbb{R}_{> 0}$.
I'm aware of the review articles by Pomerance, Granville, Hildebrand and Tenenbaum, which each deal with various estimates of the De Bruijn function and its useful in the Quadratic Sieve Method of factorization and applications to cryptography, and even Waring's Problem. However, none of these review articles deal with the consequences of having an exact formula.
Answer: I would say it would be important enough to publish it. According to the survey by Hildebrand and Tenenbaum, the approximate estimates have themselves found surprising applications in number theory. An exact formula will only do better!
In any case, one can never expect the surprising ways some results can be used. Consider the pigeon-hole principle for instance.
Congratulations, btw.
(Probably not the answer you were expecting, though).


Imprimir consultas

Question: Tenho uma view em minha aplicação em asp.net mvc que permite ao usuário realizar uma busca, a qual retorna nome e dados daquela busca. Eu queria poder imprimir esse resultado da busca. Como eu faço para imprimir div ou table?
Minha view:

     @using (Html.BeginForm())
     {
         IEnumerable<Banco.Models.Perfil> modelPerfil = (IEnumerable<Banco.Models.Perfil>)ViewBag.Perfil;

Pesquisa por Dados

  <input type="text" name="texto" id="texto" placeholder="Digite a busca" />
         <button class="btn btn-primary btn-xs" type="submit">Filtrar</button>

     }

    @{
        if (Model != null)
        {
            foreach (var item in Model)
            {

        Nome
        Experiência

                   @item.Perfil.Nome
                    @item.Atividades
                   @* @item.Perfil.Chapa	*@

                      |   @Html.ActionLink("Ver Dados", "Details", "Relatorio", new { userName = @item.Perfil.Chapa }, null)|

            }
        }
    }

Controller
    [HttpGet]
    public ActionResult Pesquisa()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Pesquisa(string texto)
    {
        ViewBag.Perfil = db.Perfis.AsEnumerable();
        return View(db.Experiencia.Where(x => x.Atividades.Contains(texto)).OrderBy(x => x.NomeEmpresa));
    }

Comment: Em qual formato você quer imprimir?
Comment: Tanto faz. Só quero poder realizar a impressão do resultado da busca.
Answer: Aqui com base nesse link tem um tutorial bem fácil de se seguir. Eu usei e é relativamente simples, só precisa de um pouco de atenção. Lá tem como fazer, mas vou colocar os exemplos aqui pra você:
Instalação da biblioteca
Para instalar é fácil, vá ao prompt do Nuget e instale a biblioteca Rotativa, que é ela que vai ser usada pra gerar o pdf pra ser impresso. Dessa maneira abrindo o prompt coloque:
Install-Package Rotativa(ou pra ser ficar mais igual ao prompt: PM>Install-Package Rotativa)
Confecção da View
Essa view vai ser usada como modelo pra criação do seu relatório, ou consulta, como você quer. Lembrando aqui que esse relatório é só um exemplo, você pode customiza-lo da maneira que achar melhor:
Modelo.cshtml
 @model RelatorioPDF.Models.Usuario
 <!DOCTYPE html>

   <meta charset="utf-8" />
   <title>Exemplo de Relatório em PDF</title>

  <link href="~/Content/estilos-relatorio.css" rel="stylesheet" />

RECIBO DE DISPENSAÇÃO

Meu Sistema

Hospital São Paulo

Farmácia

                Dispensado:

                10/10/2012

                Cartão do SUS:

                123.1232.123.123

                Usuario:

                João da Silva Gonçalves

                Prescritor:

                Jonas São João

                Nº Registro:

                12323132

                Origem da Receita:

                10/10/012

Produtos Dispensados:

                        Produto
                        Atendido?
                        Und
                        Dispensado
                        Unitário R$
                        Total R$

                        Anador
                        Sim
                        FRS
                        10
                        1,2345
                        12,23

                        Possologia: 1 dose, 3 vez por dia, durante 5 dias

                        Dipirona
                        Sim
                        FRS
                        10
                        1,2345
                        12,23

                        Possologia: 1 dose, 3 vez por dia, durante 5 dias

                        Total
                        R$ 12,23

                Observação:

                Paciente com fortes dores de cabeça

Usuário: Cleyton Ferrari Emitido: 26/10/2012 CleytonFerrari.com

Colocando para funcionar
Depois de a view de modelo ter sido criada pra ser impressa ou salva em pdf, agora é só criar a lógica no controller pra que se seja realmente criado o pdf:
Controller
Nesse controller, é so um exemplo, pra salientar, e você pode colocar a action de criação do modelo em qualquer controller ok ? Aqui é só um exemplo.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RelatorioPDF.Models;
using Rotativa;
using Rotativa.Options;

namespace RelatorioPDF.Controllers
{
  public class RelatoriosController : Controller
{
       /*
           * Retorna a view simples em HTML, usada como modelo para gerar o PDF
        */
    public ActionResult ModeloHTML()
    {
        return View("Modelo");
    }

       /*
        * Retorna um PDF diretamente no browser com as configurações padrões
        * ViewName é setado somente para utilizar o próprio Modelo anterior
        * Caso não queira setar o ViewName, você deve gerar a view com o mesmo nome da action
     */
    public ActionResult PDFPadrao()
    {
        var pdf = new ViewAsPdf
                      {
                          ViewName = "Modelo"
                      };
        return pdf;
    }

    /*
     * Configura algumas propriedades do PDF, inclusive o nome do arquivo gerado,
     * Porem agora ele baixa o pdf ao invés de mostrar no browser
     */
    public ActionResult PDFConfigurado()
    {
        var pdf = new ViewAsPdf
        {
            ViewName = "Modelo",
            FileName = "NomeDoArquivoPDF.pdf",
            PageSize = Size.A4,
            IsGrayScale = true,
            PageMargins = new Margins{Bottom = 5, Left = 5, Right = 5, Top = 5},
        };
        return pdf;
    }

    /*
     * Pode passar um modelo para a view que vai ser utilizada para gerar o PDF
     */
    public ActionResult PDFComModel()
    {
        var modelo = new Usuario
                         {
                             Nome = "Cleyton Ferrari",
                             Site = "http://cleytonferrari.com"
                         };

        var pdf = new ViewAsPdf
        {
            ViewName = "Modelo",
            Model = modelo
        };

        return pdf;
    }

}
}

Observações
Seguindo esse exemplo irá funcionar a geração da impressão de suas consultas tranquilamente. Agora, se for uma coisa mais dinâmica, digo, com dados vindos do banco, é só você adaptar o código e colocar a manipulação do banco, igual quando vem criadas as actions que vem com o scaffolding. Ou você pode dar uma olhada em uma pergunta minha que eu coloquei a action do jeito certo pra buscar os dados dinamicamente, e inclusive respondi a pergunta mostrando a forma certa de se gerar o relatório ao clicar no link.
Comment: Não é bom usar o Rotativa. Ele não funciona no Azure.
Comment: Mas se ele num for colocar no azure é uma boa. Mas você sabe porque não funciona @CiganoMorrisonMendez ?
Comment: Dá erro. Contatei o desenvolvedor e ele disse que não iria resolver.
Comment: Nossa... Que interesse dele então em relação ao um erro que ele pode resolver né... Mas tem outros que funcionam certo ?
Comment: Sim, tem o RazorPDF, que funciona em Azure. Este que eu uso nas minhas soluções: https://www.nuget.org/packages/RazorPDF
Answer: A maneira mais simples é através de um link em JavaScript:
Imprimir

Para evitar que o título seja impresso na página, use a seguinte configuração no seu Layout:

Comment: Não estou usando Azure não e busco os dados do banco sim. Vou tentar o razorPDF então e para algumas pastas basta esse javascript. Testei esse javascript:windows.print e vi que retorna tudo o que aparece na minha página. Ok, em alguns casos é isso mesmo que preciso, mas se eu quiser por exemplo  não imprimir os botões e links da página, como faço?
Comment: Api você teria que preparar uma View simplificada. Não precisa ser necessariamente um PDF.
Comment: Só criando uma outra view simplificada? Não consigo de alguma forma na mesma view omitir o que não quero imprimir?
Comment: Só criando uma função JavaScript que oculte aquilo que você não quer exibir, pra depois chamar o `window.print()`.

Imprimir consultas


Does IDs from `ls -l /dev/disk/by-id` output are unique to a disk? - DELL PERC card

Question: Does output from ls -l /dev/disk/by-id can be used as a universal disk identifier?
I am currently trying to find a unique identifier that I can use to create a ZFS raidz pool using a unique identifier for each disk.
Potentially I want to use the same identifier to restore the ZFS pool after the system reinstall.
I have these requirements:

Disks don't have partitions yet.
Disks can be moved to another machine.
Disks can change position slot in the same machine.

I'm currently using:

Ubuntu Server 20.04 LTS
DELL PowerEdge R710
DELL PERC6/i raid card
5 x 500GB DELL disks attached to raid card (sdb-sbf)
1 x 120GB SSD that is not attached to the raid card (sda)

PS. This RAID card doesn't have pass-through, so each disk is attached as an individual RAID0. Does it change the serial exposed to the OS?
Example output from ls -lah /dev/disk/by-id/
~$ ls -lah /dev/disk/by-id/
total 0
drwxr-xr-x 3 root root 960 Oct 23 06:12 .
drwxr-xr-x 8 root root 160 Oct 18 18:53 ..
lrwxrwxrwx 1 root root   9 Oct 18 18:53 ata-ADATA_SP550_2G2520036769 -> ../../sda
lrwxrwxrwx 1 root root  10 Oct 18 18:54 ata-ADATA_SP550_2G2520036769-part1 -> ../../sda1
lrwxrwxrwx 1 root root  10 Oct 18 18:54 ata-ADATA_SP550_2G2520036769-part2 -> ../../sda2
lrwxrwxrwx 1 root root   9 Oct 18 18:53 scsi-0ATA_ADATA_SP550_2G2520036769 -> ../../sda
lrwxrwxrwx 1 root root  10 Oct 18 18:54 scsi-0ATA_ADATA_SP550_2G2520036769-part1 -> ../../sda1
lrwxrwxrwx 1 root root  10 Oct 18 18:54 scsi-0ATA_ADATA_SP550_2G2520036769-part2 -> ../../sda2
lrwxrwxrwx 1 root root   9 Oct 18 18:53 scsi-1ATA_ADATA_SP550_2G2520036769 -> ../../sda
lrwxrwxrwx 1 root root  10 Oct 18 18:54 scsi-1ATA_ADATA_SP550_2G2520036769-part1 -> ../../sda1
lrwxrwxrwx 1 root root  10 Oct 18 18:54 scsi-1ATA_ADATA_SP550_2G2520036769-part2 -> ../../sda2
lrwxrwxrwx 1 root root   9 Oct 18 18:53 scsi-36a4badb02b6020002666efd071e1c1a0 -> ../../sdb
lrwxrwxrwx 1 root root   9 Oct 18 18:53 scsi-36a4badb02b6020002666effa74599a2b -> ../../sdc
lrwxrwxrwx 1 root root   9 Oct 18 18:53 scsi-36a4badb02b6020002666f01c766dd5f0 -> ../../sdd
lrwxrwxrwx 1 root root   9 Oct 18 18:53 scsi-36a4badb02b6020002666f04478ce7cc5 -> ../../sde
lrwxrwxrwx 1 root root   9 Oct 18 18:53 scsi-36a4badb02b6020002666f0627a912d6b -> ../../sdf
lrwxrwxrwx 1 root root   9 Oct 18 18:53 scsi-SATA_ADATA_SP550_2G2520036769 -> ../../sda
lrwxrwxrwx 1 root root  10 Oct 18 18:54 scsi-SATA_ADATA_SP550_2G2520036769-part1 -> ../../sda1
lrwxrwxrwx 1 root root  10 Oct 18 18:54 scsi-SATA_ADATA_SP550_2G2520036769-part2 -> ../../sda2
drwxr-xr-x 2 root root 340 Oct 18 18:53 scsi-SDELL_PERC_6
lrwxrwxrwx 1 root root   9 Oct 18 18:53 usb-iDRAC_LCDRIVE_20120430-0:0 -> ../../sdg
lrwxrwxrwx 1 root root   9 Oct 18 18:53 usb-iDRAC_Virtual_CD_20120430-0:0 -> ../../sr0
lrwxrwxrwx 1 root root   9 Oct 18 18:53 usb-iDRAC_Virtual_Floppy_20120430-0:1 -> ../../sdh
lrwxrwxrwx 1 root root   9 Oct 18 18:53 wwn-0x6a4badb02b6020002666efd071e1c1a0 -> ../../sdb
lrwxrwxrwx 1 root root   9 Oct 18 18:53 wwn-0x6a4badb02b6020002666effa74599a2b -> ../../sdc
lrwxrwxrwx 1 root root   9 Oct 18 18:53 wwn-0x6a4badb02b6020002666f01c766dd5f0 -> ../../sdd
lrwxrwxrwx 1 root root   9 Oct 18 18:53 wwn-0x6a4badb02b6020002666f04478ce7cc5 -> ../../sde
lrwxrwxrwx 1 root root   9 Oct 18 18:53 wwn-0x6a4badb02b6020002666f0627a912d6b -> ../../sdf

Is /dev/disk/by-id/wwn-0x6a4badb02b6020002666efd071e1c1a0 persistent if system is reinstalled? ('wwn' standing for World Wide Name)
Does it point to the disk or to the raid card slot?
Answer: The World Wide Name is expected to be globally unique, and barring mistakes by a drive manufacturer it should be.
However, in the case of the single-disk RAID0 on your ancient PERC card, which was how people worked around its lack of JBOD support, the WWN refers to the virtual RAID0 disk, not to the physical disk. (And global uniqueness might not be possible, but they will at least be unique on your controller.) This should not cause you a problem in practice, but if it does, then buy a different HBA that supports JBOD.
Comment: Your consideration about replacing the PERC card is pretty on point, those cards are pretty old and don't offer JBOD. Thank you by the way.


If $12$ distinct balls are distributed to $8$ numbered cells, what is the probability that there is no empty cell?

Question: I am trying to solve this question:
Let us assume we are distributing 12 different balls between 8 numbered cells, so that each distribution of balls into cells is obtained with equal probability. What is the probability that there is no empty cell?
At first I gave to each ball an unique ID, such that:
1 = ball number 1,
2 = ball number 2, and so on.
Now i defined $\Omega =\left\{ \left( x_{1},\ldots ,x_{12}\right) | \forall i,x_{i}\in \left[ 8\right] \right\} =\left[ 8\right] ^{12}$, and so the event we want to compute is:
$A=\{ \left( x_{1},\ldots ,x_{12}\right) \in \Omega | \forall i\in \left[ 8\right] \exists j\in \left[ 12\right] ,x_{j}=i \}$.
At first I tried to work with $A^{c}$, but then I noticed that I have duplicates, so I tried to compute $|A|$ directly.
I said, in order for no cell to be empty, we will choose 8 balls out of the 12 and distribute them into the eight cells, so that each cell contains exactly one ball. Then, we will distribute the remaining four balls into the eight cells and finish.
So let's do the math:

Choose 8 unique balls out of 12 is $\begin{pmatrix} 12 \\ 8 \end{pmatrix}$
Distribute the balls to the cells is $8!$
Then, distribute the remaining four is $8^{4}$

So, overall we have: $|A| = \begin{pmatrix} 12 \\ 8 \end{pmatrix} \cdot 8! \cdot 8^{4}$
Now, $|\Omega| = 8^{12}$, so finally we get:
$\mathbb{P}(A) = \dfrac{\begin{pmatrix} 12 \\ 8 \end{pmatrix}\cdot 8!\cdot 8^{4}}{8^{12}} = 1.18961 >1$.
I don't understand what I'm doing wrong, so would glad for help.
Comment: Please write a title that is specific to the problem.
Answer: Method 1:  We use the Inclusion-Exclusion Principle to count the favorable cases.
There are eight choices for each of the $12$ balls, so there are $8^{12}$ possible distributions.  From these, we must subtract those distributions which miss one or more of the cells.  There are $\binom{8}{k}$ ways to exclude $k$ of the eight cells from receiving a ball and $(8 - k)^{12}$ ways to distribute the balls to the remaining $8 - k$ cells.  By the Inclusion-Exclusion Principle, the number of ways to distribute $12$ distinct balls to eight cells so that no cell is left empty is
$$8^{12} - \binom{8}{1}7^{12} + \binom{8}{2}6^{12} - \binom{8}{3}5^{12} + \binom{8}{4}4^{12} - \binom{8}{5}3^{12} + \binom{8}{6}2^{12} - \binom{8}{7}1^{12} + \binom{8}{8}0^{12}$$
To see what you are doing wrong, we need to do a direct count.
Method 2:  We perform a direct count of the favorable cases.
The number $12$ can be partitioned into eight parts in five ways:
\begin{align*}
12 & = 5 + 1 + 1 + 1 + 1 + 1 + 1 + 1\\
   & = 4 + 2 + 1 + 1 + 1 + 1 + 1 + 1\\
   & = 3 + 3 + 1 + 1 + 1 + 1 + 1 + 1\\
   & = 3 + 2 + 2 + 1 + 1 + 1 + 1 + 1\\
   & = 2 + 2 + 2 + 2 + 1 + 1 + 1 + 1
\end{align*}
Five balls in one cell and one ball in each of the other seven cells:  There are eight ways to select the cell which receives five balls, $\binom{12}{5}$ ways to select the balls that are placed in that cell, and $7!$ ways to distribute the remaining seven balls to the remaining seven cells so that each of those cells receives one ball.  Hence, there are
$$\binom{8}{1}\binom{12}{5}7!$$
such distributions.
Four balls in one cell, two balls in another cell, and one ball in each of the other six cells:  There are eight ways to select the cell which receives four balls, $\binom{12}{4}$ ways to select the four balls that are placed in that cell, seven ways to select the cell which receives two balls, $\binom{8}{2}$ ways to select the balls that are placed in that cell, and $6!$ ways to distribute the remaining six balls to the remaining six cells so that each of those cells receives one ball.  Hence, there are
$$\binom{8}{1}\binom{12}{4}\binom{7}{1}\binom{8}{2}6!$$
such distributions.
Three balls each in two cells and one ball each in the other six cells:  There are $\binom{8}{2}$ ways to select the two cells that will each receive three balls, $\binom{12}{3}$ ways to select the three balls that will be placed in the leftmost of those two cells, $\binom{9}{3}$ ways to select the three balls that will be placed in the other selected cell, and $6!$ ways to distribute the remaining six balls to the remaining six cells so that each of those cells receives one ball.  Hence, there are
$$\binom{8}{2}\binom{12}{3}\binom{9}{3}6!$$
such distributions.
Three balls in one cell, two balls each in two other cells, and one ball each in the other five cells:  There are eight ways to select the cell that receives three balls, $\binom{12}{3}$ ways to select the three balls that will be placed in that cell, $\binom{7}{2}$ ways to select the two cells that will receive two balls each, $\binom{9}{2}$ ways to select the two balls that will be placed in the leftmost of those cells, $\binom{7}{2}$ ways to select the two balls that will be placed in the other selected cell, and $5!$ ways to distribute the remaining five balls to the remaining five cells so that each cell receives one of those balls.  There are
$$\binom{8}{1}\binom{12}{3}\binom{7}{2}\binom{9}{2}\binom{7}{2}5!$$
such distributions.
Four cells each receive two balls and the other four cells each receive one ball:  There are $\binom{8}{4}$ ways to select the four cells that each receive four balls, $\binom{12}{2}\binom{10}{2}\binom{8}{2}\binom{6}{2}$ ways to select the balls that will be placed in those cells as we proceed from the leftmost to the rightmost of the four selected cells, and $4!$ ways to distribute the remaining four balls to the remaining four cells so that each cell receives one of those balls.  There are
$$\binom{8}{4}\binom{12}{2}\binom{10}{2}\binom{8}{2}\binom{6}{2}4!$$
such distributions.
Total:  Since these cases are mutually exclusive and exhaustive, there are
$$\binom{8}{1}\binom{12}{5}7! + \binom{8}{1}\binom{12}{4}\binom{7}{1}\binom{8}{2}6! + \binom{8}{2}\binom{12}{3}\binom{9}{3}6! + \binom{8}{1}\binom{12}{3}\binom{7}{2}\binom{9}{2}\binom{7}{2}5! + \binom{8}{4}\binom{12}{2}\binom{10}{2}\binom{8}{2}\binom{6}{2}4!$$
ways to distribute $12$ distinct balls to eight cells so that no cell is left empty.
What are you doing wrong?
By designating a particular ball as the ball that is placed in a cell, you count each distribution multiple times, once for each ball you could have designated as the ball that is placed in that cell.
Let's illustrate that point with second case, which you count $4 \cdot 2 = 8$ times.  Suppose balls $1, 2, 3, 4$ are placed in cell $A$, balls $5, 6$ are placed in cell $B$, ball $7$ is placed in cell $C$, ball $8$ is placed in cell $D$, ball $9$ is placed in cell $E$, ball $10$ is placed in cell $F$, ball $11$ is placed in cell $G$, and ball $12$ is placed in cell $H$.  You count this distribution eight times:
$$
\begin{array}{c c c c c c c c c c}
A & B & C & D & E & F & G & H & \text{additional balls in cell $A$} & \text{additional ball in cell $B$}\\ \hline
1 & 5 & 7 & 8 & 9 & 10 & 11 & 12 & 2, 3, 4 & 6\\
1 & 6 & 7 & 8 & 9 & 10 & 11 & 12 & 2, 3, 4 & 5\\
2 & 5 & 7 & 8 & 9 & 10 & 11 & 12 & 1, 3, 4 & 6\\
2 & 6 & 7 & 8 & 9 & 10 & 11 & 12 & 1, 3, 4 & 5\\
3 & 5 & 7 & 8 & 9 & 10 & 11 & 12 & 1, 2, 4 & 6\\
3 & 6 & 7 & 8 & 9 & 10 & 11 & 12 & 1, 2, 4 & 5\\
4 & 5 & 7 & 8 & 9 & 10 & 11 & 12 & 1, 2, 3 & 6\\
4 & 6 & 7 & 8 & 9 & 10 & 11 & 12 & 1, 2, 3 & 5\\
\end{array}
$$
By similar reasoning, you count the first case five times, the third case $3 \cdot 3 = 9$ times, the fourth case $3 \cdot 2 \cdot 2 = 12$ times, and the fifth case $2 \cdot 2 \cdot 2 \cdot 2 = 16$ times.
Observe that
$$\color{red}{5}\binom{8}{1}\binom{12}{5}7! + \color{red}{8}\binom{8}{1}\binom{12}{4}\binom{7}{1}\binom{8}{2}6! + \color{red}{9}\binom{8}{2}\binom{12}{3}\binom{9}{3}6! + \color{red}{12}\binom{8}{1}\binom{12}{3}\binom{7}{2}\binom{9}{2}\binom{7}{2}5! + \color{red}{16}\binom{8}{4}\binom{12}{2}\binom{10}{2}\binom{8}{2}\binom{6}{2}4! = \color{red}{\binom{12}{8}8!8^4}$$
Comment: Thank you very much! I now understand where I was wrong and why I need to use exclusion inclusion principle
Answer: Note that in your calculations you are counting the next senerio twice, ball 1 was chosen as one of the "filing" balls and was put in cell 1, or ball 1 wasn't chosen as one of the "filing" balls but still was put in cell 1.
To fix this divide by the number of duplicates. While noting that this number changes in correspondence to how mach was added to each cell (4 balls in 4 different cells is different then 4 balls in the same cell).
Comment: So how would you suggest to do the calculations? or to work with $A^{c}$?
Comment: I though maybe to use Inclusion–exclusion principle, but not sure how
Comment: Calculate A as you did in your answer, but when distributing the last four balls condition on how you distribiute them and devide by the number of duplicates. For example the number of events where all cells are not empty and all balls not "filing" a cell are in the same cell is $\begin{pmatrix} 12 \\ 8 \end{pmatrix} \cdot 8! \cdot 8 \cdot \frac{1}{5}$. Do the same for all other scenarios.
Answer: Each ball has $8$ choices for boxes, so total choices $=8^{12}$ which will form the denominator $D$
So we shall just focus on the number of ways, the numerator $N$
and the required probability will be $\frac{N}{D}$

The simplest way is to use Stirling numbers of the second kind, which places distinct objects into identical boxes, and permute the boxes, hence
$8!*S(12,8) = 6411968640$
If you don't have a calculator for Stirling numbers,the usual way is to apply inclusion-exclusion
The direct way may appear tedious, but can be made  semi-mechanical using permutations using the formula [Lay down pattern] $\times$ [Permute pattern]

$5 + 1 + 1 + 1 + 1 + 1 + 1 + 1:\;\Large\frac{12!}{5!}\times\frac{8!}{7!}$
$4 + 2 + 1 + 1 + 1 + 1 + 1 + 1:\;\Large\frac{12!}{4!2!}\times\frac{8!}{6!}$
$3 + 3 + 1 + 1 + 1 + 1 + 1 + 1:\;\Large\frac{12!}{3!3!}\times\frac{8!}{2!6!}$
$3 + 2 + 2 + 1 + 1 + 1 + 1 + 1:\;\Large\frac{12!}{3!2!2!}\times\frac{8!}{2!5!}$
$2 + 2 + 2 + 2 + 1 + 1 + 1 + 1:\;\Large\frac{12!}{2!2!2!2!}\times \frac{8!}{4!4!}$
Add up to get $N= 6411968640 $
Answer: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{{\displaystyle #1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\on}[1]{\operatorname{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\sr}[2]{\,\,\,\stackrel{{#1}}{{#2}}\,\,\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
\begin{align}
& \color{#44f}{\sum_{c_{1} = \color{red}{\Large1}}^{\infty}{1 \over 12}
\sum_{c_{2} = \color{red}{\Large1}}^{\infty}{1 \over 12}\ldots
\sum_{c_{8} = \color{red}{\Large1}}^{\infty}{1 \over 12}}
\bracks{z^{12}}z^{c_{1}\ +\ c_{2}\ +\ \cdots\ +\ c_{8}}
\\[5mm] = & \
{1 \over 12^{8}}\bracks{z^{12}}\pars{\sum_{c = 1}^{\infty}z^{c}}^{8} =
{1 \over 12^{8}}\bracks{z^{12}}\pars{z \over 1 - z}^{8} =
{1 \over 12^{8}}\bracks{z^{4}}\pars{1 - z}^{-8}
\\[5mm] = & \
{1 \over 12^{8}}{-8 \choose 4}\pars{-1}^{-4} =
{1 \over 12^{8}}{11 \choose 4}\pars{-1}^{4} =
{1 \over 12^{8}}\, 330
\\[5mm] = &\
\bbx{\color{#44f}{55 \over 71663616}} \approx 7.6747 \times 10^{-7}
\end{align}
Comment: Your denominator should be $8^{12}$ since there are eight choices for each of the $12$ balls.  Also, you obtained a much smaller number of favorable cases than true blue anil or I did.


SQL inserting numerous columns for matrix

Question: Is there any quick way I could transpose values in a row to column headers.. say I have row values A, B, C ... Z in a column called indx_nm. Is there a easy way to make column headers A, B, C ... Z  without having to manually populate this (I have 1000 distinct values that I meet to make a covariance matrix out of)
Answer: You may use dynamic PIVOT.
DECLARE @cols AS NVARCHAR(MAX),
@query  AS NVARCHAR(MAX);

SET @cols = STUFF((SELECT ',' + CONVERT(VARCHAR,indx_nm)
            FROM TableName c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')
set @query = 'SELECT ' + @cols + ' from             (
                select indx_nm,
                Othercolumn
                from temp
           ) x
            pivot
            (
                 max(Othercolumn)
                for indx_nm in (' + @cols + ')
            ) p '
EXECUTE @query
Comment: please post an example!
Comment: Sorry, i lost connection when i was ready to post an example. Now i am away from my pc, so i can only post some references.
Comment: This is what i assembled in my phone on top of my head, so give it a try and we'll see.
Comment: i keep getting a "incorrect syntax near '-' " on line 5 which will not go away.. weird it appears no matter how i change my code its always line 5 regardless of the code
Comment: You may have a problem on the indx_nm values. What kind of values do you have there?
Comment: You may also replace EXECUTE with PRINT, and see what sql is going to be executed. Then try that sql and see what errors you get.
Comment: and when i have `EXECUTE` it just prints `the name 'SELECT A, B, .... is not a valid identifier`
Comment: Can you post exactly the sql of the print? I am still on a phone so i cannot really test.
Comment: `DECLARE @cols AS NVARCHAR(MAX), @query  AS NVARCHAR(MAX);`

`SET @cols = STUFF((SELECT ',' + CONVERT(VARCHAR,indx_nm) FROM' 'dWA_NSCC.[CORP\Eng].indx_nm c FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)'),1,1,'')`
`SET @query = 'SELECT ' + @cols + 'from'
 '(select indx_nm, Othercolumn from temp) x pivot ( max(Othercolumn) for indx_nm in (' + @cols + ') ) p' `

`EXECUTE @query`

`SELECT * FROM dWA_NSCC.[CORP\Eng].indx_nm
ORDER BY indx_nm`
Comment: Thanks but i meant the one exposed by the print.
Comment: `DECLARE @cols AS NVARCHAR(MAX), @query  AS NVARCHAR(MAX);

SET @cols = STUFF((SELECT ',' + CONVERT(VARCHAR,indx_nm) FROM dWA_NSCC.[CORP\Eng].indx_nm c FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)'),1,1,'')
SET @query = 'SELECT ' + @cols + 'from
 (select indx_nm, Othercolumn from temp) x pivot ( max(Othercolumn) for indx_nm in (' + @cols + ') ) p'

PRINT @query`
returns: `SELECT ABQI      ,ACNACTR   ,ACNITTR   ,ACNRET    ,ACNRMBTR  ,ACNSCT    ,AGIXLT    `(and on - all the indices i have listed in the rows)
Comment: I am afraid i will need a pc. I am really sorry for the inconvinience.
Comment: every single one is distinct
Comment: Yes, but how many are there? EXECUTE has a limit of 4000 characters, so if the list is too big...


What is meant by using a probability distribution to model the output data for a regression problem?

Question: Often a theoretical text will say something like, 'a probability distribution may be used to model the data' or, 'assume a probability distribution such as normal or Lognormal for the outputs'.
What is being conveyed when someone mentions that 'a distribution is being used to model the outputs'?
Comment: It would be better to cite a particular text and quote it directly, rather than loosely summarize what many texts do.
Comment: What do you mean by "output"? Could you provide some context for those quotes?
Comment: Is there something about this you find particularly confusing? It seems self-explanatory, so I assume there's a specific aspect of it that's troubling you.
Answer: By assuming some probability for our data we mean that we use some statistical distribution (i.e. mathematical function) as approximation of our data.
Sir Francis Galton in 1886 used data on parents height and their adult children height to describe regression towards mediocrity. This was one of the first times when correlation and regression was used. We can use this data to illustrate how distribution can be used to describe data.
We can approximate parents heights distribution by a normal distribution. As you can see from the plot below, normal distribution (red line) does not fit perfectly to the data, but it fits reasonably well. You could ask why would we like to use any approximation in here? The major advantage is that it makes things simpler because we can describe whole distribution of heights just by two parameters: $\mu$ for mean height and $\sigma$ for standard deviation. Knowing these two parameters not only lets us approximately re-create the data values, but also allows us to assign probabilities to values that were not observed in our dataset.

Galton used this data to show regression to the mean phenomenon. What he described is that heights of parents and their children are related and there is some rate that describes the relation. The rate of how parent's height influences child's height can be summarized using a single number $\rho$ for correlation coefficient or regression slope. The $\rho$ parameter can be also thought as a parameter of bivariate normal distribution. So in this case, distribution not only approximates the individual variable, but also relation of two variables, i.e. it leads to a statistical model of the observed phenomenon.
This leads us to replace the original counts

with a statistical distribution (red-yellow blob marks kernel density and gray ellipses mark bivariate normal density)

By saying that we assume distribution for data we mean that we use this distribution to build a model. Such model is obviously wrong, because it is an approximation, but it is useful, since it describes the complicated phenomenon in simple mathematical terms.

Galton, F. (1886). Regression Towards Mediocrity in Hereditary Stature. Journal of the Anthropological Institute, 15, 246-263.
Hanley, J. A. (2004). "Transmuting" women into men: Galton's family data on human stature. The American Statistician, 58(3), 237-243.


Given $f(x)$ and $g(x)$ find the following and state if the composite function exists

Question: This is a two part question. I want to find the following and determine whether or not the composite functions exist. I'm fairly sure of my functions, but I would like to confirm that they are correct as well as my conclusions about whether or not they exist.
Answer: Yes, it is true if you consider real field.


Get Fullpath of embedded resource Xamarin Forms

Question: I am currently using FilePicker in xamarin forms to choose a zip file, then I get fullpath from it and use this fullpath in Xamarin.Android project. Using following code:
<code>            var result = await FilePicker.PickAsync(new PickOptions
            {

                PickerTitle = "Select zip file"
            });

            if (result != null)
            {
                FileNameLabel.Text = $"{result.FileName}";
                if (!result.FileName.EndsWith("zip", StringComparison.OrdinalIgnoreCase))
                {
                    await DisplayAlert("Wrong File", "Selected file is not right", "Ok");
                }
                else
                {
                    var stream = result.OpenReadAsync();
                    _filepath = result.FullPath;
                }

            }
</code>
I want to do the same thing, but without FilePicker, instead add my zip file as embedded resource.
I know I can access, embedded resouce using following code, but I am unable to get FullPath.
<code>        var assembly = IntrospectionExtensions.GetTypeInfo(typeof(App)).Assembly;
        Stream stream = assembly.GetManifestResourceStream("TestFile.json");
</code>
is it possible to do something like:
<code>         File file = new File(assembly.GetManifestResourceStream("TestFile.Zip"));
        _fullname = file.FullName;
</code>
Comment: embedded resources are not files and do not have file paths
Comment: Then is it logical to move embedded resource to cache and try to get Fullpath?
Answer: Yes,you could use Xamarin.Essentials to obtain the OS's cache directory and then copy the embedded resource to it.
For example:
<code>var cacheFile = Path.Combine(FileSystem.CacheDirectory, "your file");
if (File.Exists(cacheFile))
    File.Delete(cacheFile);
using (var resource = Assembly.GetExecutingAssembly().GetManifestResourceStream("your embedded resource"))
using (var file = new FileStream(cacheFile, FileMode.Create, FileAccess.Write))
 {
   resource.CopyTo(file);
 }
</code>


Check string is null or empty in linq

Question: I have string with empty space("________")
string MyNote= Convert.ToString(Session["MyNote"]);

if(MyNote!=null || MyNote != "")
{

}

MyNote != "" does not work if string has more space so
How can I check my string is "" or null  by using linq in C#?
Comment: If you really wanted to use LINQ the correct answer would have been `if (MyNote != null && MyNote.Any(c => !char.IsWhitespace(c))) ...`. But I doubt this is about LINQ.
Answer: String.IsNullOrWhiteSpace is the method you're looking for.

Indicates whether a specified string is null, empty, or consists only of white-space characters.

Alternatively, using your idea:
if(MyNote!=null && MyNote.Trim() != "")
{

}

or
if(MyNote!=null && MyNote.Trim().Length == 0)
{

}

Comment: You should change `||` into `&&`. You actually check for Is **Not** Null Or **Not** WhiteSpace. This will even throw an exception if MyNote is null.
Answer: if(MyNote!=null || MyNote.Length > 0) //or you may want to set different value than 0
{

}

Comment: And with trimming it won't work either since it throws an exception when MyNote is null.
Answer: This works for me:
 string MyNote = Session["MyNote"] == null ? String.Empty : Session["MyNote"].ToString();

Check string is null or empty in linq


Minimum posterior probability for Bayesian changepoint analysis in R

Question: I have the following data set:
Here is the sample data for this:
structure(list(V1 = c(7L, 6L, 4L, 4L, 4L, 2L, 5L, 4L, 4L, 4L,
6L, 7L, 8L, 6L, 10L, 7L, 9L, 5L, 1L, 4L, 5L, 5L, 2L, 2L, 5L,
1L, 2L, 4L, 0L, 3L, 6L, 3L, 6L, 1L, 5L, 3L, 4L, 0L, 2L, 4L)), class =
"data.frame", row.names = c(NA,
-40L))

I am using the bcp package in R to detect change points.
bcp_x <- bcp(dat$count, return.mcmc = TRUE)
plot(bcp_x)

Questions:
According to this tutorial,
https://www.marinedatascience.co/blog/2019/09/28/comparison-of-change-point-detection-methods/
at least 70% of the Posterior probability should be exceeded to be considered as a significant changepoint. In my data set I can see two peaks around 10 and 19, but probabilities are 0.4 and 0.6 respectively. How true is this minimum 70% for the Bayesian changepoint threshold?
Any thoughts on this? Maybe the Bayesian method is not appropriate for this data set? How can I determine the minimum probability to consider the peaks as significant?
I'll appreciate any thoughts on this.
Answer: In case it may be useful for those who still check this old question, here are some additional thoughts, especially to your second question: Is there an accepted method or r-package that is used for determining the optimal number of changepoints in a given a time series? First, a similar question was asked here at How to determine correct changepoints from Posterior Probabilities (bcp R package)?.
As some background information, in Bayesian inference, the number of changepoints (ncp) is not an unknown constant but a random variable by itself, so the Bayesian result will give a posterior distribution of ncp. There is no concept like optimal number of changepoints unless we further introduce a utility function to optimize. Instead, a reasonable thing to do is to just get some statistics (e.g.,  mean, mode, median, and percentiles) from the distribution of ncp, just as typically done for any probability distributions.  As I recall, bcp doesn't dump the distribution of ncp (I may be wrong). A package I developed called Rbeast (available at https://github.com/zhaokg/Rbeast) dumps the distribution of ncp, as illustrated below for your data.
Y = c(7L, 6L, 4L, 4L, 4L, 2L, 5L, 4L, 4L, 4L, 6L, 7L, 8L, 6L, 10L, 7L, 9L, 5L, 1L, 4L, 5L, 5L, 2L, 2L, 5L, 1L, 2L, 4L, 0L, 3L, 6L, 3L, 6L, 1L, 5L, 3L, 4L, 0L, 2L, 4L)

library(Rbeast)

# Rbeast does time series decompositon and changepoint detection at the same time.
# Y doesn't have any periodic/seasonal variation, so set season='none'
# By default, beast fits a linear sloped model (y=ax+b) for each segment

o = beast(Y, season='none')

# your bcp code fits a constant or flat line to each segment; this can be done
# in Rbeast by setting the min and max order of the polynomial segment to c(0,0).

o = beast(Y, season='none', torder.minmax=c(0,0))

print(o)
plot(o)

Shown below are the posterior distribution of ncp and a summary of several common statistics derived from it. In Rbeast, I used the median (ncp_median) as the default 'optimal` number of changepoints when plotting in the function plot().
#####################################################################
#                      Trend  Changepoints                          #
#####################################################################
.-------------------------------------------------------------------.
| Ascii plot of probability distribution for number of chgpts (ncp) |
.-------------------------------------------------------------------.
|Pr(ncp = 0 )=0.035|*****                                           |
|Pr(ncp = 1 )=0.174|**********************                          |
|Pr(ncp = 2 )=0.378|*********************************************** |
|Pr(ncp = 3 )=0.276|***********************************             |
|Pr(ncp = 4 )=0.107|**************                                  |
|Pr(ncp = 5 )=0.026|****                                            |
|Pr(ncp = 6 )=0.004|*                                               |
|Pr(ncp = 7 )=0.000|*                                               |
|Pr(ncp = 8 )=0.000|*                                               |
|Pr(ncp = 9 )=0.000|*                                               |
.-------------------------------------------------------------------.
|    Summary for number of Trend ChangePoints (tcp)                 |
.-------------------------------------------------------------------.
|ncp_max    = 9    | MaxTrendKnotNum: A parameter you set           |
|ncp_mode   = 2    | Pr(ncp= 2)=0.38: There is a 37.8% probability  |
|                  | that the trend component has  2 changepoint(s).|
|ncp_mean   = 2.34 | Sum{ncp*Pr(ncp)} for ncp = 0,...,9             |
|ncp_pct10  = 1.00 | 10% percentile for number of changepoints      |
|ncp_median = 2.00 | 50% percentile: Median number of changepoints  |
|ncp_pct90  = 4.00 | 90% percentile for number of changepoints      |
.-------------------------------------------------------------------.
| List of probable trend changepoints ranked by probability of      |
| occurrence: Please combine the ncp reported above to determine    |
| which changepoints below are  practically meaningful              |
'-------------------------------------------------------------------'
|tcp#              |time (cp)                  |prob(cpPr)          |
|------------------|---------------------------|--------------------|
|1                 |18.000000                  |0.72929             |
|2                 |11.000000                  |0.53813             |
|3                 |23.000000                  |0.17671             |
|4                 |31.000000                  |0.13967             |
|5                 |34.000000                  |0.13675             |
|6                 |6.000000                   |0.10292             |
.-------------------------------------------------------------------.

Additional comments on your original question:
I just want to re-iterate the excellent points made by Thomas Lumley. There is no set standard/threshold for determining the presence/absence of changepoints. In the application fields I am familiar with, the choice of the thresholds is problem-specific and, in many cases, inspired by domain expert knowledge.
Regardless, one important clarification is:  A higher peak indicates a higher chance of being a changepoint only at that particular SINGLE point in time (suppose your data is a time series) and does not necessarily mean a higher chance of observing a changepoint AROUND that time. For example, a window of posterior changepoint occurrence probability values c(0,0,0.5,0,0) (i.e., the peak prob is 0.5 and the summed prob is 0.5) is less likely to be a changepoint compared to another window c(0.1,0.2,0.21,0.2,0.1) (i.e., the peak prob is 0.21 but the summed prob is 0.71). That is, it is not reliable to check only the peak value; rather, a more reasonable metric is to look around the neighbors around the peak and use the summed prob.
Answer: That's not what the tutorial says. It says, about one example where there's an obvious changepoint

The lower posterior probability plot shows that at one location (looks
  like #28) the probability of a change is very high. We can get the
  exact locations where probabilities are high (e.g. > 70%) with this
  code:

That's not a criterion for saying there is a changepoint; it's code for finding where the changepoint is when you know it has high probability.
Typically you'd want to use a much lower threshold than 70%. Even a threshold of 50% requires that it's more likely than not that there's threshold at precisely this point. If the location of the threshold is uncertain by one or two time units it will be hard to meet a 50% probability threshold for any one time point.
In your example I would say you have evidence for two changepoints.
Comment: Thanks for the clarification. I think this line: 'The highest posterior probabilities for a change are found at location 10, 26 and 46. But only at #26 is the probability higher then 70%, which is considered the minimum to indicate a significant change.' The part with multiple changepoint.  I have another question. Is there an accepted method or r-package that is used for determining the optimal number of changepoints in a given a time series?


Does a pitcher get credited with a loss after a no-hitter with an unearned run?

Question: Let's say a pitcher is currently pitching a no-hitter: No runs, no hits, 9 innings pitch. However, his offense gets no runs and he gives up one unearned run by having a dropped ball in the outfield, and a run scores even though he gave up no earned hits or no base on balls. The pitcher's team loses the game 1-0 and that pitcher's stat line is 9IP, 0ER, 1R, 0H, 0BB. Does he still get credited with a loss?
Answer: Yes. He was the pitcher of record at the time that the other team took the lead and never relinquished it, so he gets the loss.
While this may seem unlikely, most things have happened in baseball at one time or another; depending slightly on your definition of "no hitter" there have been five instances of this since 1900 - three of those were for the away team, so the pitcher pitched only eight innings, making it not an official no hitter.


Dúvida C# Classe ADO.NET - Acessando dados de um DataTable

Question: Olá, boa noite, sou novo por aqui e um iniciante na programação C#.
Estou desenvolvendo um sistema CRUD de discos de vinil (um vicio particular hahaha), utilizando classes ADO.NET, similar ao artigo abaixo. Entretanto não estou conseguindo avançar em meu projeto rs, estou tentando realizar uma pesquisar através do nome do álbum e ou do nome do artista/banda, através de um formulário, porém não estou conseguindo obter êxito em minha pesquisa.
Segue parte do meu projeto:
1) Classe ConsultaAlbum, onde retorna um DataTable.
class ConsultaAlbum
{
    DataAccess dataAccess = new DataAccess();

    public DataTable ConsultarAlbum(string pesquisaAlbum, string pesquisaArtista)
    {
        // Limpando os parãmetros
        dataAccess.LimparParametros();
        string SQL = @"SELECT
                                       A.ID AS ID,
                                       AR.ARTISTA AS ARTISTA,
                                       GR.GRAVADORA AS GRAVADORA,
                                       A.ALBUM AS ALBUM,
                                       A.ANO AS ANO,
                                       A.GENERO AS GENERO,
                                       A.PRENSAGEM AS PRENSAGEM,
                                       A.CORVINIL AS COR,
                                       A.FORMATO AS FORMATO,
                                       A.ROTACAO ROTACAO,
                                       A.IMAGEM AS IMAGEM,
                                       A.FLAG AS FLAG
                       FROM
                                       ALBUM AS A
                                       INNER JOIN ARTISTA AS AR ON (A.ID_ARTISTA = AR.ID)
                                       INNER JOIN GRAVADORA AS GR ON (A.ID_GRAVADORA = GR.ID)
                       WHERE
                                       FLAG = 'A' AND
                                       UPPER(ALBUM) LIKE '%@PESQUISA_ALBUM%' OR
                                       UPPER(ARTISTA) LIKE'%@PESQUISA_ARTISTA%'";
        // Adicionando novos parâmetros
        dataAccess.AdicionarParametro("@PESQUISA_ALBUM", SqlDbType.VarChar, pesquisaAlbum);
        dataAccess.AdicionarParametro("@PESQUISA_ARTISTA", SqlDbType.VarChar, pesquisaArtista);
        // Retorna um DataTable com os dados da consulta
        return dataAccess.ExecutaConsulta(SQL);
    }

}
}

2)Botão Pesquisar, provavelmente aqui esta o meu problema, onde não estou conseguindo realizar a pesquisa, por não obter nenhum dado no DataTable, os dados vem de um retorno DataTable da classe acima, onde passo por parâmetro o nome do artista e ou do álbum, abaixo é um exemplo de como estou tentando realizar a pesquisa, através de um foreach e acessando suas linhas, apenas de como estou tentando realizar a pesquisa.
public partial class Consultar : UserControl
{
    DataAccess dataAccess = new DataAccess();

    public Consultar()
    {
        InitializeComponent();
    }
   private void btnPesquisarArtistaAlbum_Click(object sender, EventArgs e)
   {
        ConsultaAlbum consulta = new ConsultaAlbum();
        Album album = new Album();

        string pesquisaAlbum = "";
        string pesquisaArtista = "";

        pesquisaAlbum = txtPesquisarAlbum.Text;
        pesquisaArtista = txtPesquisarArtista.Text;

        //Pega os valores dos campos e seta nas propriedades das classes Artista, Gravadora e Album
        consulta.ConsultarAlbum(pesquisaAlbum, pesquisaArtista);

        album.Artista = txtArtista.Text;
        txtAlbum.Text = album.NomeAlbum;
        txtGenero.Text = album.Genero;
        txtPrensagem.Text = album.Prensagem;
        txtGravadora.Text = album.Gravadora;
        //Tratar exceção!!
        //album.Ano = Convert.ToInt32(txtAno.Text);
        txtCor.Text = album.Cor;
        //Tratar exceção!!
        //(rButtonLp.Checked) ? "LP" : "EP" = album.Formato;
        //(rButton33.Checked) ? "33" : "45" = album.Rotacao;
        //Falta validar imagem em branco antes de salvar !!
        pictureVinyl.ImageLocation = album.Imagem;

    }

 }
}

3) Classe Album
class Album
{
[Required]
public int Id { get; set; }

[Required(ErrorMessage = "Nome do álbum obrigatório")]
[RegularExpression(@"^[0-9a-zA-Z''''''''''''''''-''''''''\\\\\\\\\\\\\\\\s]{1,100}$", ErrorMessage = "Nome inválido")]
public string NomeAlbum { get; set; }

[RegularExpression(@"^[0-9a-zA-Z''''''''''''''''-''''''''\\\\\\\\\\\\\\\\s]{1,100}$", ErrorMessage = "Gênero inválido")]
public string Genero { get; set; }

[RegularExpression(@"^[0-9a-zA-Z''''''''''''''''-''''''''\\\\\\\\\\\\\\\\s]{1,100}$", ErrorMessage = "Prensagem inválida")]
public string Prensagem { get; set; }

[Required(ErrorMessage = "Ano do álbum obrigatório")]
[RegularExpression(@"^[0-9'-'\s]{4,4}$", ErrorMessage = "Ano inválido")]
public int Ano { get; set; }

[RegularExpression(@"^[a-zA-Z''''''''''''''''-''''''''\\\\\\\\\\\\\\\\s]{1,100}$", ErrorMessage = "Cor inválida")]
public string Cor { get; set; }

[Required]
public string Formato { get; set; }

[Required]
public string Rotacao { get; set; }

public string Imagem { get; set; }

public string Flag { get; set; }

public string Artista { get; set; }

public string Gravadora { get; set; }

}

Estou desenvolvendo esse projeto de maneira autodidata, e aprendendo muito com o que pesquiso, cursos online, artigos e dúvidas publicadas aqui no site.
Desde já, agradeço toda ajuda. obrigado =)
***Artigo utilizando para a criação da classe DataAccess ADO.NET:
https://www.devmedia.com.br/desenvolvendo-uma-classe-ado-net-para-acesso-a-dados-sql-server/32336
Comment: veja: https://pt.stackoverflow.com/a/311774/69359
Answer: Pelo que vejo a condição "WHERE" não me parece correcta.
Deveria estar "WHERE ... AND (... OR ...)"
 WHERE
      A.FLAG = 'A' AND
      (UPPER(A.ALBUM) LIKE '%@PESQUISA_ALBUM%' OR
       UPPER(AR.ARTISTA) LIKE'%@PESQUISA_ARTISTA%')";

Comment: Estou utilizando o OR, pois quero pesquisar pelo campo artista ou album, um dos dois ou os dois, ao executar o SQL no BD, o mesmo me retorna normalmente os dados, por isso que acho que o SQL não esta errado, mas irei testar tua sugestão assim que estiver em casa. Obrigado!
Answer: Provavelmente as cláusulas estão em conflito, use parâmetros para definir precedências quando houver AND e OR na mesma cláusula, caso contrário, o filtro do FLAG só funcionará em conjunto com o filtro do ALBUM mas não com o filtro do ARTISTA. Outro ponto importante é lembrar que em SQL a comparação de qualquer coisa com NULL retornará false. Então uma melhor escrita para a cláusula WHERE seria:

WHERE FLAG = 'A' AND (UPPER(ISNULL(ALBUM,'')) LIKE '%@PESQUISA_ALBUM%' OR
  UPPER(ISNULL(ARTISTA,'')) LIKE '%@PESQUISA_ARTISTA%'")

Comment: Muito obrigado, irei implementar, desde já agradeço!


Dynamic Linq 2 Sql using Expressions Trees raising exception "Binary Operator LessThan not defined for System.String and System.String"

Question: I'm trying to write a dynamic Linq 2 Sql query using Expressions trees but I'm getting a exception telling me that the LessThan and GreaterThan operators are not defined for System.String and System.String, which i find odd, is that true? or am I doing something wrong?
Expression<Func<SomeDataContextType, string>> codeSelectorExpresion =
    x => x.CodeColumn;
var row = Expression.Parameter(typeof(SomeDataContextType), "row");
var expression =
   Expression.GreaterThan(
       Expression.Invoke(codeSelectorExpression, row),
       Expression.Constant("someString", typeof(string)));
//I'm trying to build something like SomeDataContextType.CodeColumn > "someString"

Answer: Sorry, after strugling for a while i realized that the > and < operators on strings are implemented calling to string.CompareTo, so i updated the code to use the string.CompareTo method instead and it worked. Thank you anyway,
Tthe expression need to be:
var expression =
    Expression.GreaterThan(
       Expression.Call(
            Expression.Invoke(codeSelectorExpression, row),
            typeof(string).GetMethod("CompareTo", new[] {typeof(string)}),
            Expression.Constant("someString")),
       Expression.Constant(0, typeof(int)));


c++ no suitable user-defined conversion from "myClass1" to "myClass1" exists

Question: I'm very new to c++ and was really confused when this syntax error was highlighted by visual studio 2010.
Definitions
class myClass1 {
    public:
        myClass1();
}
class myClass2 {
    public:
        myClass2();
        void doSomething(myClass1 thing) {};
}

int main(int argc, char* argv[]) {
    vector<myClass1> arr;
    arr.resize(1);
    arr[0] = myClass1();
    myClass2 c2 = myClass2();
    c2.doSomething(arr[0]); //this line is being highlighted as giving the error in the title
};

I'm just really confused as to what this means.
The syntax error is at the line that i commented and it gives the error "no suitable user-defined conversion from "myClass1" to "myClass1".
Edit: sorry about not making the question clear
Comment: Post the entire (compilable) example that is showing the problem, and also show what error the compiler is giving.  While there are some things that you are doing that are "unconventional", the posted code doesn't look problematic, and in fact, fixing the obvious compilation issues (no `;` after class definitions, no definitions of the functions declared), compiles as expected.
Comment: -1 "this line is being highlighted as giving the error in the title" is wrong. the title talks about `myClass`. the code on the other hand has `myClass1` and `myClass2`, but no `myClass`.
Comment: [You didn't post the code that has the error](http://coliru.stacked-crooked.com/a/775200a346d63b5b) so we can't help you. You should read how to make a [Minimal, Reproducable Example](https://stackoverflow.com/help/minimal-reproducible-example)
Answer: The myClass* classes contain nothing/do nothing so it's kind of hard to understand your purpose.
Your code won't compile because the constructors are not defined.
You should always provide a minimum of relevant information (and not much more) in your code pastes.
To declare an instance of a myClass2 object on the stack, simply do:
myClass2 c2;

The doSomething method uses a copy of myClass1, which is probably not what you want.
The copy constructor is not defined (but there is nothing to copy).
Plus the function does nothing...
Comment: @cJZougloub You don't have to define a copy constructor in C++ - the compiler gives you a shallow copy constructor as a gift if you don't define one.
Comment: Ah true, you just didn't define a copy constructor. You should use `void doSomething(myClass1 & thing);`
Comment: @IdanArye: The default copy constructor is not always shallow.
Comment: @BenVoigt True - it does call the member fields' copy constructors if they have any.